forked from xujiajun/gorouter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.go
More file actions
267 lines (217 loc) · 6.66 KB
/
router.go
File metadata and controls
267 lines (217 loc) · 6.66 KB
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package gorouter
import (
"context"
"fmt"
"net/http"
"regexp"
"strings"
)
var (
defaultPattern = `[\w]+`
idPattern = `[\d]+`
idKey = `id`
)
type (
// middlewareType is a private type that is used for middleware
middlewareType func(next http.HandlerFunc) http.HandlerFunc
// Router is a simple HTTP route multiplexer that parses a request path,
// records any URL params, and executes an end handler.
Router struct {
prefix string
// The middleware stack
middleware []middlewareType
// the tree routers
trees map[string]*Tree
// Custom route not found handler
notFound http.HandlerFunc
}
)
// New returns a newly initialized Router object that implements the Router
func New() *Router {
return &Router{
trees: make(map[string]*Tree),
}
}
// GET adds the route `path` that matches a GET http method to
// execute the `handle` http.HandlerFunc.
func (router *Router) GET(path string, handle http.HandlerFunc) {
router.Handle(http.MethodGet, path, handle)
}
// POST adds the route `path` that matches a POST http method to
// execute the `handle` http.HandlerFunc.
func (router *Router) POST(path string, handle http.HandlerFunc) {
router.Handle(http.MethodPost, path, handle)
}
// DELETE adds the route `path` that matches a DELETE http method to
// execute the `handle` http.HandlerFunc.
func (router *Router) DELETE(path string, handle http.HandlerFunc) {
router.Handle(http.MethodDelete, path, handle)
}
// PUT adds the route `path` that matches a PUT http method to
// execute the `handle` http.HandlerFunc.
func (router *Router) PUT(path string, handle http.HandlerFunc) {
router.Handle(http.MethodPut, path, handle)
}
// PATCH adds the route `path` that matches a PATCH http method to
// execute the `handle` http.HandlerFunc.
func (router *Router) PATCH(path string, handle http.HandlerFunc) {
router.Handle(http.MethodPatch, path, handle)
}
// Group define routes groups If there is a path prefix that use `prefix`
func (router *Router) Group(prefix string) *Router {
return &Router{
prefix: prefix,
trees: router.trees,
middleware: router.middleware,
}
}
// NotFoundFunc registers a handler when the request route is not found
func (router *Router) NotFoundFunc(handler http.HandlerFunc) {
router.notFound = handler
}
// Handle registers a new request handle with the given path and method.
func (router *Router) Handle(method string, path string, handle http.HandlerFunc) {
if method == "" {
panic(fmt.Errorf("invalid method"))
}
if router.trees == nil {
router.trees = make(map[string]*Tree)
}
root := router.trees[method]
if root == nil {
root = NewTree()
router.trees[method] = root
}
if router.prefix != "" {
path = router.prefix + "/" + path
}
root.Add(path, handle, router.middleware...)
}
// GetParam return route param stored in r.
func GetParam(r *http.Request, key string) string {
return GetAllParams(r)[key]
}
// contextKeyType is a private struct that is used for storing values in net.Context
type contextKeyType struct{}
// contextKey is the key that is used to store values in the net.Context for each request
var contextKey = contextKeyType{}
// paramsMapType is a private type that is used to store route params
type paramsMapType map[string]string
// GetAllParams return all route params stored in r.
func GetAllParams(r *http.Request) paramsMapType {
values, ok := r.Context().Value(contextKey).(paramsMapType)
if ok {
return values
}
return paramsMapType{}
}
// ServeHTTP makes the router implement the http.Handler interface.
func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
requestUrl := r.URL.Path
nodes := router.trees[r.Method].Find(requestUrl, 0)
for _, node := range nodes {
handler := node.handle
path := node.path
if handler != nil {
if path == requestUrl {
handle(w, r, handler, node.middleware)
return
}
if path == requestUrl[1:] {
handle(w, r, handler, node.middleware)
return
}
}
}
if nodes == nil {
res := strings.Split(requestUrl, "/")
prefix := res[1]
nodes := router.trees[r.Method].Find(prefix, 1)
for _, node := range nodes {
handler := node.handle
if handler != nil && node.path != requestUrl {
if matchParamsMap, ok := router.matchAndParse(requestUrl, node.path); ok {
ctx := context.WithValue(r.Context(), contextKey, matchParamsMap)
r = r.WithContext(ctx)
handle(w, r, handler, node.middleware)
return
}
}
}
}
router.HandleNotFound(w, r, router.middleware)
}
// Use appends a middleware handler to the middleware stack.
func (router *Router) Use(middleware ...middlewareType) {
if len(middleware) > 0 {
router.middleware = append(router.middleware, middleware...)
}
}
// HandleNotFound registers a handler when the request route is not found
func (router *Router) HandleNotFound(w http.ResponseWriter, r *http.Request, middleware []middlewareType) {
if router.notFound != nil {
handle(w, r, router.notFound, middleware)
return
}
http.NotFound(w, r)
}
// handle execute middleware chain
func handle(w http.ResponseWriter, r *http.Request, handler http.HandlerFunc, middleware []middlewareType) {
var baseHandler = handler
for _, m := range middleware {
baseHandler = m(baseHandler)
}
baseHandler(w, r)
}
// Match check if the request match the route Pattern
func (router *Router) Match(requestUrl string, path string) bool {
_, ok := router.matchAndParse(requestUrl, path)
return ok
}
// matchAndParse check if the request matches the route path and returns a map of the parsed
func (router *Router) matchAndParse(requestUrl string, path string) (paramsMapType, bool) {
res := strings.Split(path, "/")
if res == nil {
return nil, false
}
var (
matchName []string
sTemp string
)
matchParams := make(paramsMapType)
for _, str := range res {
if str != "" {
r := []byte(str)
if string(r[0]) == "{" && string(r[len(r)-1]) == "}" {
matchStr := string(r[1 : len(r)-1])
res := strings.Split(matchStr, ":")
matchName = append(matchName, res[0])
sTemp = sTemp + "/" + "(" + res[1] + ")"
} else if string(r[0]) == ":" {
matchStr := string(r)
res := strings.Split(matchStr, ":")
matchName = append(matchName, res[1])
if res[1] == idKey {
sTemp = sTemp + "/" + "(" + idPattern + ")"
} else {
sTemp = sTemp + "/" + "(" + defaultPattern + ")"
}
} else {
sTemp = sTemp + "/" + str
}
}
}
pattern := sTemp
re := regexp.MustCompile(pattern)
submatch := re.FindSubmatch([]byte(requestUrl))
if submatch != nil {
if string(submatch[0]) == requestUrl {
submatch = submatch[1:]
for k, v := range submatch {
matchParams[matchName[k]] = string(v)
}
return matchParams, true
}
}
return nil, false
}