-
Notifications
You must be signed in to change notification settings - Fork 8
/
route.go
103 lines (80 loc) · 1.66 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
// Copyright © 2016-2018 Eduard Sesigin. All rights reserved. Contacts: <[email protected]>
package bxog
// route
import (
"net/http"
"strings"
)
// The route for URL
type route struct {
id string // added by the user
method string
handler func(http.ResponseWriter, *http.Request, *Router)
sections []*section
url string
}
func (r *Router) newRoute(url string, handler func(http.ResponseWriter, *http.Request, *Router), method string) *route {
route := &route{
url,
method,
handler,
[]*section{},
url,
}
route.setSections(url)
r.routes = append(r.routes, route)
return route
}
func (r *route) setSections(url string) {
sec := r.parseUrl(url[1:])
if len(sec) < HTTP_SECTION_COUNT {
r.sections = sec
} else {
panic("Too many parameters!")
}
}
func (r *route) Method(value string) *route {
r.method = value
return r
}
func (r *route) Id(value string) *route {
r.id = value
return r
}
func (r *route) parseUrl(url string) []*section {
var arraySec []*section
if len(url) == 0 {
return []*section{}
}
result := r.genSplit(url)
for _, value := range result {
if strings.HasPrefix(value, ":") {
arraySec = append(arraySec, newSection(value[1:], TYPE_ARG))
} else {
arraySec = append(arraySec, newSection(value, TYPE_STAT))
}
}
return arraySec
}
func (r *route) genSplit(s string) []string {
n := 1
c := DELIMITER_BYTE
for i := 0; i < len(s); i++ {
if s[i] == c {
n++
}
}
out := make([]string, n)
count := 0
begin := 0
length := len(s) - 1
for i := 0; i <= length; i++ {
if s[i] == c {
out[count] = s[begin:i]
count++
begin = i + 1
}
}
out[count] = s[begin : length+1]
return out
}