-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
105 lines (89 loc) · 2.59 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
package orange
import "github.com/julienschmidt/httprouter"
import "net/http"
// Router
type Router struct {
app *App
handlerFuncs []HandlerFunc
prefix string
}
// Use: add middlewares
func (r *Router) Use(middlewares ...HandlerFunc) {
r.handlerFuncs = append(r.handlerFuncs, middlewares...)
}
// GET: handle GET method
func (r *Router) GET(path string, handlers ...HandlerFunc) {
r.Handle("GET", path, handlers)
}
// POST: handle POST method
func (r *Router) POST(path string, handlers ...HandlerFunc) {
r.Handle("POST", path, handlers)
}
// PATCH: handle PATCH method
func (r *Router) PATCH(path string, handlers ...HandlerFunc) {
r.Handle("PATCH", path, handlers)
}
// PUT: handle PUT method
func (r *Router) PUT(path string, handlers ...HandlerFunc) {
r.Handle("PUT", path, handlers)
}
// DELETE: handle DELETE method
func (r *Router) DELETE(path string, handlers ...HandlerFunc) {
r.Handle("DELETE", path, handlers)
}
// HEAD: handle HEAD method
func (r *Router) HEAD(path string, handlers ...HandlerFunc) {
r.Handle("HEAD", path, handlers)
}
// OPTIONS: handle OPTIONS method
func (r *Router) OPTIONS(path string, handlers ...HandlerFunc) {
r.Handle("OPTIONS", path, handlers)
}
// Controller: add sub router as controller
func (r *Router) Controller(path string, handlers ...HandlerFunc) *Router {
handlers = r.mergeHandlers(handlers)
return &Router{
handlerFuncs: handlers,
prefix: r.path(path),
app: r.app,
}
}
// HandlerFunc: convert http.HandlerFunc to app.HandlerFunc
func (r *Router) HTTPHandlerFunc(h http.HandlerFunc) HandlerFunc {
return func(ctx *Context) {
h(ctx.response, ctx.request)
}
}
// Handle : handle with specific method
func (r *Router) Handle(method, path string, handlers []HandlerFunc) {
handlers = r.mergeHandlers(handlers)
r.app.httprouter.Handle(method, r.path(path), func(rw http.ResponseWriter, req *http.Request, params httprouter.Params) {
ctx := r.app.newContext(rw, req)
ctx.params = params
ctx.handlerFuncs = handlers
ctx.Next()
r.app.pool.Put(ctx)
})
}
// path: get new path
func (r *Router) path(p string) string {
if r.prefix == "/" {
return p
}
return stringConcat(r.prefix, p)
}
// mergeHandlers: merge new handlers function to existing
func (r *Router) mergeHandlers(handlers []HandlerFunc) []HandlerFunc {
aLen := len(r.handlerFuncs)
hLen := len(handlers)
h := make([]HandlerFunc, aLen+hLen)
copy(h, r.handlerFuncs)
for i := 0; i < hLen; i++ {
h[aLen+i] = handlers[i]
}
return h
}
// ServceHttp
func (r *Router) ServeHTTP(res http.ResponseWriter, req *http.Request) {
r.app.httprouter.ServeHTTP(res, req)
}