-
Notifications
You must be signed in to change notification settings - Fork 11
/
rewrite.go
260 lines (239 loc) · 5.87 KB
/
rewrite.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package middleware
import (
"fmt"
"regexp"
"strconv"
"strings"
"github.com/webx-top/echo"
)
type (
RewriteRegExp struct {
Old *regexp.Regexp
New *regexp.Regexp
}
// RewriteConfig defines the config for Rewrite middleware.
RewriteConfig struct {
// Skipper defines a function to skip middleware.
Skipper echo.Skipper `json:"-"`
// Rules defines the URL path rewrite rules. The values captured in asterisk can be
// retrieved by index e.g. $1, $2 and so on.
// Example:
// "/old": "/new",
// "/api/*": "/$1",
// "/js/*": "/public/javascripts/$1",
// "/users/*/orders/*": "/user/$1/order/$2",
// "/users/:id": "/user/$1",
// "/match/<name:[0-9]+>": "/user/$1",
// Required.
Rules map[string]string `json:"rules"`
addresses map[string]*RewriteRegExp //"/old": old<*regexp.Regexp>
rulesRegex map[*regexp.Regexp]string //old<*regexp.Regexp>: "/new"
rvsesRegex map[*regexp.Regexp]string //new<*regexp.Regexp>: "/old/$1"
}
)
// Init Initialize
func (c *RewriteConfig) Init() *RewriteConfig {
c.rulesRegex = map[*regexp.Regexp]string{}
c.rvsesRegex = map[*regexp.Regexp]string{}
c.addresses = map[string]*RewriteRegExp{}
for k, v := range c.Rules {
c.Set(k, v)
}
return c
}
func QueryParamToRegexpRule(query string) (string, string, []string) {
s := strings.Builder{}
rv := strings.Builder{}
var regExp bool
var regExpParam bool
var param bool
rule := strings.Builder{}
var rules []string
for _, r := range query {
if regExp {
if r == '>' {
regExp = false
regExpParam = false
s.WriteRune(')')
rule.WriteRune(')')
rules = append(rules, rule.String())
rule.Reset()
continue
}
if !regExpParam {
if r == ':' {
regExpParam = true
}
continue
}
rule.WriteRune(r)
} else {
if r == '*' {
rv.WriteString("$" + strconv.Itoa(len(rules)+1))
s.WriteString(`(\S*)`)
rule.WriteString(`(\S*)`)
rules = append(rules, rule.String())
rule.Reset()
continue
}
if r == ':' {
param = true
rv.WriteString("$" + strconv.Itoa(len(rules)+1))
s.WriteString(`([^/]+)`)
rule.WriteString(`([^/]+)`)
rules = append(rules, rule.String())
rule.Reset()
continue
}
if r == '<' {
regExp = true
rv.WriteString("$" + strconv.Itoa(len(rules)+1))
s.WriteRune('(')
rule.WriteRune('(')
continue
}
if param {
if r != '/' {
continue
}
param = false
}
rv.WriteRune(r)
}
s.WriteRune(r)
}
return `^` + s.String() + `$`, rv.String(), rules
}
// Set rule
func (c *RewriteConfig) Set(urlPath, newPath string) *RewriteConfig {
re, ok := c.addresses[urlPath]
if ok {
delete(c.rulesRegex, re.Old)
delete(c.rvsesRegex, re.New)
}
c.Add(urlPath, newPath)
return c
}
// Delete rule
func (c *RewriteConfig) Delete(urlPath string) *RewriteConfig {
re, ok := c.addresses[urlPath]
if ok {
delete(c.addresses, urlPath)
delete(c.rulesRegex, re.Old)
delete(c.rvsesRegex, re.New)
}
return c
}
func ValidateRewriteRule(urlPath, newPath string) error {
r, _, ps := QueryParamToRegexpRule(urlPath)
_, err := regexp.Compile(r)
if err != nil {
return fmt.Errorf(`%w: %s (routeURL: %s)`, err, r, urlPath)
}
newR := newPath
if len(ps) > 0 {
newR = echo.CaptureTokensByValues(ps).Replace(newR)
}
_, err = regexp.Compile(`^` + newR + `$`)
if err != nil {
if len(ps) > 0 {
err = fmt.Errorf(`%w: %s (rewriteTo: %s)`, err, newR, newPath)
} else {
err = fmt.Errorf(`%w: %s`, err, newR)
}
}
return err
}
// Add rule
func (c *RewriteConfig) Add(urlPath, newPath string) *RewriteConfig {
r, rv, ps := QueryParamToRegexpRule(urlPath)
re := regexp.MustCompile(r)
c.rulesRegex[re] = newPath
newR := newPath
if len(ps) > 0 {
newR = echo.CaptureTokensByValues(ps).Replace(newR)
}
rve := regexp.MustCompile(`^` + newR + `$`)
c.rvsesRegex[rve] = rv
c.addresses[urlPath] = &RewriteRegExp{
Old: re,
New: rve,
}
return c
}
// Rewrite url
func (c *RewriteConfig) Rewrite(urlPath string) string {
for k, v := range c.rulesRegex {
replacer := echo.CaptureTokens(k, urlPath)
if replacer != nil {
urlPath = replacer.Replace(v)
}
}
return urlPath
}
// Reverse url
func (c *RewriteConfig) Reverse(urlPath string) string {
for k, v := range c.rvsesRegex {
replacer := echo.CaptureTokens(k, urlPath)
if replacer != nil {
urlPath = replacer.Replace(v)
}
}
return urlPath
}
var (
// DefaultRewriteConfig is the default Rewrite middleware config.
DefaultRewriteConfig = RewriteConfig{
Skipper: echo.DefaultSkipper,
}
)
// Rewrite returns a Rewrite middleware.
//
// Rewrite middleware rewrites the URL path based on the provided rules.
func Rewrite(rules map[string]string) echo.MiddlewareFuncd {
c := DefaultRewriteConfig
c.Rules = rules
return RewriteWithConfig(c)
}
// RewriteWithConfig returns a Rewrite middleware with config.
// See: `Rewrite()`.
func RewriteWithConfig(config RewriteConfig) echo.MiddlewareFuncd {
// Defaults
if config.Rules == nil {
panic("echo: rewrite middleware requires url path rewrite rules")
}
if config.Skipper == nil {
config.Skipper = DefaultRewriteConfig.Skipper
}
config.Init()
return func(next echo.Handler) echo.HandlerFunc {
return func(c echo.Context) (err error) {
if config.Skipper(c) {
return next.Handle(c)
}
req := c.Request()
req.URL().SetPath(config.Rewrite(req.URL().Path()))
return next.Handle(c)
}
}
}
func UnrewriteWithConfig(config RewriteConfig) echo.MiddlewareFuncd {
// Defaults
if config.Rules == nil {
panic("echo: rewrite middleware requires url path rewrite rules")
}
if config.Skipper == nil {
config.Skipper = DefaultRewriteConfig.Skipper
}
config.Init()
return func(next echo.Handler) echo.HandlerFunc {
return func(c echo.Context) (err error) {
if config.Skipper(c) {
return next.Handle(c)
}
req := c.Request()
req.URL().SetPath(config.Reverse(req.URL().Path()))
return next.Handle(c)
}
}
}