-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute.go
51 lines (41 loc) · 1.1 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
package temaki
import (
"fmt"
"net/http"
"regexp"
"strings"
)
var rgx = regexp.MustCompile(`\{(.*?)\}`)
var rgxIn = regexp.MustCompile(`\((.*?)\)`)
type Route struct {
method string
regex *regexp.Regexp
pathParams map[string]int
handler http.HandlerFunc
}
func NewRoute(method, pattern string, handler http.HandlerFunc) Route {
pathParamsMap, regexPath := parseURL(pattern)
if regexPath[0] != '/' {
regexPath = fmt.Sprintf("/%s", regexPath)
}
return Route{method, regexp.MustCompile("^" + regexPath + "$"), pathParamsMap, handler}
}
func parseURL(path string) (map[string]int, string) {
pathParams := map[string]int{}
params := rgx.FindAllString(path, -1)
for i, param := range params {
oldParam := param
param = param[1 : len(param)-1]
pathParamKey := param
strPattern := "([^/]+)"
inParam := rgxIn.FindAllString(param, -1)
if len(inParam) == 1 {
strPattern = inParam[0]
pathParamKey = strings.Split(param, strPattern)[0]
strPattern = inParam[0]
}
pathParams[pathParamKey] = i
path = strings.Replace(path, oldParam, strPattern, 1)
}
return pathParams, path
}