-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathredirecterrors.go
More file actions
92 lines (80 loc) · 2.27 KB
/
redirecterrors.go
File metadata and controls
92 lines (80 loc) · 2.27 KB
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 redirecterrors traefik plugin to do external redirect on HTTP errors
package redirecterrors
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Config the plugin configuration.
type Config struct {
Status []string `json:"status,omitempty"`
Target string `json:"target,omitempty"`
OutputStatus int `json:"outputStatus,omitempty"`
}
// CreateConfig creates the default plugin configuration.
func CreateConfig() *Config {
return &Config{
Status: []string{},
Target: "",
OutputStatus: 302,
}
}
// RedirectErrors a RedirectErrors plugin.
type RedirectErrors struct {
name string
next http.Handler
httpCodeRanges HTTPCodeRanges
target string
outputStatus int
}
// New creates a new RedirectErrors plugin.
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
if len(config.Target) == 0 {
return nil, fmt.Errorf("target url must be set")
}
httpCodeRanges, err := NewHTTPCodeRanges(config.Status)
if err != nil {
return nil, err
}
return &RedirectErrors{
httpCodeRanges: httpCodeRanges,
next: next,
name: name,
target: config.Target,
outputStatus: config.OutputStatus,
}, nil
}
func (a *RedirectErrors) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
catcher := newCodeCatcher(rw, a.httpCodeRanges)
a.next.ServeHTTP(catcher, req)
if !catcher.isFilteredCode() {
return
}
code := catcher.getCode()
println("Caught HTTP status code", code, "redirecting")
// try to cobble together the original URL
proto := req.Header.Get("X-Forwarded-Proto")
host := req.Header.Get("X-Forwarded-Host")
fullURL := req.URL.String()
if len(proto) != 0 && len(host) != 0 {
fullURL = proto + "://" + host
fullURL += req.URL.RequestURI()
} else {
println("Missing proxy headers!")
}
location := a.target
location = strings.ReplaceAll(location, "{status}", strconv.Itoa(code))
location = strings.ReplaceAll(location, "{url}", url.QueryEscape(fullURL))
println("New location:", location)
rw.Header().Set("Location", location)
rw.WriteHeader(a.outputStatus)
_, err := io.WriteString(rw, "Redirecting")
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
}