-
Notifications
You must be signed in to change notification settings - Fork 1
/
route.go
87 lines (80 loc) · 1.97 KB
/
route.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 viot
import(
"sync"
"regexp"
"fmt"
"path"
"strings"
)
type Route struct{
HandlerError func(w ResponseWriter, r *Request)
rt sync.Map // 路由表 map[string]
}
//HandleFunc 绑定处理函数,匹配的网址支持正则,这说明你要严格的检查。
// url string 网址,支持正则匹配
// handler func(w ResponseWriter, r *Request) 处理函数
func (T *Route) HandleFunc(url string, handler func(w ResponseWriter, r *Request)){
if handler == nil {
T.rt.Delete(url)
return
}
T.rt.Store(url, HandlerFunc(handler))
}
//ServeIOT 服务IOT
// w ResponseWriter 响应
// r *Request 请求
func (T *Route) ServeIOT(w ResponseWriter, r *Request){
upath := r.URL.Path
inf, ok := T.rt.Load(r.URL.Path)
if ok {
inf.(Handler).ServeIOT(w, r)
if upath == r.URL.Path {
return
}
}else{
var handleFunc Handler
T.rt.Range(func(k, v interface{}) bool {
pattern := k.(string)
//正则
if strings.HasPrefix(pattern, "^") || strings.HasSuffix(pattern, "$") {
regexpRegexp, err := regexp.Compile(pattern)
if err != nil {
return true
}
_, complete := regexpRegexp.LiteralPrefix()
if !complete {
regexpRegexp.Longest()
if regexpRegexp.MatchString(r.URL.Path) {
ok = true
handleFunc = v.(Handler)
return false
}
}
return true
}
//通配符
matched, _ := path.Match(pattern, r.URL.Path)
if matched {
ok = true
handleFunc = v.(Handler)
return false
}
return true
});
if ok {
handleFunc.ServeIOT(w, r)
if upath == r.URL.Path {
return
}
}
}
//处理错误的请求
if T.HandlerError != nil {
T.HandlerError(w, r)
return
}
//默认的错误处理
w.Status(404)
w.Header().Set("Connection","close")
w.SetBody(fmt.Sprintf("The path does not exist %s", upath))
}