-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
134 lines (105 loc) · 2.52 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
package main
import (
"net/http"
"strings"
)
type RouterHandler = func(*Context, func())
const Any = ""
type RouterEntry struct {
method string
path string
pathRange bool
handlers []RouterHandler
next *RouterEntry
}
type Router struct {
head *RouterEntry
foot *RouterEntry
}
func NewRouter() *Router {
return &Router{}
}
func (r *Router) Next(ctx *Context, next func()) {
for entry := r.head; entry != nil; entry = entry.next {
if len(entry.handlers) == 0 {
continue
}
if entry.method != "" && entry.method != ctx.req.Method {
continue
}
if entry.path != "" && entry.path != ctx.req.URL.Path {
if entry.pathRange {
match := entry.path
if !strings.HasSuffix(match, "/") {
match = match + "/"
}
if !strings.HasPrefix(ctx.req.URL.Path, match) {
continue
}
} else {
continue
}
}
doContinue := false
for _, handler := range entry.handlers {
doContinue = false
handler(ctx, func() {
doContinue = true
})
if !doContinue {
break
}
}
if !doContinue {
break
}
}
next()
}
func (r *Router) Handle(method string, path string, handlers ...RouterHandler) {
if len(handlers) > 0 {
entry := &RouterEntry{
path: path,
method: method,
handlers: handlers,
}
if r.foot == nil {
r.head = entry
r.foot = entry
} else {
r.foot.next = entry
r.foot = entry
}
}
}
func (r *Router) Use(path string, handlers ...RouterHandler) {
r.Handle("", path, handlers...)
r.foot.pathRange = true
}
func (r *Router) Get(path string, handlers ...RouterHandler) {
r.Handle(http.MethodGet, path, handlers...)
}
func (r *Router) Head(path string, handlers ...RouterHandler) {
r.Handle(http.MethodHead, path, handlers...)
}
func (r *Router) Post(path string, handlers ...RouterHandler) {
r.Handle(http.MethodPost, path, handlers...)
}
func (r *Router) Put(path string, handlers ...RouterHandler) {
r.Handle(http.MethodPut, path, handlers...)
}
func (r *Router) Patch(path string, handlers ...RouterHandler) {
r.Handle(http.MethodPatch, path, handlers...)
}
func (r *Router) Delete(path string, handlers ...RouterHandler) {
r.Handle(http.MethodDelete, path, handlers...)
}
func (r *Router) Connect(path string, handlers ...RouterHandler) {
r.Handle(http.MethodConnect, path, handlers...)
}
func (r *Router) Options(path string, handlers ...RouterHandler) {
r.Handle(http.MethodOptions, path, handlers...)
}
func (r *Router) Trace(path string, handlers ...RouterHandler) {
r.Handle(http.MethodTrace, path, handlers...)
}