-
Notifications
You must be signed in to change notification settings - Fork 0
/
blue.go
108 lines (85 loc) · 2.34 KB
/
blue.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
99
100
101
102
103
104
105
106
107
108
package blue
import (
"net/http"
)
type HandlerFunc func(ctx *Context)
type Engine struct {
methodRoutes []MethodRoute
globalMidwares []HandlerFunc
}
func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := &Context{Request: r, ResponseWriter: w, engine: e, index: -1}
e.handleRequest(c)
}
func (e *Engine) handleRequest(c *Context) {
path := c.Request.URL.Path
method := c.Request.Method
c.handlers = append(c.handlers, e.globalMidwares...)
for _, methodRoute := range e.methodRoutes {
if methodRoute.Method == method {
handler, p, _ := methodRoute.Root.getValue(path)
if handler != nil {
c.Params = p
c.handlers = append(c.handlers, handler)
c.Next()
return
}
}
}
//404
e.handle404(c)
}
func (e *Engine) handle404(c *Context) {
c.Next()
c.ResponseWriter.WriteHeader(http.StatusNotFound)
c.ResponseWriter.Write([]byte("404"))
}
func (e *Engine) Run(addr string) {
DebugLog("start listening " + addr)
http.ListenAndServe(addr, e)
}
func (e *Engine) AddRoute(method string, path string, handler HandlerFunc) {
for index, methodRoute := range e.methodRoutes {
if methodRoute.Method == method {
e.methodRoutes[index].Root.addRoute(path, handler)
return
}
}
root := new(node)
e.methodRoutes = append(e.methodRoutes, MethodRoute{Method: method, Root: root})
root.addRoute(path, handler)
}
func (e *Engine) GET(path string, handler HandlerFunc) {
e.AddRoute("GET", path, handler)
}
func (e *Engine) POST(path string, handler HandlerFunc) {
e.AddRoute("POST", path, handler)
}
func (e *Engine) DELETE(path string, handler HandlerFunc) {
e.AddRoute("DELETE", path, handler)
}
func (e *Engine) PATCH(path string, handler HandlerFunc) {
e.AddRoute("DELETE", path, handler)
}
func (e *Engine) OPTIONS(path string, handler HandlerFunc) {
e.AddRoute("DELETE", path, handler)
}
func (e *Engine) HEAD(path string, handler HandlerFunc) {
e.AddRoute("DELETE", path, handler)
}
func (e *Engine) ANY(path string, handler HandlerFunc) {
e.GET(path, handler)
e.POST(path, handler)
}
func (e *Engine) AddGlobalMidware(midware HandlerFunc) {
e.globalMidwares = append(e.globalMidwares, midware)
}
type MethodRoute struct {
Method string
Root *node
}
func NewEngine() *Engine {
e := &Engine{globalMidwares: make([]HandlerFunc, 0), methodRoutes: []MethodRoute{}}
e.AddGlobalMidware(LogMidware)
return e
}