forked from OneOfOne/gserv
/
utils.go
231 lines (195 loc) · 4.72 KB
/
utils.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package router
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strings"
)
type nodePart string
func (np nodePart) Name() string { return string(np[1:]) }
func (np nodePart) Type() uint8 { return np[0] }
func (np nodePart) String() string {
if np.Type() == '/' {
return fmt.Sprintf("{%s}", np.Name())
}
return fmt.Sprintf("{%s '%c'}", np.Name(), np.Type())
}
var re = regexp.MustCompile(`([:*/]?[^:*]+)`)
// splitPathToParts takes in a path (ex: /api/v1/someEndpoint/:id/*any) and returns:
//
// pp -> the longest part before the first param (/api/v1/someEndpoint/:)
// rest -> all the params (id, any)
// num -> number of params (probably not needed...)
// stars -> number of stars, basically a sanity check, if it's not 0 or 1 then it's an invalid path
func splitPathToParts(p string) (pp string, rest []nodePart, num, stars int) {
parts := re.FindAllString(p, -1)
if len(parts) < 2 {
pp = p
return
}
pp = parts[0]
for _, part := range parts[1:] {
splitPathFn(part, '/', func(sp string, _, _ int) bool {
switch c := sp[0]; c {
case '*':
stars++
fallthrough
case ':':
num++
fallthrough
case '/':
rest = append(rest, nodePart(sp))
}
return false
})
}
return
}
func splitPathFn(s string, sep uint8, fn func(p string, pidx, idx int) bool) bool {
for i, pi, last := 0, 0, 0; i < len(s); i++ {
if s[i] != sep {
if i < len(s)-1 {
continue
}
i = len(s)
}
if ss := s[last:i]; ss != "" {
if fn(ss, pi, i) {
return true
}
last = i
pi++
}
}
return false
}
func revSplitPathFn(s string, sep uint8, fn func(p string, pidx, idx int) bool) bool {
for i, pi, last := len(s)-1, 0, len(s); i > -1; i-- {
if s[i] != sep {
continue
}
if ss := s[i:last]; ss != "" {
if fn(ss, pi, last) {
return true
}
last = i
pi++
}
}
return false
}
type headRW struct {
http.ResponseWriter
}
func (w *headRW) Write(p []byte) (int, error) { return ioutil.Discard.Write(p) }
func pathNoQuery(p string) string {
if idx := strings.IndexByte(p, '?'); idx != -1 {
return p[:idx]
}
return p
}
// based on https://github.com/gin-gonic/gin/blob/a8fa424ae529397d4a0f2a1f9fda8031851a3269/path.go#L21
// cleanPath is the URL version of path.Clean, it returns a canonical URL path
// for p, eliminating . and .. elements.
//
// The following rules are applied iteratively until no further processing can
// be done:
// 1. Replace multiple slashes with a single slash.
// 2. Eliminate each . path name element (the current directory).
// 3. Eliminate each inner .. path name element (the parent directory)
// along with the non-.. element that precedes it.
// 4. Eliminate .. elements that begin a rooted path:
// that is, replace "/.." by "/" at the beginning of a path.
//
// If the result of this process is an empty string, "/" is returned.
func cleanPath(p string) (_ string, modified bool) {
// Turn empty string into "/"
if p == "" {
return "/", false
}
n := len(p)
var buf []byte
// Invariants:
// reading from path; r is index of next byte to process.
// writing to buf; w is index of next byte to write.
// path must start with '/'
r := 1
w := 1
if p[0] != '/' {
r = 0
buf = make([]byte, n+1)
buf[0] = '/'
}
trailing := n > 2 && p[n-1] == '/'
// A bit more clunky without a 'lazybuf' like the path package, but the loop
// gets completely inlined (bufApp). So in contrast to the path package this
// loop has no expensive function calls (except 1x make)
for r < n {
switch {
case p[r] == '/':
// empty path element, trailing slash is added after the end
r++
case p[r] == '.' && r+1 == n:
trailing = true
r++
case p[r] == '.' && p[r+1] == '/':
// . element
r++
case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'):
// .. element: remove to last /
r += 2
if w > 1 {
// can backtrack
w--
if buf == nil {
for w > 1 && p[w] != '/' {
w--
}
} else {
for w > 1 && buf[w] != '/' {
w--
}
}
}
default:
// real path element.
// add slash if needed
if w > 1 {
bufApp(&buf, p, w, '/')
w++
}
// copy element
for r < n && p[r] != '/' {
bufApp(&buf, p, w, p[r])
w++
r++
}
}
}
// re-append trailing slash
if trailing && w > 1 {
bufApp(&buf, p, w, '/')
w++
}
if buf == nil {
return p[:w], w < len(p)
}
return string(buf[:w]), true
}
// internal helper to lazily create a buffer if necessary.
func bufApp(buf *[]byte, s string, w int, c byte) {
if *buf == nil {
if s[w] == c {
return
}
*buf = make([]byte, len(s))
copy(*buf, s[:w])
}
(*buf)[w] = c
}
var routeCtxKey = struct{}{}
func RouteFromRequest(r *http.Request) *Route {
rn, _ := r.Context().Value(routeCtxKey).(*Route)
return rn
}