-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.go
92 lines (82 loc) · 2.14 KB
/
plugin.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
package plugin_cond_redirect
import (
"context"
"net/http"
"regexp"
)
type RedirectRule struct {
WithHost bool `mapstructure:"withHost,omitempty"`
SourcePattern string `mapstructure:"sourcePattern"`
DestinationPattern string `mapstructure:"destinationPattern"`
Condition RawRedirectCondition `mapstructure:"condition"`
}
type RawRedirectCondition struct {
T string `mapstructure:"type"`
Data map[string]interface{} `mapstructure:",remain"`
}
type RedirectCondition interface {
build() (redirectCondition, error)
}
type Config struct {
StatusCode int `mapstructure:"statusCode,omitempty"`
Rules []RedirectRule `mapstructure:"rules,omitempty"`
}
type ConditionalRedirect struct {
next http.Handler
config *Config
name string
statusCode int
rules []redirectRule
}
func CreateConfig() *Config {
return &Config{
StatusCode: 0,
Rules: make([]RedirectRule, 0),
}
}
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
rules := make([]redirectRule, 0)
for _, r := range config.Rules {
refined, err := r.Condition.refine()
if err != nil {
return nil, err
}
condition, err := refined.build()
if err != nil {
return nil, err
}
rules = append(rules, redirectRule{
withHost: r.WithHost,
source: regexp.MustCompile(r.SourcePattern),
destination: r.DestinationPattern,
condition: condition,
})
}
statusCode := config.StatusCode
if statusCode == 0 {
statusCode = 302
}
return &ConditionalRedirect{
next: next,
config: config,
name: name,
statusCode: statusCode,
rules: rules,
}, nil
}
func (c *ConditionalRedirect) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
url := req.URL.String()
uri := req.URL.RequestURI()
for _, r := range c.rules {
src := uri
if r.withHost {
src = url
}
if r.source.MatchString(src) && r.condition.check(req) {
rw.Header().Set("Location", r.source.ReplaceAllString(src, r.destination))
rw.WriteHeader(c.statusCode)
return
}
}
c.next.ServeHTTP(rw, req)
}