-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengine.go
211 lines (170 loc) · 4.41 KB
/
engine.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
package water
import (
"net/http"
"sync"
"time"
"github.com/meilihao/logx"
)
type Handler interface {
ServeHTTP(*Context)
}
type HandlerFunc func(*Context)
func (f HandlerFunc) ServeHTTP(ctx *Context) {
f(ctx)
}
// support http.Handler, but not recommended
func newHandler(handler interface{}) Handler {
switch h := handler.(type) {
case Handler:
return h
case func(*Context):
return HandlerFunc(h)
case http.Handler:
return HandlerFunc(func(ctx *Context) {
h.ServeHTTP(ctx, ctx.Request)
})
case func(http.ResponseWriter, *http.Request):
return HandlerFunc(func(ctx *Context) {
h(ctx, ctx.Request)
})
default:
panic("unsupported handler")
}
}
func newHandlers(handlers []interface{}) (a []Handler) {
n := len(handlers)
a = make([]Handler, n)
for i, h := range handlers {
a[i] = newHandler(h)
}
return a
}
// WrapHandlerFunc wrap func to HandlerFunc
func WrapHandler(handler interface{}) Handler {
return newHandler(handler)
}
// // BeforeHandler represents a handler executes at beginning of every request(before HandlerFuncs).
// // Water stops future process when it returns true.
// type BeforeHandler func(http.ResponseWriter, *http.Request) bool
// --- water ---
type Engine struct {
*options
rootRouter *Router
routers [8]*node
routersStatic [8]map[string]*node
routeStore *routeStore
ctxPool sync.Pool
}
func newWater() *Engine {
e := &Engine{
routers: [8]*node{},
routersStatic: [8]map[string]*node{},
}
e.ctxPool.New = func() interface{} {
return newContext()
}
return e
}
func (e *Engine) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if !req.ProtoAtLeast(1, 1) || req.RequestURI == "*" || req.Method == "CONNECT" {
rw.WriteHeader(http.StatusNotAcceptable)
return
}
index := MethodIndex(req.Method)
if index < 0 {
rw.WriteHeader(http.StatusMethodNotAllowed)
return
}
ctx := e.ctxPool.Get().(*Context)
ctx.reset()
ctx.ResponseWriter = rw.(ResponseWriter)
ctx.Request = req
// fast match for static routes
if e.options.EnableStaticRouter {
ctx.endNode = e.routersStatic[index][req.URL.Path]
}
if ctx.endNode == nil {
// curl http://localhost:8081 or http://localhost:8081/ -> req.URL.Path=="/"
ctx.endNode, ctx.Params = e.routers[index].Match(req.URL.Path)
}
if ctx.endNode == nil {
if len(e.options.NoFoundHandlers) != 0 {
ctx.handlers = e.options.NoFoundHandlers
} else {
ctx.WriteHeader(http.StatusNotFound)
e.ctxPool.Put(ctx)
return
}
} else {
ctx.handlers = ctx.endNode.handlers
}
ctx.Environ = make(Environ)
ctx.handlersLength = len(ctx.handlers)
ctx.run()
e.ctxPool.Put(ctx)
}
// Run start web service
// Deprecated: please use Run()
func (e *Engine) ListenAndServe(addr string) error {
return http.ListenAndServe(addr, e)
}
// Run start web service with tls
// Deprecated: please use RunTLS()
func (e *Engine) ListenAndServeTLS(addr, certFile, keyFile string) error {
return http.ListenAndServeTLS(addr, certFile, keyFile, e)
}
// Run start web service
// defualt port is ":8080"
func (e *Engine) Run(addr ...string) error {
wantAddr := resolveAddress(addr)
return http.ListenAndServe(wantAddr, e)
}
// Run start web service with tls
func (e *Engine) RunTLS(addr, certFile, keyFile string) error {
return http.ListenAndServeTLS(addr, certFile, keyFile, e)
}
func (e *Engine) buildTree() {
var endNode *node
for _, v := range e.routeStore.routeSlice {
if t := e.routers[MethodIndex(v.method)]; t != nil {
endNode = t.add(v.variantUri, v.handlers)
} else {
t := newTree()
endNode = t.add(v.variantUri, v.handlers)
e.routers[MethodIndex(v.method)] = t
}
if e.options.EnableStaticRouter && isStaticRoute(endNode) {
if e.routersStatic[MethodIndex(v.method)] == nil {
e.routersStatic[MethodIndex(v.method)] = map[string]*node{}
}
e.routersStatic[MethodIndex(v.method)][v.variantUri] = endNode
}
endNode.matchNode = v
}
}
// 向上递归检查是否为static route
func isStaticRoute(node *node) bool {
if node == nil {
return true
}
if node.typ != _PATTERN_STATIC {
return false
}
return isStaticRoute(node.parent)
}
// handle log before invoke Logger()
// 处理调用Logger()前的日志
func (e *Engine) log(status int, req *http.Request) {
if LogClose {
return
}
start := time.Now()
logx.Infof("%s |%s| %13v | %16s | %7s %s",
logPrefix(req),
logStatus(status),
time.Now().Sub(start),
requestRealIp(req),
req.Method,
req.URL.String(),
)
}