-
Notifications
You must be signed in to change notification settings - Fork 0
/
cat.go
80 lines (65 loc) · 1.93 KB
/
cat.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
package cat
import (
"html/template"
"net/http"
"strings"
)
// HandlerFunc defines the request handler used by cat
type HandlerFunc func(ctx *Context)
// Engine implement the interface of ServeHTTP
type Engine struct {
*RouteGroup
router *router
groups []*RouteGroup // store all groups
// html
htmlTemplates *template.Template
funcMap template.FuncMap
}
// New is the constructor of cat.Engine
func New() *Engine {
engine := &Engine{router: newRouter()}
engine.RouteGroup = &RouteGroup{
engine: engine,
}
engine.groups = []*RouteGroup{engine.RouteGroup}
return engine
}
// Default use Logger() & Recovery middlewares
func Default() *Engine {
engine := New()
engine.Use(Logger(), Recovery())
return engine
}
func (engine *Engine) SetFuncMap(funcMap template.FuncMap) {
engine.funcMap = funcMap
}
func (engine *Engine) LoadHTMLGlob(pattern string) {
engine.htmlTemplates = template.Must(template.New("").Funcs(engine.funcMap).ParseGlob(pattern))
}
func (engine *Engine) addRoute(method string, pattern string, handler HandlerFunc) {
engine.router.addRoute(method, pattern, handler)
}
// GET defines the method to add GET request
func (engine *Engine) GET(pattern string, handler HandlerFunc) {
engine.addRoute(http.MethodGet, pattern, handler)
}
// POST defines the method to add POST request
func (engine *Engine) POST(pattern string, handler HandlerFunc) {
engine.addRoute(http.MethodPost, pattern, handler)
}
// Run defines the method to start a http server
func (engine *Engine) Run(addr string) (err error) {
return http.ListenAndServe(addr, engine)
}
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
var middlewares = make([]HandlerFunc, 0)
for _, group := range engine.groups {
if strings.HasPrefix(req.URL.Path, group.prefix) {
middlewares = append(middlewares, group.middlewares...)
}
}
c := newContext(w, req)
c.handlers = middlewares
c.engine = engine
engine.router.handle(c)
}