forked from vardius/gorouter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nethttp.go
281 lines (225 loc) · 6.36 KB
/
nethttp.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
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package gorouter
import (
"net/http"
"net/url"
"strings"
"github.com/ceriath/gorouter/v4/context"
"github.com/ceriath/gorouter/v4/middleware"
"github.com/ceriath/gorouter/v4/mux"
pathutils "github.com/ceriath/gorouter/v4/path"
)
var allNethttpMethods = []string{
http.MethodGet,
http.MethodHead,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
http.MethodConnect,
http.MethodOptions,
http.MethodTrace,
}
// New creates new net/http Router instance, returns pointer
func New(fs ...MiddlewareFunc) Router {
globalMiddleware := transformMiddlewareFunc(fs...)
r := &router{
tree: mux.NewTree(),
globalMiddleware: globalMiddleware,
}
r.handler = globalMiddleware.Compose(http.HandlerFunc(r.serveHTTP)).(http.Handler)
return r
}
type router struct {
tree mux.Tree
globalMiddleware middleware.Collection
fileServer http.Handler
notFound http.Handler
notAllowed http.Handler
handler http.Handler
middlewareCounter uint
}
func (r *router) PrettyPrint() string {
return r.tree.PrettyPrint()
}
func (r *router) POST(p string, f http.Handler) {
r.Handle(http.MethodPost, p, f)
}
func (r *router) GET(p string, f http.Handler) {
r.Handle(http.MethodGet, p, f)
}
func (r *router) PUT(p string, f http.Handler) {
r.Handle(http.MethodPut, p, f)
}
func (r *router) DELETE(p string, f http.Handler) {
r.Handle(http.MethodDelete, p, f)
}
func (r *router) PATCH(p string, f http.Handler) {
r.Handle(http.MethodPatch, p, f)
}
func (r *router) OPTIONS(p string, f http.Handler) {
r.Handle(http.MethodOptions, p, f)
}
func (r *router) HEAD(p string, f http.Handler) {
r.Handle(http.MethodHead, p, f)
}
func (r *router) CONNECT(p string, f http.Handler) {
r.Handle(http.MethodConnect, p, f)
}
func (r *router) TRACE(p string, f http.Handler) {
r.Handle(http.MethodTrace, p, f)
}
func (r *router) USE(method, path string, fs ...MiddlewareFunc) {
m := transformMiddlewareFunc(fs...)
for i, mf := range m {
m[i] = middleware.WithPriority(mf, r.middlewareCounter)
}
r.tree = r.tree.WithMiddleware(method+path, m, 0)
r.middlewareCounter += uint(len(m))
}
func (r *router) USEANY(path string, fs ...MiddlewareFunc) {
m := transformMiddlewareFunc(fs...)
for i, mf := range m {
m[i] = middleware.WithPriority(mf, r.middlewareCounter)
}
for _, method := range allNethttpMethods {
r.tree = r.tree.WithMiddleware(method+path, m, 0)
}
r.middlewareCounter += uint(len(m))
}
func (r *router) Handle(method, path string, h http.Handler) {
route := newRoute(h)
r.tree = r.tree.WithRoute(method+path, route, 0)
}
func (r *router) Mount(path string, h http.Handler) {
pathRewrite := newPathSlashesStripper(strings.Count(path, "/"))
route := newRoute(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, pathRewrite(r))
}))
for _, method := range allNethttpMethods {
r.tree = r.tree.WithSubrouter(method+path, route, 0)
}
}
func (r *router) Compile() {
for i, methodNode := range r.tree {
r.tree[i].WithChildren(methodNode.Tree().Compile())
}
}
func (r *router) NotFound(notFound http.Handler) {
r.notFound = notFound
}
func (r *router) NotAllowed(notAllowed http.Handler) {
r.notAllowed = notAllowed
}
func (r *router) ServeFiles(fs http.FileSystem, root string, strip bool) {
if root == "" {
panic("gorouter.ServeFiles: empty root!")
}
handler := http.FileServer(fs)
if strip {
handler = http.StripPrefix("/"+root+"/", handler)
}
r.fileServer = handler
}
func (r *router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.handler.ServeHTTP(w, req)
}
func (r *router) serveHTTP(w http.ResponseWriter, req *http.Request) {
var path string
if root := r.tree.Find(req.Method); root != nil {
var h http.Handler
if req.URL.Path == "/" {
if root.Route() != nil && root.Route().Handler() != nil {
if r.middlewareCounter > 0 {
computedHandler := root.Middleware().Sort().Compose(root.Route().Handler())
h = computedHandler.(http.Handler)
} else {
h = root.Route().Handler().(http.Handler)
}
h.ServeHTTP(w, req)
return
}
} else {
path = pathutils.TrimSlash(req.URL.Path)
if route, params := root.Tree().MatchRoute(path); route != nil {
if r.middlewareCounter > 0 {
var allMiddleware middleware.Collection
if treeMiddleware := root.Tree().MatchMiddleware(path); len(treeMiddleware) > 0 {
allMiddleware = root.Middleware().Merge(treeMiddleware).Sort()
} else {
allMiddleware = root.Middleware().Sort()
}
computedHandler := allMiddleware.Compose(route.Handler())
h = computedHandler.(http.Handler)
} else {
h = route.Handler().(http.Handler)
}
if len(params) > 0 {
req = req.WithContext(context.WithParams(req.Context(), params))
}
h.ServeHTTP(w, req)
return
}
}
}
path = pathutils.TrimSlash(req.URL.Path)
// Handle file serve
if req.Method == http.MethodGet && r.fileServer != nil {
r.fileServer.ServeHTTP(w, req)
return
}
// Handle OPTIONS
if allow := allowed(r.tree, req.Method, path); len(allow) > 0 {
w.Header().Set("Allow", allow)
if req.Method == http.MethodOptions {
return
}
// Handle 405
r.serveNotAllowed(w, req)
return
}
// Handle 404
r.serveNotFound(w, req)
}
func (r *router) serveNotFound(w http.ResponseWriter, req *http.Request) {
if r.notFound != nil {
r.notFound.ServeHTTP(w, req)
} else {
http.NotFound(w, req)
}
}
func (r *router) serveNotAllowed(w http.ResponseWriter, req *http.Request) {
if r.notAllowed != nil {
r.notAllowed.ServeHTTP(w, req)
} else {
http.Error(w,
http.StatusText(http.StatusMethodNotAllowed),
http.StatusMethodNotAllowed,
)
}
}
func transformMiddlewareFunc(fs ...MiddlewareFunc) middleware.Collection {
m := make(middleware.Collection, len(fs))
for i, f := range fs {
m[i] = func(mf MiddlewareFunc) middleware.WrapperFunc {
return func(h middleware.Handler) middleware.Handler {
return mf(h.(http.Handler))
}
}(f) // f is a reference to function so we have to wrap if with that callback
}
return m
}
func newPathSlashesStripper(stripSlashes int) func(r *http.Request) *http.Request {
return func(r *http.Request) *http.Request {
r2 := new(http.Request)
*r2 = *r
r2.URL = new(url.URL)
*r2.URL = *r.URL
p := pathutils.StripLeadingSlashes(r.URL.Path, stripSlashes)
if p != "" {
r2.URL.Path = p
} else {
r2.URL.Path = "/"
}
return r2
}
}