-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.go
62 lines (51 loc) · 1.27 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
package rest
import (
"net/http"
"path"
"sync"
)
type enginez struct {
// routerz 实现路由搜索添加的功能
*routerz
// 挂载在引擎上的全局中间件
middlewares []HandlerFunc
// 用于取用 Context 实例
pool sync.Pool
}
func newEnginez() *enginez {
e := &enginez{
routerz: newRouterz(),
}
e.pool.New = func() interface{} {
return e.allocateContext()
}
return e
}
func (e *enginez) addRoute(method, path string, handler HandlerFunc) error {
return e.routerz.addRoute(method, path, handler)
}
func (e *enginez) search(method, path string) (HandlerFunc, error) {
return e.routerz.search(method, path)
}
func (e *enginez) use(middlewares ...HandlerFunc) {
for _, m := range middlewares {
e.middlewares = append(e.middlewares, m)
}
}
func (e *enginez) ServeHTTP(w http.ResponseWriter, req *http.Request) {
reqPath := path.Clean(req.URL.Path)
h, _ := e.search(req.Method, reqPath)
// TODO need check method and path is ok
// means u should check search func called err result
// core code
// 1. get ctx from pool
ctx := e.pool.Get().(Context)
// 2. reset the ctx
ctx.init(w, req)
ctx.setHandlers(append(e.middlewares, h)...)
// 3. pass ctx to handler and run it
ctx.Next()
}
func (e *enginez) allocateContext() Context {
return newContext()
}