-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflex.go
74 lines (59 loc) · 1.35 KB
/
flex.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
package flex
import (
"log"
"net/http"
"sync"
)
type (
HandlerFunc func(ctx *Context) error
MiddlewareFunc func(h HandlerFunc) HandlerFunc
HttpErrHandler func(ctx *Context, err error)
Param map[string][]byte
M map[string]interface{}
)
type Flex struct {
*Router
errHandler HttpErrHandler
notFoundHandler HandlerFunc
pool sync.Pool
}
func New() *Flex {
flex := &Flex{
Router: newRouter(),
errHandler: defaultErrHandler,
notFoundHandler: defaultNotFoundHandler,
}
flex.pool.New = func() interface{} {
return flex.allocateContext()
}
return flex
}
func (flex *Flex) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
ctx := flex.pool.Get().(*Context)
ctx.reset(req, rw)
flex.handleConn(ctx)
flex.pool.Put(ctx)
}
func (flex *Flex) handleConn(ctx *Context) {
h := flex.notFoundHandler
if nd, err := flex.findRouter(ctx.Method(), ctx.Path()); err == nil {
h = nd.handler
ctx.params = nd.params
}
if err := h(ctx); err != nil {
flex.errHandler(ctx, err)
}
}
func (flex *Flex) allocateContext() *Context {
return &Context{
flex: flex,
Resp: NewResponse(nil),
}
}
func defaultErrHandler(ctx *Context, err error) {
log.Printf("error: %+v", err)
ctx.Write(400, []byte(err.Error()))
}
func defaultNotFoundHandler(ctx *Context) error {
return ctx.Write(404, []byte("page not found"))
}