-
Notifications
You must be signed in to change notification settings - Fork 5
/
router.go
53 lines (42 loc) · 1.38 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
package xingyun
import (
"net/http"
"github.com/gorilla/mux"
)
type Router interface {
Handle(pattern string, h ContextHandler)
HandleFunc(pattern string, h ContextHandlerFunc)
Get(pattern string, h ContextHandlerFunc)
Post(pattern string, h ContextHandlerFunc)
ServeHTTP(w http.ResponseWriter, r *http.Request)
}
type router struct {
router *mux.Router
afterRoute PipeHandler
}
func newRouter(afterRoute PipeHandler) *router {
gorillaRouter := mux.NewRouter()
gorillaRouter.KeepContext = true
gorillaRouter.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
})
return &router{router: gorillaRouter, afterRoute: afterRoute}
}
func (r *router) getWrapHandler(h ContextHandlerFunc) http.Handler {
return ToHTTPHandlerFunc(Wrap(r.afterRoute, h))
}
func (r *router) Get(path string, h ContextHandlerFunc) {
r.router.Handle(path, r.getWrapHandler(h)).Methods("GET")
}
func (r *router) Post(path string, h ContextHandlerFunc) {
r.router.Handle(path, r.getWrapHandler(h)).Methods("POST")
}
func (r *router) Handle(path string, h ContextHandler) {
r.router.Handle(path, r.getWrapHandler(h.ServeContext))
}
func (r *router) HandleFunc(path string, h ContextHandlerFunc) {
r.router.HandleFunc(path, r.getWrapHandler(h).ServeHTTP)
}
func (r *router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.router.ServeHTTP(w, req)
}