-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
87 lines (69 loc) · 2.1 KB
/
router.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
package mohttp
import (
"net/http"
"github.com/julienschmidt/httprouter"
"golang.org/x/net/context"
)
var setRouter, getRouter = ContextValueAccessors("github.com/jonasi/mohttp.Router")
var notFoundHandler = HandlerFunc(func(c context.Context) {
GetResponseWriter(c).WriteHeader(http.StatusNotFound)
})
var methodNotAllowedHandler = HandlerFunc(func(c context.Context) {
GetResponseWriter(c).WriteHeader(http.StatusMethodNotAllowed)
})
func GetRouter(c context.Context) (*Router, bool) {
r, ok := getRouter(c).(*Router)
return r, ok
}
func NewRouter() *Router {
r := &Router{
router: httprouter.New(),
}
r.use = []Handler{
setRouter(r),
}
r.HandleNotFound(notFoundHandler)
r.HandleMethodNotAllowed(methodNotAllowedHandler)
return r
}
type Router struct {
router *httprouter.Router
use []Handler
}
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.router.ServeHTTP(w, req)
}
func (r *Router) Handle(method, path string, handlers ...Handler) {
r.router.Handle(method, path, func(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
h := append(append([]Handler{}, r.use...), handlers...)
c := HTTPContext(w, req, p)
Serve(c, h...)
})
}
func (r *Router) Use(h ...Handler) {
r.use = append(r.use, h...)
}
func (r *Router) Register(routes ...Route) {
for _, rt := range routes {
r.Handle(rt.Method(), rt.Path(), rt.Handlers()...)
}
}
func (r *Router) RegisterHTTPHandler(method, path string, h http.Handler) {
r.router.Handle(method, path, func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
h.ServeHTTP(w, r)
})
}
func (r *Router) HandleNotFound(h ...Handler) {
r.router.NotFound = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
handlers := append(append([]Handler{}, r.use...), h...)
c := HTTPContext(w, req, nil)
Serve(c, handlers...)
})
}
func (r *Router) HandleMethodNotAllowed(h ...Handler) {
r.router.MethodNotAllowed = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
handlers := append(append([]Handler{}, r.use...), h...)
c := HTTPContext(w, req, nil)
Serve(c, handlers...)
})
}