-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
58 lines (45 loc) · 886 Bytes
/
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
54
55
56
57
58
package tgbcr
import (
"strings"
)
type Router struct {
Collection struct {
Childs []Child
}
}
type HandlerFunc func(Context)
type Child struct {
Path string
Handler HandlerFunc
}
func New() *Router {
return &Router{}
}
func (r *Router) Handle(path string, handler HandlerFunc) {
if path == "" {
panic("Path must not be empty")
}
if path[0] != '/' {
panic("Path must start with \"/\"")
}
if len(path) < 2 {
panic("Path must have at least single charactor to match")
}
r.Collection.Childs = append(r.Collection.Childs, Child{
Path: path,
Handler: handler,
})
}
func (r *Router) Dispatch(text string, context Context) {
/**
* Sanitize and extract the command string from
* the provided text string
*/
path := strings.Fields(text)[0]
for _, e := range r.Collection.Childs {
if e.Path == path {
e.Handler(context)
return
}
}
}