-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandle.go
61 lines (55 loc) · 1.82 KB
/
handle.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
package xhttp
import (
xerr "github.com/goclub/error"
"github.com/gorilla/mux"
"net/http"
"strings"
)
type HandleFunc func(c *Context) (err error)
func (serve *Router) HandleFunc(route Route, handler HandleFunc) {
coreHandleFunc(serve, serve.router, route, handler)
}
func (group *Group) HandleFunc(route Route, handler HandleFunc) {
coreHandleFunc(group.serve, group.router, route, handler)
}
func (serve *Router) NetHttpHandleFunc(path string, handler func(w http.ResponseWriter, r *http.Request)) {
serve.router.HandleFunc(path, handler)
}
func (group *Group) NetHttpHandleFunc(path string, handler func(w http.ResponseWriter, r *http.Request)) {
group.router.HandleFunc(path, handler)
}
func coreHandleFunc(serve *Router, router *mux.Router, route Route, handler HandleFunc) {
if route.Path == "" {
panic(xerr.New("goclub/http: HandleFunc(route) route.Path can not be empty string"))
}
if strings.HasPrefix(route.Path, "/") == false {
route.Path = "/" + route.Path
xerr.PrintStack(xerr.New("goclub/http: HandleFunc(route) route.Path must has prefix /"))
}
serve.patterns = append(serve.patterns, route)
router.HandleFunc(route.Path, func(w http.ResponseWriter, r *http.Request) {
c := NewContext(w, r, serve)
defer func() {
r := recover()
if r != nil {
c.CheckPanic(r)
return
}
}()
err := handler(c)
if err != nil {
c.CheckError(err)
return
}
}).Methods(route.Method.String())
}
func (serve *Router) Handle(path string, handler http.Handler) {
coreHandle(serve, serve.router, path, handler)
}
func (group *Group) Handle(path string, handler http.Handler) {
coreHandle(group.serve, group.router, path, handler)
}
func coreHandle(serve *Router, router *mux.Router, path string, handler http.Handler) {
serve.patterns = append(serve.patterns, Route{"*", path})
router.Handle(path, handler)
}