-
Notifications
You must be signed in to change notification settings - Fork 14
/
gorilla.go
218 lines (195 loc) · 5.59 KB
/
gorilla.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
// Copyright 2012 The Gorilla Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package reverse
import (
"bytes"
"fmt"
"net/http"
"net/url"
"regexp"
"strings"
)
// GorillaHost ----------------------------------------------------------------
func NewGorillaHost(pattern string) (*GorillaHost, error) {
pattern, err := gorillaPattern(pattern, true, false, false)
if err != nil {
return nil, err
}
r, err := CompileRegexp(pattern)
if err != nil {
return nil, err
}
return &GorillaHost{*r}, nil
}
// GorillaHost matches a URL host using Gorilla's special syntax for named
// groups: `{name:regexp}`.
type GorillaHost struct {
Regexp
}
func (m *GorillaHost) Match(r *http.Request) bool {
return m.MatchString(getHost(r))
}
// Extract returns positional and named variables extracted from the URL host.
func (m *GorillaHost) Extract(result *Result, r *http.Request) {
result.Values = mergeValues(result.Values, m.Values(getHost(r)))
}
// Build builds the URL host using the given positional and named variables,
// and writes it to the given URL.
func (m *GorillaHost) Build(u *url.URL, values url.Values) error {
host, err := m.RevertValid(values)
if err == nil {
if u.Scheme == "" {
u.Scheme = "http"
}
u.Host = host
}
return err
}
// GorillaPath ----------------------------------------------------------------
func NewGorillaPath(pattern string, strictSlash bool) (*GorillaPath, error) {
regexpPattern, err := gorillaPattern(pattern, false, false, strictSlash)
if err != nil {
return nil, err
}
r, err := CompileRegexp(regexpPattern)
if err != nil {
return nil, err
}
return &GorillaPath{*r, pattern, strictSlash}, nil
}
// GorillaPath matches a URL path using Gorilla's special syntax for named
// groups: `{name:regexp}`.
type GorillaPath struct {
Regexp
pattern string
strictSlash bool
}
func (m *GorillaPath) Match(r *http.Request) bool {
return m.MatchString(r.URL.Path)
}
// Extract returns positional and named variables extracted from the URL path.
func (m *GorillaPath) Extract(result *Result, r *http.Request) {
result.Values = mergeValues(result.Values, m.Values(r.URL.Path))
if result.Handler == nil && m.strictSlash {
result.Handler = redirectPath(m.pattern, r)
}
}
// Build builds the URL path using the given positional and named variables,
// and writes it to the given URL.
func (m *GorillaPath) Build(u *url.URL, values url.Values) error {
path, err := m.RevertValid(values)
if err == nil {
u.Path = path
}
return err
}
// GorillaPathPrefix ----------------------------------------------------------
func NewGorillaPathPrefix(pattern string) (*GorillaPathPrefix, error) {
regexpPattern, err := gorillaPattern(pattern, false, true, false)
if err != nil {
return nil, err
}
r, err := CompileRegexp(regexpPattern)
if err != nil {
return nil, err
}
return &GorillaPathPrefix{*r}, nil
}
// GorillaPathPrefix matches a URL path prefix using Gorilla's special syntax
// for named groups: `{name:regexp}`.
type GorillaPathPrefix struct {
Regexp
}
func (m *GorillaPathPrefix) Match(r *http.Request) bool {
return m.MatchString(r.URL.Path)
}
// Extract returns positional and named variables extracted from the URL path.
func (m *GorillaPathPrefix) Extract(result *Result, r *http.Request) {
result.Values = mergeValues(result.Values, m.Values(r.URL.Path))
}
// Build builds the URL path using the given positional and named variables,
// and writes it to the given URL.
func (m *GorillaPathPrefix) Build(u *url.URL, values url.Values) error {
path, err := m.RevertValid(values)
if err == nil {
u.Path = path
}
return err
}
// Helpers --------------------------------------------------------------------
// gorillaPattern transforms a gorilla pattern into a regexp pattern.
func gorillaPattern(tpl string, matchHost, prefixMatch, strictSlash bool) (string, error) {
// Check if it is well-formed.
idxs, err := braceIndices(tpl)
if err != nil {
return "", err
}
// Now let's parse it.
defaultPattern := "[^/]+"
if matchHost {
defaultPattern = "[^.]+"
prefixMatch, strictSlash = false, false
} else {
if prefixMatch {
strictSlash = false
}
if strictSlash && strings.HasSuffix(tpl, "/") {
tpl = tpl[:len(tpl)-1]
}
}
pattern := bytes.NewBufferString("^")
var end int
for i := 0; i < len(idxs); i += 2 {
// Set all values we are interested in.
raw := tpl[end:idxs[i]]
end = idxs[i+1]
parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2)
name := parts[0]
patt := defaultPattern
if len(parts) == 2 {
patt = parts[1]
}
// Name or pattern can't be empty.
if name == "" || patt == "" {
return "", fmt.Errorf("missing name or pattern in %q",
tpl[idxs[i]:end])
}
// Build the regexp pattern.
fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), name, patt)
}
// Add the remaining.
raw := tpl[end:]
pattern.WriteString(regexp.QuoteMeta(raw))
if strictSlash {
pattern.WriteString("[/]?")
}
if !prefixMatch {
pattern.WriteByte('$')
}
return pattern.String(), nil
}
// braceIndices returns the first level curly brace indices from a string.
// It returns an error in case of unbalanced braces.
func braceIndices(s string) ([]int, error) {
var level, idx int
idxs := make([]int, 0)
for i := 0; i < len(s); i++ {
switch s[i] {
case '{':
if level++; level == 1 {
idx = i
}
case '}':
if level--; level == 0 {
idxs = append(idxs, idx, i+1)
} else if level < 0 {
return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
}
}
}
if level != 0 {
return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
}
return idxs, nil
}