-
Notifications
You must be signed in to change notification settings - Fork 0
/
goweb.go
97 lines (83 loc) · 1.7 KB
/
goweb.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
/**
* @Author: dsreshiram@gmail.com
* @Date: 2022/7/16 下午 04:30
*/
package goweb
import (
"context"
"net/http"
"sync"
)
type GOweb struct {
RouterGroup
noRouter HandlerFunc
context.Context
}
var (
// 内存优化
contextPool = sync.Pool{
New: func() any {
return new(Context)
},
}
)
func (g *GOweb) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
c, cancel := context.WithCancel(g.Context)
ctx := contextPool.Get().(*Context)
ctx.Request = request
ctx.Writer = writer
ctx.Context = c
ctx.cancel = cancel
match, handleFunc, grep := g.PathMatch(request.RequestURI, request.Method)
if handleFunc == nil {
g.handler404(ctx)
return
}
ctx.param = match
handleFuncOrder := grep.order
gp := grep
for gp != nil {
for i := range gp.middlewares {
// 中间件只覆盖顺序靠后的路由
if gp.middlewares[i].order < handleFuncOrder {
ctx.runFunc(gp.middlewares[i].HandlerFunc)
}
}
gp = gp.parent
}
ctx.runFunc(handleFunc)
//
gp = grep
for gp != nil {
for i := range gp.footMiddle {
// 中间件只覆盖顺序靠后的路由
if gp.footMiddle[i].order < handleFuncOrder {
ctx.runFunc(gp.footMiddle[i].HandlerFunc)
}
}
gp = gp.parent
}
ctx.Stop()
contextPool.Put(ctx)
}
func (g *GOweb) NoRoute(handlerFunc HandlerFunc) {
g.noRouter = handlerFunc
}
func (g *GOweb) handler404(ctx *Context) {
if g.noRouter != nil {
g.noRouter(ctx)
} else {
http.NotFound(ctx.Writer, ctx.Request)
}
}
func New() (g *GOweb) {
g = new(GOweb)
g.Context = context.Background()
return
}
func (g *GOweb) SetValue(key, value any) {
g.Context = context.WithValue(g.Context, key, value)
}
func (g *GOweb) GetValue(key any) any {
return g.Value(key)
}