-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
202 lines (136 loc) · 3.65 KB
/
router.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package goroot
import (
"log"
"net/http"
"regexp"
"strings"
"github.com/rootspyro/goroot/cors"
"github.com/rootspyro/goroot/pages"
)
type Router struct {
//Base Node
node *Node
// Cors Configuration
cors *cors.Cors
// Global Middlewares
middlewares *[]Middleware
//Html rendering config
pages *pages.Pages
notFound Handler
}
type Node struct {
path string
actions map[string]*Handler
children map[string]*Node
}
func(router *Router)findHandler(path, method string, root *Root) (Handler, bool, bool) {
currentNode := router.node
if path != "/" {
for _, label := range router.explodePath(path) {
nextNode, exists := currentNode.children[label]
if !exists {
if currentNode.path == label {
break
} else {
// Boolean value for search if exists an children with a parameter as path. Example = /{userID}
foundedParam := false
for path, node := range currentNode.children {
if router.isParameter(path) {
foundedParam = true
root.RequestParams[router.clearParam(path)] = label
currentNode = node
break
}
}
if foundedParam {
// if node exists and has children then continue
if len(currentNode.children) > 0 {
continue
} else {
break
}
} else {
// 404
return nil, false, false
}
}
}
currentNode = nextNode
continue
}
}
handler, exists := currentNode.actions[method]
if !exists {
if len(currentNode.actions) == 0 {
return nil, false, false
}
return nil, true, false
}
return *handler, true, true
}
func(router *Router)ServeHTTP(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
// CORS
w.Header().Set("Access-Control-Allow-Origin", router.cors.ValidateOrigin(origin))
w.Header().Set("Access-Control-Allow-Methods", router.cors.AllowedMethods())
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization")
if r.Method == "OPTIONS" {
return
}
// End CORS
reqPath := r.URL.Path
// global request log
if origin == "" {
origin = r.Host
}
log.Printf("%s:%s - %s", r.Method, reqPath, origin)
rootHandler := &Root{
writter: w,
request: r,
RequestParams: make(map[string]string),
pages: router.pages,
}
// Search if the path exists
handler, pathExists, methodExists := router.findHandler(reqPath, r.Method, rootHandler)
// If path don't exists returns 404 not found
if !pathExists {
router.notFound(rootHandler)
return
}
// If path exists but not the method then returns 405 method not allowed
if !methodExists {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
// Assign the global middlewares
handler = router.SetGlobalMiddlewares(handler)
handler(rootHandler)
}
// assign the list of middlewares to the handler
func(router *Router) SetGlobalMiddlewares(handler Handler) Handler {
for _, midd := range *router.middlewares {
handler = midd(handler)
}
return handler
}
// This function split the path and removes any empty value
func(router *Router) explodePath(path string) []string {
pathList := strings.Split(path, "/")
var labels []string
for _, str := range pathList {
if str != "" {
labels =append(labels, str)
}
}
return labels
}
// Validate if an string is a path parameter like /user/{userId}
func(router *Router) isParameter(str string) bool {
re := regexp.MustCompile("{([^}]+)}")
match := re.MatchString(str)
return match
}
// Remove the keys "{}" from a path parameter. clearParam("{userId}") returns "userId"
func(router *Router) clearParam(str string) string {
return strings.Trim(str, "{}")
}