-
Notifications
You must be signed in to change notification settings - Fork 0
/
route.go
127 lines (106 loc) · 2.71 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package poteto
import (
"fmt"
"strings"
"github.com/fatih/color"
"github.com/poteto-go/poteto/constant"
"github.com/poteto-go/poteto/utils"
)
type Route interface {
Search(path string) (*route, []ParamUnit)
Insert(path string, handler HandlerFunc)
GetHandler() HandlerFunc
}
type route struct {
key string
children map[string]Route
childParamKey string
handler HandlerFunc
}
func NewRoute() Route {
return &route{
key: "",
children: make(map[string]Route),
childParamKey: "",
}
}
func (r *route) Search(path string) (*route, []ParamUnit) {
currentRoute := r
rightPath := path[1:]
param := ""
httpParams := []ParamUnit{}
if rightPath == "" {
return currentRoute, httpParams
}
// optimized router insert
// https://github.com/poteto-go/poteto/issues/113
for {
id := strings.Index(rightPath, "/")
if id < 0 {
param = rightPath
} else {
param = rightPath[:id]
rightPath = rightPath[(id + 1):]
}
if nextRoute, ok := currentRoute.children[param]; ok {
currentRoute = nextRoute.(*route)
} else {
// includes url param ex: /users/:id, /users/:id/name
if chParam := currentRoute.childParamKey; chParam != "" {
if nextRoute, ok = currentRoute.children[chParam]; ok {
currentRoute = nextRoute.(*route)
httpParam := ParamUnit{key: chParam, value: param}
httpParams = append(httpParams, httpParam)
}
} else {
return nil, httpParams
}
}
if id < 0 {
break
}
}
return currentRoute, httpParams
}
func (r *route) Insert(path string, handler HandlerFunc) {
currentRoute := r
rightPath := path[1:]
param := ""
// optimized router insert
// https://github.com/poteto-go/poteto/issues/113
for {
id := strings.Index(rightPath, "/")
if id < 0 { // means last
param = rightPath
} else {
param = rightPath[:id]
rightPath = rightPath[(id + 1):]
}
if nextRoute := currentRoute.children[param]; nextRoute == nil {
// last path includes url param ex: /users/:id
if hasParamPrefix(param) {
currentRoute.childParamKey = param
}
currentRoute.children[param] = &route{
key: param,
children: make(map[string]Route),
}
}
currentRoute = currentRoute.children[param].(*route)
if id < 0 {
break
}
}
if currentRoute.handler != nil {
coloredWarn := color.HiRedString(fmt.Sprintf("Handler Collision on %s \n", path))
utils.PotetoPrint(coloredWarn)
return
}
currentRoute.handler = handler
}
func hasParamPrefix(param string) bool {
return strings.HasPrefix(param, constant.PARAM_PREFIX)
}
func (r *route) GetHandler() HandlerFunc {
return r.handler
}