-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandle.go
98 lines (84 loc) · 2.5 KB
/
handle.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
package ming
import (
"fmt"
"strings"
"github.com/valyala/fasthttp"
)
func (r *Router) Handle(method, path string, handler fasthttp.RequestHandler) {
if !strings.HasPrefix(path, "/") {
panic("path must begin with \"/\" in \"" + path + "\"")
}
r.trees.Add(&Node{
method: method,
path: path,
handler: handler,
})
}
func (r *Router) Handler(ctx *fasthttp.RequestCtx) {
if r.PanicHandler != nil {
defer r.recv(ctx)
}
path := string(ctx.Path())
method := GetMethod(ctx)
if nodeFindByPath := r.trees.FindPath(path); nodeFindByPath.Len() != 0 {
if node := nodeFindByPath.FindMethod(method); node != nil {
handler := node.GetHandler()
handler(ctx)
} else {
if node := nodeFindByPath.GetMethodAll(); node != nil {
handler := node.GetHandler()
handler(ctx)
} else {
if r.MethodNotAllowed != nil {
r.MethodNotAllowed(ctx)
} else {
ctx.Error("method not allowed", fasthttp.StatusMethodNotAllowed)
}
}
}
} else {
if r.NotFound != nil {
r.NotFound(ctx)
} else {
ctx.Error(fmt.Sprintf("%s %s not found", method, path), fasthttp.StatusNotFound)
}
}
}
func (r *Router) Get(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodGet, path, handler)
}
func (r *Router) Head(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodHead, path, handler)
}
func (r *Router) Post(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodPost, path, handler)
}
func (r *Router) Put(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodPut, path, handler)
}
func (r *Router) Patch(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodPatch, path, handler)
}
func (r *Router) Delete(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodDelete, path, handler)
}
func (r *Router) Connect(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodConnect, path, handler)
}
func (r *Router) Options(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodOptions, path, handler)
}
func (r *Router) Trace(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodTrace, path, handler)
}
func (r *Router) All(path string, handler fasthttp.RequestHandler) {
r.Handle("ALL", path, handler)
}
func (r *Router) Static(rootPath string, IsIndexPage bool) {
fs := &fasthttp.FS{
Root: rootPath,
IndexNames: []string{"index.html"},
GenerateIndexPages: IsIndexPage,
}
r.NotFound = fs.NewRequestHandler()
}