-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandle.go
66 lines (61 loc) · 1.42 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
62
63
64
65
66
package web
import (
"net/http"
"strings"
)
type handle struct {
Routers []*router
notAllow handleFunc
notFound handleFunc
staticService handleFunc
}
//函数结构体 无返回值
type handleFunc func(*Controller)
//control router
func (h handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := &Controller{
Response: w,
Request: r,
Result: make(map[string]interface{}),
Internal: make(map[string]interface{}),
}
handle, status, isFile := h.match(r)
if isFile {
h.staticService(c)
return
}
if status == http.StatusOK {
handle(c)
Logs.Info("%s %s", r.Method, r.URL)
return
}
if status == http.StatusNotFound {
h.notFound(c)
Logs.Info("%s %s Not Found", r.Method, r.URL)
return
}
if status == http.StatusMethodNotAllowed {
Logs.Info("%s %s 404", r.Method, r.URL)
h.notAllow(c)
return
}
return
}
//根据请求找对应的handleFunc
func (h handle) match(r *http.Request) (handleFunc, int, bool) {
method := r.Method
path := strings.ToLower(r.URL.Path)
for _, router := range h.Routers {
if router.isFile && strings.HasPrefix(path, router.uri) {
return router.handle, http.StatusOK, true
}
if path == router.uri {
if router.method == "" || in(method, strings.ToUpper(router.method)) {
return router.handle, http.StatusOK, false
} else {
return router.handle, http.StatusMethodNotAllowed, false
}
}
}
return nil, http.StatusNotFound, false
}