-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtux.go
89 lines (67 loc) · 1.57 KB
/
tux.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
package tux
import (
"net"
"net/http"
"sync"
"github.com/ClarkQAQ/tux/tree"
)
type Tux struct {
*Group // 路由组
tree *tree.Tree[HandlerList] // 路由树
contextPool *sync.Pool
}
func New() *Tux {
tux := &Tux{}
tux.Group = &Group{tux, "/", nil, nil}
tux.tree = &tree.Tree[HandlerList]{}
tux.contextPool = &sync.Pool{
New: func() interface{} {
return tux.newContext()
},
}
return tux
}
func (tux *Tux) ExportRoute() []*tree.ExportValue[HandlerList] {
return tux.tree.ExportTreeMethon("")
}
func defaultNotFound(c *Context) {
c.Writer.WriteHeader(http.StatusNotFound)
c.Writer.Write([]byte("404 NOT FOUND:" + c.Req.URL.Path))
}
func (tux *Tux) Handle(c *Context) {
c.handlerList, c.vpath = tux.tree.Get(c.Req.Method + "@" + c.Req.URL.Path)
if len(c.handlerList) == 0 {
c.handlerList = append(tux.middleware, defaultNotFound)
}
c.Next()
}
func (tux *Tux) ServeHTTP(w http.ResponseWriter, req *http.Request) {
c := tux.contextPool.Get().(*Context)
defer func(t *Tux, ctx *Context) {
ctx.reset()
t.contextPool.Put(c)
}(tux, c)
c.use(w, req)
tux.Handle(c)
if c.index < -1 {
panic(nil)
}
if c.exported {
return
}
w.WriteHeader(c.Writer.status)
if _, e := w.Write(c.Writer.body.Bytes()); e != nil {
panic(e)
}
}
func (tux *Tux) ServeAddr(addr string) (*http.Server, error) {
net, e := net.Listen("tcp", addr)
if e != nil {
return nil, e
}
return tux.ServeListener(net)
}
func (tux *Tux) ServeListener(l net.Listener) (*http.Server, error) {
http := &http.Server{Handler: tux}
return http, http.Serve(l)
}