-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
201 lines (176 loc) · 4.72 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
package main
import (
"context"
"fmt"
"net/http"
"strings"
)
// Access path variables in handler:
//
// func handler(w http.ResponseWriter, r *http.Request) {
// if vars, ok := r.Context().Value("pathvars").(map[string]string); ok {
// fmt.Println(vars["{id}"])
// fmt.Println(vars["{name}"])
// }
// }
type Router struct {
endpoints PartNode
}
func NewRouter() Router {
router := Router{}
router.endpoints = PartNode{}
return router
}
var supportedMethods = []string{
http.MethodGet,
http.MethodPost,
http.MethodPut,
http.MethodDelete,
}
func (rtr *Router) Get(pattern string, handler func(http.ResponseWriter, *http.Request)) {
rtr.bindHandler(http.MethodGet, pattern, handler)
}
func (rtr *Router) Post(pattern string, handler func(http.ResponseWriter, *http.Request)) {
rtr.bindHandler(http.MethodPost, pattern, handler)
}
func (rtr *Router) Put(pattern string, handler func(http.ResponseWriter, *http.Request)) {
rtr.bindHandler(http.MethodPut, pattern, handler)
}
func (rtr *Router) Delete(pattern string, handler func(http.ResponseWriter, *http.Request)) {
rtr.bindHandler(http.MethodDelete, pattern, handler)
}
func (rtr *Router) bindHandler(method, pattern string, handler func(http.ResponseWriter, *http.Request)) {
//if _, ok := rtr.endpoints.Find(patternToKeys(method, pattern)); ok {
// return
//}
if rtr.wasBoundBefore(pattern) {
rtr.endpoints.InsertChain(patternToKeys(method, pattern), handler)
} else {
rtr.endpoints.InsertChain(patternToKeys(method, pattern), handler)
rtr.bindProcess(pattern)
}
}
// Generated by GPT-3.5
//
// Examples:
//
// Input: GET "/some/path/route/"
// Output: ["GET", "/", "some", "/", "path", "/", "route", "/"]
// Input: GET "/some/path/route"
// Output: ["GET", "/", "some", "/", "path", "/", "route"]
// Input: GET "/"
// Output: ["GET", "/"]
// Input: GET ""
// Output: ["GET"]
func patternToKeys(method, pattern string) []string {
parts := strings.Split(pattern, "/")
result := make([]string, 0, len(parts)*2+1)
result = append(result, method)
for _, part := range parts {
if part != "" {
result = append(result, "/")
result = append(result, part)
}
}
if pattern != "" && strings.HasSuffix(pattern, "/") {
result = append(result, "/")
}
return result
}
func (rtr *Router) wasBoundBefore(pattern string) bool {
var wasBound bool
for _, method := range supportedMethods {
if _, ok := rtr.endpoints.Find(patternToKeys(method, pattern)); ok {
wasBound = true
}
}
return wasBound
}
func (rtr *Router) bindProcess(pattern string) {
http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
if endpointNodes, ok := rtr.endpoints.Find(patternToKeys(r.Method, r.URL.Path)); ok {
pathvars := parsePathVars(patternToKeys(r.Method, r.URL.Path), endpointNodes)
r = r.WithContext(context.WithValue(r.Context(), "pathvars", pathvars))
endpointNodes[len(endpointNodes)-1].Val(w, r)
} else {
w.WriteHeader(http.StatusNotFound)
}
})
}
func parsePathVars(reqParts []string, nodes []*PartNode) map[string]string {
res := map[string]string{}
for i, part := range reqParts[1:] {
if isPathVar(nodes[i+1].Key) {
res[nodes[i+1].Key] = part
}
}
return res
}
// PartNode is type used to build Tree(Trie) of Route parts
type PartNode struct {
Key string
Val func(http.ResponseWriter, *http.Request) `json:"-"`
Childs map[string]*PartNode
}
func (p *PartNode) String() string {
return fmt.Sprintf("%s %p %s", p.Key, p.Val, p.Childs)
}
func (p *PartNode) InsertChain(keyChain []string, val func(http.ResponseWriter, *http.Request)) {
curr := p
for _, key := range keyChain[:len(keyChain)-1] {
curr = curr.Insert(&PartNode{Key: key})
}
curr.Insert(&PartNode{
Key: keyChain[len(keyChain)-1],
Val: val,
})
}
func (p *PartNode) Len() int {
return len(p.Childs)
}
func (p *PartNode) Insert(node *PartNode) *PartNode {
if p.Childs == nil {
p.Childs = make(map[string]*PartNode)
}
if child, ok := p.Childs[node.Key]; ok {
if node.Val != nil {
child.Val = node.Val
}
return child
} else {
p.Childs[node.Key] = node
return node
}
}
// Examples:
//
// Input: ["GET", "/", "apiroute", "/", "{pathvar}"]
// Output: [Node1, Node2, Node3, Node4, Node5], true
func (p *PartNode) Find(keys []string) ([]*PartNode, bool) {
start := p
hasFound := false
resPath := make([]*PartNode, 0, 3)
for _, key := range keys {
if n, ok := start.Childs[key]; ok {
hasFound = true
resPath = append(resPath, n)
start = n
} else if start.Len() > 0 {
hasFound = false
for k, v := range start.Childs {
if isPathVar(k) {
hasFound = true
resPath = append(resPath, v)
start = v
}
}
} else {
hasFound = false
break
}
}
return resPath, hasFound
}
func isPathVar(key string) bool {
return strings.HasPrefix(key, "{")
}