/
ghttp_server_router_middleware.go
72 lines (65 loc) · 2.04 KB
/
ghttp_server_router_middleware.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
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package ghttp
import (
"context"
"reflect"
"github.com/gogf/gf/v2/debug/gdebug"
)
const (
// The default route pattern for global middleware.
defaultMiddlewarePattern = "/*"
)
// BindMiddleware registers one or more global middleware to the server.
// Global middleware can be used standalone without service handler, which intercepts all dynamic requests
// before or after service handler. The parameter `pattern` specifies what route pattern the middleware intercepts,
// which is usually a "fuzzy" pattern like "/:name", "/*any" or "/{field}".
func (s *Server) BindMiddleware(pattern string, handlers ...HandlerFunc) {
var (
ctx = context.TODO()
)
for _, handler := range handlers {
s.setHandler(ctx, setHandlerInput{
Prefix: "",
Pattern: pattern,
HandlerItem: &HandlerItem{
Type: HandlerTypeMiddleware,
Name: gdebug.FuncPath(handler),
Info: handlerFuncInfo{
Func: handler,
Type: reflect.TypeOf(handler),
},
},
})
}
}
// BindMiddlewareDefault registers one or more global middleware to the server using default pattern "/*".
// Global middleware can be used standalone without service handler, which intercepts all dynamic requests
// before or after service handler.
func (s *Server) BindMiddlewareDefault(handlers ...HandlerFunc) {
var (
ctx = context.TODO()
)
for _, handler := range handlers {
s.setHandler(ctx, setHandlerInput{
Prefix: "",
Pattern: defaultMiddlewarePattern,
HandlerItem: &HandlerItem{
Type: HandlerTypeMiddleware,
Name: gdebug.FuncPath(handler),
Info: handlerFuncInfo{
Func: handler,
Type: reflect.TypeOf(handler),
},
},
})
}
}
// Use is the alias of BindMiddlewareDefault.
// See BindMiddlewareDefault.
func (s *Server) Use(handlers ...HandlerFunc) {
s.BindMiddlewareDefault(handlers...)
}