-
Notifications
You must be signed in to change notification settings - Fork 1
/
shared.go
122 lines (97 loc) · 2.5 KB
/
shared.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package trinity
import (
"net/http"
"reflect"
"strings"
)
var (
Post = method("POST")
Get = method("GET")
Put = method("PUT")
Delete = method("DELETE")
Head = method("HEAD")
emptyController = Controller("")
emptyAction = Action("")
emptyValues = make([]reflect.Value, 0)
)
type httpHandler func(response http.ResponseWriter, request *http.Request) ActionResultInterface
type Controller string
type Action string
type method string
func C(s string) Controller {
return Controller(s)
}
func A(s string) Action {
return Action(s)
}
// Checks whether controller equals s. Case insensitive
func (c Controller) EqualsS(s string) bool {
logger.Debugf("c.EqualsS %v == %s", c, s)
return strings.ToLower(s) == strings.ToLower(string(c))
}
// Checks whether action equals s. Case insensitive
func (a Action) EqualsS(s string) bool {
logger.Debugf("a.EqualsS %v == %s", a, s)
return strings.ToLower(s) == strings.ToLower(string(a))
}
// Pair of controller and action
type ControllerAction struct {
C Controller
A Action
}
// Returns true if both controller and action are not empty
func (ca *ControllerAction) IsFull() bool {
return ca.C != emptyController && ca.A != emptyAction
}
func toLowerA(a Action) Action {
return Action(strings.ToLower(string(a)))
}
func toLowerC(c Controller) Controller {
return Controller(strings.ToLower(string(c)))
}
func createURL(c Controller, a Action, params map[string]string) string {
url := "/" + string(c) + "/" + string(a)
query := ""
if params != nil {
for k, v := range params {
if len(query) != 0 {
query += "&"
}
query += k + "=" + v
}
}
if len(query) != 0 {
url += "?" + query
}
return url
}
func parseURL(url string) (c Controller, a Action) {
logger.Trace("")
if len(url) == 0 {
return
}
pathParts := strings.Split(url[1:], "/")
if len(pathParts) > 0 {
c = Controller(pathParts[0])
}
if len(pathParts) > 1 {
a = Action(pathParts[1])
}
return
}
func traceParamValue(paramValue reflect.Value) {
logger.Tracef("paramValue: Type.Name= %v Kind= %v", paramValue.Type().Name(), paramValue.Kind())
}
func traceParamType(paramType reflect.Type) {
logger.Tracef("paramType: Name= %v Kind= %v", paramType.Name(), paramType.Kind())
}
func stripPrefix(prefix string, h http.Handler, nf http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.HasPrefix(r.URL.Path, prefix) {
nf.ServeHTTP(w, r)
return
}
r.URL.Path = r.URL.Path[len(prefix):]
h.ServeHTTP(w, r)
})
}