-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
193 lines (161 loc) · 5.07 KB
/
main.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
// Package responsebodyrewrite provides a middleware that rewrites the response body based on the status code and the content of the response.
package traefik_responsebodyrewrite
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"regexp"
)
// parsedRewrite holds one rewrite body configuration with parsed values.
type parsedRewrite struct {
regex *regexp.Regexp
replacement []byte
}
// parsedResponse holds one response configuration with parsed values.
type parsedResponse struct {
rewrites []parsedRewrite
status HTTPCodeRanges
}
// Rewrite holds one rewrite body configuration.
type Rewrite struct {
Regex string `json:"regex,omitempty"`
Replacement string `json:"replacement,omitempty"`
}
// Response holds one response configuration.
type Response struct {
Rewrites []Rewrite `json:"rewrites,omitempty"`
Status string `json:"status,omitempty"`
}
// Config the plugin configuration.
type Config struct {
Responses []Response `json:"responses,omitempty"`
}
// CreateConfig creates the default plugin configuration.
func CreateConfig() *Config {
return &Config{
Responses: []Response{},
}
}
// responsebodyrewrite is a middleware that rewrites the response body based on the status code and the content of the response.
type responsebodyrewrite struct {
next http.Handler
name string
responses []parsedResponse
infoLogger *log.Logger
}
// New creates a new instance of the responsebodyrewrite middleware.
// It takes a context.Context, an http.Handler, a *Config, and a name string as parameters.
// It returns an http.Handler and an error.
func New(_ context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
infoLogger := log.New(io.Discard, "INFO: responsebodyrewrite: ", log.Ldate|log.Ltime)
infoLogger.SetOutput(os.Stdout)
infoLogger.Printf("Responses config: %s", config.Responses)
parsedResponses := make([]parsedResponse, len(config.Responses))
for i, response := range config.Responses {
// Parse the HTTP code ranges
httpCodeRanges, err := NewHTTPCodeRanges([]string{response.Status})
if err != nil {
return nil, err
}
// Parse the rewrites
rewrites := make([]parsedRewrite, len(response.Rewrites))
for i, rewriteConfig := range response.Rewrites {
regex, err := regexp.Compile(rewriteConfig.Regex)
if err != nil {
return nil, fmt.Errorf("error compiling regex %q: %w", rewriteConfig.Regex, err)
}
rewrites[i] = parsedRewrite{
regex: regex,
replacement: []byte(rewriteConfig.Replacement),
}
}
parsedResponses[i] = parsedResponse{
rewrites: rewrites,
status: httpCodeRanges,
}
}
return &responsebodyrewrite{
responses: parsedResponses,
next: next,
name: name,
infoLogger: infoLogger,
}, nil
}
// ServeHTTP is the method that handles the HTTP request.
// It rewrites the response body based on the status code and the content of the response.
func (r *responsebodyrewrite) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
wrappedWriter := &responseWriter{
code: http.StatusOK,
headerMap: make(http.Header),
ResponseWriter: rw,
responses: r.responses,
}
r.next.ServeHTTP(wrappedWriter, req)
bodyBytes := wrappedWriter.buffer.Bytes()
for _, response := range r.responses {
if !response.status.Contains(wrappedWriter.code) {
continue
}
for _, rewrite := range response.rewrites {
bodyBytes = rewrite.regex.ReplaceAll(bodyBytes, rewrite.replacement)
}
break
}
if _, err := rw.Write(bodyBytes); err != nil {
r.infoLogger.Printf("unable to write body: %v", err)
}
}
// responseWriter is a wrapper around an http.ResponseWriter that allows us to intercept the response.
// It implements the http.ResponseWriter interface.
type responseWriter struct {
buffer bytes.Buffer
headerMap http.Header
headersSent bool
code int
http.ResponseWriter
responses []parsedResponse
}
// WriteHeader implements the http.ResponseWriter interface.
// It intercepts the response status code and stores it in the responseWriter struct.
func (rw *responseWriter) WriteHeader(statusCode int) {
if rw.headersSent {
return
}
rw.code = statusCode
// Check if the status code is in the list of status codes to rewrite.
for _, response := range rw.responses {
if !response.status.Contains(statusCode) {
continue
}
rw.ResponseWriter.Header().Del("Content-Length")
break
}
rw.headersSent = true
rw.ResponseWriter.WriteHeader(statusCode)
}
// Write implements the http.ResponseWriter interface.
func (rw *responseWriter) Write(p []byte) (int, error) {
if !rw.headersSent {
rw.WriteHeader(http.StatusOK)
}
return rw.buffer.Write(p)
}
// Hijack implements the http.Hijacker interface.
func (rw *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if h, ok := rw.ResponseWriter.(http.Hijacker); ok {
return h.Hijack()
}
return nil, nil, fmt.Errorf("not a hijacker: %T", rw.ResponseWriter)
}
// Flush implements the http.Flusher interface.
func (rw *responseWriter) Flush() {
if flusher, ok := rw.ResponseWriter.(http.Flusher); ok {
flusher.Flush()
}
}