-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathplugin.go
180 lines (149 loc) · 4.16 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
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
package traefik_plugin_redirect
import (
"context"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
)
const (
schemeHTTP = "http"
schemeHTTPS = "https"
)
// Redirect holds one redirect configuration
type Redirect struct {
Regex string `json:"regex" yaml:"regex"`
Replacement string `json:"replacement" yaml:"replacement"`
StatusCode int `json:"statusCode" yaml:"statusCode"`
}
// Config the plugin configuration.
type Config struct {
Debug bool `json:"debug,omitempty" yaml:"debug,omitempty"`
Redirects []Redirect `json:"redirects,omitempty" yaml:"redirects,omitempty"`
}
// CreateConfig creates the default plugin configuration.
func CreateConfig() *Config {
return &Config{}
}
// Plugin this is a Traefik redirect plugin.
type Plugin struct {
next http.Handler
name string
debug bool
redirects []redirect
rawURL func(*http.Request) string
}
type redirect struct {
Regex *regexp.Regexp `json:"regex,omitempty"`
Replacement string `json:"replacement,omitempty"`
StatusCode int `json:"statusCode,omitempty"`
}
// New created a new plugin.
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
plugin := &Plugin{
next: next,
name: name,
debug: config.Debug,
redirects: make([]redirect, 0),
rawURL: rawURL,
}
for _, cfg := range config.Redirects {
rxp, err := regexp.Compile(cfg.Regex)
if err != nil {
return nil, err
}
plugin.redirects = append(plugin.redirects, redirect{
Regex: rxp,
Replacement: cfg.Replacement,
StatusCode: cfg.StatusCode,
})
}
return plugin, nil
}
func (p *Plugin) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
oldURL := p.rawURL(req)
// If no redirection registered, skip to the next handler.
if p.redirects == nil || len(p.redirects) == 0 {
p.next.ServeHTTP(rw, req)
return
}
// Loop all redirections
for _, r := range p.redirects {
if r.Regex.MatchString(oldURL) {
// Apply a rewrite regexp to the URL.
newURL := r.Regex.ReplaceAllString(oldURL, r.Replacement)
// Add headers for debug
if p.debug {
rw.Header().Set("X-Middleware-Name", p.name)
rw.Header().Set("X-Middleware-Regex", r.Regex.String())
rw.Header().Set("X-Middleware-Replacement", r.Replacement)
rw.Header().Set("X-Middleware-StatusCode", strconv.Itoa(r.StatusCode))
rw.Header().Set("X-Middleware-Old-URL", oldURL)
rw.Header().Set("X-Middleware-New-URL", newURL)
}
// Parse the rewritten URL and replace request URL with it.
parsedURL, err := url.Parse(newURL)
if err != nil {
continue
}
// Check if identical url, and redirect
if newURL != oldURL {
handler := &moveHandler{location: parsedURL, statusCode: r.StatusCode}
handler.ServeHTTP(rw, req)
return
}
// Make sure the request URI corresponds the rewritten URL.
req.URL = parsedURL
req.RequestURI = req.URL.RequestURI()
p.next.ServeHTTP(rw, req)
return
}
}
p.next.ServeHTTP(rw, req)
}
type moveHandler struct {
location *url.URL
statusCode int
}
func (m *moveHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Location", m.location.String())
status := m.statusCode
if status == 0 {
status = http.StatusFound
if req.Method != http.MethodGet {
status = http.StatusTemporaryRedirect
}
}
if req.Method != http.MethodGet && status == http.StatusMovedPermanently {
status = http.StatusPermanentRedirect
}
rw.WriteHeader(status)
_, err := rw.Write([]byte(http.StatusText(status)))
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
}
func rawURL(req *http.Request) string {
scheme := schemeHTTP
host := req.Host
port := ""
uri := req.RequestURI
schemeRegex := `^(https?):\/\/(\[[\w:.]+\]|[\w\._-]+)?(:\d+)?(.*)$`
re, _ := regexp.Compile(schemeRegex)
if re.Match([]byte(req.RequestURI)) {
match := re.FindStringSubmatch(req.RequestURI)
scheme = match[1]
if len(match[2]) > 0 {
host = match[2]
}
if len(match[3]) > 0 {
port = match[3]
}
uri = match[4]
}
if req.TLS != nil {
scheme = schemeHTTPS
}
return strings.Join([]string{scheme, "://", host, port, uri}, "")
}