forked from gin-gonic/gin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgin.go
330 lines (286 loc) · 10.5 KB
/
gin.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"net/http"
"sync"
)
const maxHandlerChainSize = 64
type (
HandlerChain []HandlerFunc
HandlerFunc func(*Context)
)
// last returns the last handler in the chain, it returns nil if chain is empty.
// ie. the last handler is the main own.
func (chain HandlerChain) last() HandlerFunc {
if n := len(chain); n > 0 {
return chain[n-1]
}
return nil
}
var _ http.Handler = (*Engine)(nil)
// Engine is the framework's instance, it contains the muxer, middleware and configuration settings.
// Create an instance of Engine, by using New() or Default().
//
// NOTE:
// Engine is NOT copyable.
// Please serially sets Engine(normally set in 'init' or 'main' goroutine).
type Engine struct {
RouteGroup
startChecker startChecker
contextPool sync.Pool
noRoute HandlerChain
noMethod HandlerChain
allNoRoute HandlerChain // always == combineHandlerChain(middlewares, noRoute)
allNoMethod HandlerChain // always == combineHandlerChain(middlewares, noMethod)
trees trees // point treeBuffer
treeBuffer [len(httpMethods) * 2]tree
// Enables automatic redirection if the current route can't be matched but a
// handler for the path with (without) the trailing slash exists.
// For example if /foo/ is requested but a route only exists for /foo, the
// client is redirected to /foo with http status code 301 for GET requests
// and 307 for all other request methods.
redirectTrailingSlash bool
// If enabled, the router tries to fix the current request path, if no
// handle is registered for it.
// First superfluous path elements like ../ or // are removed.
// Afterwards the router does a case-insensitive lookup of the cleaned path.
// If a handle can be found for this route, the router makes a redirection
// to the corrected path with status code 301 for GET requests and 307 for
// all other request methods.
// For example /FOO and /..//Foo could be redirected to /foo.
// redirectTrailingSlash is independent of this option.
redirectFixedPath bool
// If enabled, the router checks if another method is allowed for the
// current route, if the current request can not be routed.
// If this is the case, the request is answered with 'Method Not Allowed'
// and HTTP status code 405.
// If no other Method is allowed, the request is delegated to the NotFound
// handler.
handleMethodNotAllowed bool
}
// New returns a new blank Engine instance without any middleware attached.
// By default the configuration is:
// - RedirectTrailingSlash: true
// - RedirectFixedPath: false
// - HandleMethodNotAllowed: false
func New() *Engine {
debugPrintEngineNew()
engine := &Engine{
redirectTrailingSlash: true,
redirectFixedPath: false,
handleMethodNotAllowed: false,
}
engine.RouteGroup.basePath = "/"
engine.RouteGroup.engine = engine
engine.contextPool.New = contextPoolNew
engine.trees = engine.treeBuffer[:0]
return engine
}
func contextPoolNew() interface{} { return new(Context) }
func (engine *Engine) addRoute(method, path string, handlers HandlerChain) {
if method == "" {
panic("http method can not be empty")
}
if path == "" || path[0] != '/' {
panic("path must begin with '/'")
}
if len(handlers) == 0 {
panic("there must be at least one handler")
}
// each handler in handlers is valid, see function combineHandlerChain.
engine.startChecker.check() // check if engine has been started.
debugPrintRoute(method, path, handlers)
root := engine.trees.getTree(method)
if root == nil {
root = new(node)
engine.trees = engine.trees.addTree(method, root)
}
root.addRoute(path, handlers)
}
// Routes returns a slice of registered routes, including some useful information, such as:
// the http method, path and the handler name.
func (engine *Engine) Routes() (routes []Route) {
return engine.trees.routes()
}
// Attachs a global middleware to Engine. ie. the middleware attached though Use() will be
// included in the handler chain for every single request. Even 404, 405, static files...
// For example, this is the right place for a logger or error management middleware.
func (engine *Engine) Use(middleware ...HandlerFunc) {
engine.startChecker.check()
engine.RouteGroup.Use(middleware...)
engine.rebuild404Handlers()
engine.rebuild405Handlers()
}
// NoRoute set handlers for NoRoute. It return a 404 code by default.
func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
engine.startChecker.check()
engine.noRoute = handlers
engine.rebuild404Handlers()
}
func (engine *Engine) rebuild404Handlers() {
engine.allNoRoute = combineHandlerChain(engine.middlewares, engine.noRoute)
}
// NoRoute set handlers for NoMethod. It return a 405 code by default.
func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
engine.startChecker.check()
engine.noMethod = handlers
engine.rebuild405Handlers()
}
func (engine *Engine) rebuild405Handlers() {
engine.allNoMethod = combineHandlerChain(engine.middlewares, engine.noMethod)
}
// Enables automatic redirection if the current route can't be matched but a
// handler for the path with (without) the trailing slash exists.
// For example if /foo/ is requested but a route only exists for /foo, the
// client is redirected to /foo with http status code 301 for GET requests
// and 307 for all other request methods.
//
// Default is true.
func (engine *Engine) RedirectTrailingSlash(b bool) {
engine.startChecker.check()
engine.redirectTrailingSlash = b
}
// If enabled, the router tries to fix the current request path, if no
// handle is registered for it.
// First superfluous path elements like ../ or // are removed.
// Afterwards the router does a case-insensitive lookup of the cleaned path.
// If a handle can be found for this route, the router makes a redirection
// to the corrected path with status code 301 for GET requests and 307 for
// all other request methods.
// For example /FOO and /..//Foo could be redirected to /foo.
// RedirectTrailingSlash is independent of this option.
//
// Default is false.
func (engine *Engine) RedirectFixedPath(b bool) {
engine.startChecker.check()
engine.redirectFixedPath = b
}
// If enabled, the router checks if another method is allowed for the
// current route, if the current request can not be routed.
// If this is the case, the request is answered with 'Method Not Allowed'
// and HTTP status code 405.
// If no other Method is allowed, the request is delegated to the NotFound
// handler.
//
// Default is false.
func (engine *Engine) HandleMethodNotAllowed(b bool) {
engine.startChecker.check()
engine.handleMethodNotAllowed = b
}
// =====================================================================================================================
// Run attaches the engine to a http.Server and starts listening and serving HTTP requests.
// It is a shortcut for http.ListenAndServe(addr, engine)
// Note: this method will block the calling goroutine undefinitelly unless an error happens.
func (engine *Engine) Run(addr string) (err error) {
engine.startChecker.start()
defer func() { debugPrintError(err) }()
debugPrint("Listening and serving HTTP on %s\r\n", addr)
return http.ListenAndServe(addr, engine)
}
// RunTLS attaches the engine to a http.Server and starts listening and serving HTTPS (secure) requests.
// It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, engine)
// Note: this method will block the calling goroutine undefinitelly unless an error happens.
func (engine *Engine) RunTLS(addr string, certFile string, keyFile string) (err error) {
engine.startChecker.start()
defer func() { debugPrintError(err) }()
debugPrint("Listening and serving HTTPS on %s\r\n", addr)
return http.ListenAndServeTLS(addr, certFile, keyFile, engine)
}
// ServeHTTP implements the http.Handler interface.
func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
engine.startChecker.start()
ctx := engine.contextPool.Get().(*Context)
defer engine.contextPool.Put(ctx)
ctx.reset()
ctx.ResponseWriter.reset(w)
ctx.Request = r
engine.serveHTTP(ctx)
}
func (engine *Engine) serveHTTP(ctx *Context) {
httpMethod := ctx.Request.Method
path := ctx.Request.URL.Path
// find root of the tree for the given HTTP method
root := engine.trees.getTree(httpMethod)
if root != nil {
// find route in tree
handlers, params, tsr := root.getValue(path, ctx.Params)
if handlers != nil {
ctx.handlers = handlers
ctx.Params = params
ctx.Next()
return
}
if httpMethod != HttpMethodConnect && path != "/" {
if tsr && engine.redirectTrailingSlash {
redirectTrailingSlash(ctx)
return
}
if engine.redirectFixedPath && redirectFixedPath(ctx, root, engine.redirectTrailingSlash) {
return
}
}
}
// Handle 405
if engine.handleMethodNotAllowed {
trees := engine.trees
for i := 0; i < len(trees); i++ {
if trees[i].method == httpMethod {
continue // Skip the requested method - we already tried this one
}
if handlers, _, _ := trees[i].root.getValue(path, ctx.Params); handlers != nil {
ctx.handlers = engine.allNoMethod
serveError(ctx, 405, default405Body)
return
}
}
}
// Handle 404
ctx.handlers = engine.allNoRoute
serveError(ctx, 404, default404Body)
}
var (
default404Body = []byte("404 page not found")
default405Body = []byte("405 method not allowed")
)
func serveError(ctx *Context, defaultCode int, defaultMessage []byte) {
ctx.Next()
if w := ctx.ResponseWriter; !w.WroteHeader() {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(defaultCode)
w.Write(defaultMessage)
}
}
func redirectTrailingSlash(ctx *Context) {
req := ctx.Request
path := req.URL.Path // path != "/"
code := 301
if req.Method != HttpMethodGet {
code = 307
}
if len(path) > 1 && path[len(path)-1] == '/' {
req.URL.Path = path[:len(path)-1]
} else {
req.URL.Path = path + "/"
}
debugPrint("redirecting request %d: %s --> %s\r\n", code, path, req.URL.Path)
http.Redirect(ctx.ResponseWriter, req, req.URL.String(), code)
}
func redirectFixedPath(ctx *Context, root *node, fixTrailingSlash bool) bool {
req := ctx.Request
path := req.URL.Path // path != "/"
fixedPath, found := root.findCaseInsensitivePath(pathClean(path), fixTrailingSlash)
if found {
code := 301
if req.Method != HttpMethodGet {
code = 307
}
req.URL.Path = string(fixedPath)
debugPrint("redirecting request %d: %s --> %s\r\n", code, path, req.URL.Path)
http.Redirect(ctx.ResponseWriter, req, req.URL.String(), code)
return true
}
return false
}