-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple.go
66 lines (55 loc) · 1.19 KB
/
simple.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
package simple
import (
"net/http"
"strings"
)
type Simple struct {
*group
groups []*group
}
func Default() *Simple {
s := New()
s.Use(Logger(), Recovery())
return s
}
func New() *Simple {
s := &Simple{}
g := &group{
prefix: "",
router: newRouter(),
simple: s,
middleware: make(HandlersChain, 0),
}
s.group = g
s.groups = []*group{g}
return s
}
func (s *Simple) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var middlewares []HandlerFunc
for _, group := range s.groups {
if strings.HasPrefix(r.URL.Path, group.prefix) {
middlewares = append(middlewares, group.middleware...)
}
}
context := newContext(w, r)
context.handlers = middlewares
s.handler(context)
}
func (s *Simple) Run(addr string, callback func()) error {
callback()
return http.ListenAndServe(addr, s)
}
func (s *Simple) handler(c *Context) {
node := s.router.getRoute(c.Method, c.Path)
if node == nil {
c.handlers = append(c.handlers, func(c *Context) {
c.Status(http.StatusNotFound).
String("%s: %s", http.StatusText(http.StatusNotFound), c.Path)
})
goto Next
}
c.Params = node.parseParams(c.Path)
c.handlers = append(c.handlers, node.handlers...)
Next:
c.Next()
}