-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute.go
88 lines (75 loc) · 1.91 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
88
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package coap
import (
"strings"
)
type RouteCallback func(req *Message) *Message
type routeEntry struct {
children map[string]*routeEntry
key string
callback RouteCallback
}
func (s *Server) AddRoute(path string, callback RouteCallback) {
if path == "/" {
routeMap := s.routes
routeMap["*"] = &routeEntry{children: map[string]*routeEntry{}, callback: callback}
return
}
pathParts := strings.Split(path, "/")
var route *routeEntry
var found bool
routeMap := s.routes
for idx, part := range pathParts {
if len(part) == 0 {
continue
}
var key string
if part[0] == '{' {
key = part[1 : len(part)-1]
part = "*"
}
if route, found = routeMap[part]; found {
if idx == len(pathParts)-1 {
route.callback = callback
} else {
routeMap = route.children
}
} else {
if idx == len(pathParts)-1 {
route = &routeEntry{children: map[string]*routeEntry{}, callback: callback, key: key}
} else {
route = &routeEntry{children: map[string]*routeEntry{}, key: key}
}
routeMap[part] = route
routeMap = route.children
}
}
return
}
func (s *Server) matchRoutes(msg *Message) RouteCallback {
pathParts := strings.Split(msg.PathString(), "/")
var route *routeEntry
var found bool
routeMap := s.routes
var deepestCallback RouteCallback
for _, part := range pathParts {
if route, found = routeMap[part]; found {
deepestCallback = route.callback
routeMap = route.children
} else {
if route, found = routeMap["*"]; found {
deepestCallback = route.callback
if msg.PathVars == nil {
msg.PathVars = map[string]string{}
}
routeMap = route.children
msg.PathVars[route.key] = part
} else {
break
}
}
}
return deepestCallback
}