-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb.go
69 lines (56 loc) · 1.58 KB
/
web.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
package framework
import (
"html/template"
"net/http"
"strings"
)
type HandlerFunc func(*Context)
type Engine struct {
*RouterGroup
router *router
groups []*RouterGroup
htmlTemplates *template.Template
funcMap template.FuncMap
}
func New() *Engine {
engine := &Engine{router: newRouter()}
engine.RouterGroup = &RouterGroup{engine: engine}
engine.groups = []*RouterGroup{engine.RouterGroup}
return engine
}
func (e *Engine) addRoute(method string, pattern string, handler HandlerFunc) {
e.router.addRoute(method, pattern, handler)
}
func (e *Engine) GET(pattern string, handler HandlerFunc) {
e.addRoute("GET", pattern, handler)
}
func (e *Engine) POST(pattern string, handler HandlerFunc) {
e.addRoute("POST", pattern, handler)
}
func (e *Engine) PUT(pattern string, handler HandlerFunc) {
e.addRoute("PUT", pattern, handler)
}
func (e *Engine) DELETE(pattern string, handler HandlerFunc) {
e.addRoute("DELETE", pattern, handler)
}
func (e *Engine) Run(addr string) error {
return http.ListenAndServe(addr, e)
}
func (e *Engine) SetFuncMap(funcMap template.FuncMap) {
e.funcMap = funcMap
}
func (e *Engine) LoadHTMLGlob(pattern string) {
e.htmlTemplates = template.Must(template.New("").Funcs(e.funcMap).ParseGlob(pattern))
}
func (e *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
var middleware []HandlerFunc
for _, group := range e.groups {
if strings.HasPrefix(req.URL.Path, group.prefix) {
middleware = append(middleware, group.middleware...)
}
}
c := newContext(w, req)
c.handlers = middleware
c.engine = e
e.router.handler(c)
}