Repository navigation
Expand file tree
/
Copy pathdweb.go
More file actions
68 lines (56 loc) · 1.45 KB
/
Copy pathdweb.go
File metadata and controls
68 lines (56 loc) · 1.45 KB
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
package dweb
import (
"html/template"
"log"
"net/http"
"strings"
"time"
)
type engine struct {
groups []*routerGroup
topRouterGroup *routerGroup
htmlTemplate *template.Template
funcMap template.FuncMap
}
type HandlerFunc func(c *Context)
func New() *engine {
tg := GenTopRouterGroup()
e := engine{topRouterGroup: tg}
e.groups = append(e.groups, tg)
return &e
}
func (e *engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := newContext(w, r)
for _, g := range e.groups {
if strings.HasPrefix(r.URL.Path, g.prefix) {
c.handlers = append(c.handlers, g.middlewares...)
}
}
e.topRouterGroup.router.handle(c)
}
func (e *engine) Run(port string) {
log.Fatal(http.ListenAndServe(port, e))
}
func (e *engine) TopRouterGroup() *routerGroup {
return e.topRouterGroup
}
func (e *engine) GenerateAndRecordRouterGroup(parent *routerGroup, prefix string) *routerGroup {
newGroup := parent.Group(prefix)
e.groups = append(e.groups, newGroup)
return newGroup
}
func (e *engine) LoadHTMLGlob(pattern string) {
e.htmlTemplate = template.Must(template.New("").Funcs(e.funcMap).ParseGlob(pattern))
}
// Default middleware
func Logger(c *Context) {
t := time.Now()
c.Yield()
log.Printf("[%d] %s in %v", c.StatusCode, c.r.RequestURI, time.Since(t))
}
func (e *engine) TemplateFor(name string) *template.Template {
return e.htmlTemplate.Lookup(name)
}
func (e *engine) SetFuncMap(funcMap template.FuncMap) {
e.funcMap = funcMap
}