|
@@ -1,94 +1,79 @@
|
1
|
1
|
package router
|
2
|
2
|
|
3
|
3
|
import (
|
4
|
|
- "fmt"
|
5
|
4
|
"net/http"
|
|
5
|
+ "regexp"
|
|
6
|
+ "strconv"
|
|
7
|
+ "strings"
|
6
|
8
|
)
|
7
|
9
|
|
|
10
|
+type closure func(http.ResponseWriter, *http.Request)
|
|
11
|
+
|
8
|
12
|
type route struct {
|
9
|
13
|
Pattern string
|
10
|
|
- Handler http.Handler
|
|
14
|
+ Handler closure
|
11
|
15
|
}
|
12
|
16
|
|
13
|
17
|
|
14
|
18
|
type Routes []route
|
15
|
19
|
|
|
20
|
+var routes Routes
|
|
21
|
+
|
16
|
22
|
|
17
|
|
-func (Routes) Add(pattern string, test string) {
|
18
|
|
- fmt.Print(pattern)
|
19
|
|
-
|
20
|
|
-
|
21
|
|
-
|
22
|
|
-
|
|
23
|
+func Add(pattern string, handler closure) {
|
|
24
|
+ routes = append(routes, route{
|
|
25
|
+ pattern,
|
|
26
|
+ handler,
|
|
27
|
+ })
|
|
28
|
+}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+func Match(w http.ResponseWriter, r *http.Request) {
|
|
32
|
+ url := r.URL.Path
|
|
33
|
+ for _, element := range routes {
|
|
34
|
+ when := element.Pattern
|
|
35
|
+ pattern := toRegex(when)
|
|
36
|
+
|
|
37
|
+ items := regexSubmatch(pattern, url)
|
|
38
|
+
|
|
39
|
+ if items[0] == url {
|
|
40
|
+ element.Handler(w, r)
|
|
41
|
+ }
|
|
42
|
+ }
|
|
43
|
+}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+func patternURL(url string) string {
|
|
47
|
+ lastChar := url[len(url)-1:]
|
|
48
|
+ if lastChar != "/" {
|
|
49
|
+ url = url + "/"
|
|
50
|
+ }
|
|
51
|
+
|
|
52
|
+ return url
|
23
|
53
|
}
|
24
|
54
|
|
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
|
|
-
|
|
55
|
+
|
|
56
|
+func toRegex(regex string) *regexp.Regexp {
|
|
57
|
+ return regexp.MustCompile(`(?m)` + regex)
|
|
58
|
+}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+func regexSubmatch(pattern *regexp.Regexp, str string) []string {
|
|
62
|
+ data := []string{""}
|
|
63
|
+
|
|
64
|
+ items := pattern.FindAllStringSubmatch(str, -1)
|
|
65
|
+ if len(items) > 0 {
|
|
66
|
+ data = items[0]
|
|
67
|
+ }
|
|
68
|
+
|
|
69
|
+ return data
|
|
70
|
+}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+func replaceStringsURL(items []string, urlPattern string) string {
|
|
74
|
+ for index, element := range items {
|
|
75
|
+ urlPattern = strings.Replace(urlPattern, "$"+strconv.Itoa(index), element, -1)
|
|
76
|
+ }
|
|
77
|
+
|
|
78
|
+ return urlPattern
|
|
79
|
+}
|