forked from caicloud/nirvana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
method.go
78 lines (67 loc) · 2.48 KB
/
method.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
Copyright 2017 Caicloud Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package service
import (
"net/http"
"github.com/caicloud/nirvana/definition"
)
// statusMapping contains a binding of HTTP method and success status code.
type statusMapping struct {
// HTTPMethod is HTTP method.
HTTPMethod string
// Code means a success status code.
Code int
}
var mappings = map[definition.Method]statusMapping{
definition.List: {http.MethodGet, http.StatusOK},
definition.Get: {http.MethodGet, http.StatusOK},
definition.Create: {http.MethodPost, http.StatusCreated},
definition.Update: {http.MethodPut, http.StatusOK},
definition.Patch: {http.MethodPatch, http.StatusOK},
definition.Delete: {http.MethodDelete, http.StatusNoContent},
definition.AsyncCreate: {http.MethodPost, http.StatusAccepted},
definition.AsyncUpdate: {http.MethodPost, http.StatusAccepted},
definition.AsyncPatch: {http.MethodPatch, http.StatusAccepted},
definition.AsyncDelete: {http.MethodDelete, http.StatusAccepted},
}
// HTTPMethodFor gets a HTTP method for specified definition method.
func HTTPMethodFor(m definition.Method) string {
return mappings[m].HTTPMethod
}
// HTTPCodeFor gets a success status code for specified definition method.
func HTTPCodeFor(m definition.Method) int {
return mappings[m].Code
}
// RegisterMethod registers a HTTP method and a success status code for a definition method.
func RegisterMethod(method definition.Method, httpMethod string, code int) error {
validHTTPMethod := []string{http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut,
http.MethodPatch, http.MethodDelete, http.MethodConnect, http.MethodOptions, http.MethodTrace}
found := false
for _, m := range validHTTPMethod {
if m == httpMethod {
found = true
break
}
}
if !found {
return invalidMethod.Error(httpMethod)
}
if code < 100 || code >= 600 {
return invalidStatusCode.Error()
}
mappings[method] = statusMapping{
Code: code,
HTTPMethod: httpMethod,
}
return nil
}