/
subfilter.go
208 lines (164 loc) · 4.21 KB
/
subfilter.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
// Package subfilter a plugin to rewrite response body.
package subfilter
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"regexp"
)
const contentEncodingGzip = "gzip"
// Filter holds one Filter definition.
type Filter struct {
Regex string `json:"regex,omitempty"`
Replacement string `json:"replacement,omitempty"`
}
// Config holds the plugin configuration.
type Config struct {
LastModified bool `json:"lastModified,omitempty"`
Filters []Filter `json:"filters,omitempty"`
}
// CreateConfig creates and initializes the plugin configuration.
func CreateConfig() *Config {
return &Config{}
}
type filter struct {
regex *regexp.Regexp
replacement []byte
}
type subfilter struct {
name string
next http.Handler
filters []filter
lastModified bool
}
// New creates and returns a new rewrite body plugin instance.
func New(_ context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
filters := make([]filter, 0)
for _, f := range config.Filters {
regex, err := regexp.Compile(f.Regex)
if err != nil {
log.Printf("error compiling regex %q: %v", f.Regex, err)
continue
}
newFilter := filter{
regex: regex,
replacement: []byte(f.Replacement),
}
filters = append(filters, newFilter)
}
if len(filters) == 0 {
return nil, errors.New("no valid filters. disabling")
}
sf := &subfilter{
name: name,
next: next,
filters: filters,
lastModified: config.LastModified,
}
return sf, nil
}
func (s *subfilter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
rw := &responseWriter{
lastModified: s.lastModified,
ResponseWriter: w,
buffer: &bytes.Buffer{},
}
s.next.ServeHTTP(rw, r)
ce := rw.Header().Get("Content-Encoding")
b := rw.buffer.Bytes()
if ce != "" && ce != "identity" && ce != contentEncodingGzip {
if _, err := w.Write(b); err != nil {
log.Printf("unable to write response: %v", err)
}
return
}
for _, f := range s.filters {
b = f.regex.ReplaceAll(b, f.replacement)
}
// fmt.Printf("Regexed Page: %v\n", string(b))
if ce == "gzip" {
// fmt.Printf("Gzipping regexed page: %s\n", string(b))
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
_, err := gz.Write(b)
if err != nil {
log.Printf("unable to write gzipped modified response: %v", err)
return
}
if err = gz.Close(); err != nil {
log.Printf("unable to close gzip writer: %v", err)
return
}
b = buf.Bytes()
}
// log.Printf("regexed page Gzipped: %s\n", b)
if _, err := w.Write(b); err != nil {
log.Printf("unable to write modified response: %v", err)
}
}
type responseWriter struct {
lastModified bool
wroteHeader bool
buffer *bytes.Buffer
http.ResponseWriter
}
func (r *responseWriter) WriteHeader(status int) {
if !r.lastModified {
r.Header().Del("Last-Modified")
}
r.wroteHeader = true
r.Header().Del("Content-Length")
r.ResponseWriter.WriteHeader(status)
}
func (r *responseWriter) Write(b []byte) (int, error) {
if !r.wroteHeader {
r.WriteHeader(http.StatusOK)
}
if r.Header().Get("Content-Encoding") == "gzip" {
// fmt.Printf("Received GZIP encoded page: %s\n", b)
gr, err := gzip.NewReader(bytes.NewReader(b))
if err != nil {
return 0, fmt.Errorf("unable to create gzip reader: %w", err)
}
var cleanBytes []byte
cleanBytes, err = ioutil.ReadAll(gr)
if err != nil {
return 0, fmt.Errorf("unable to read gzipped response: %w", err)
}
// fmt.Printf("Decoded page: %s\n", cleanBytes)
var i int
i, err = r.buffer.Write(cleanBytes)
if err != nil {
return i, fmt.Errorf("could not write buffer: %w", err)
}
return i, nil
}
i, err := r.buffer.Write(b)
if err != nil {
return i, fmt.Errorf("could not write buffer: %w", err)
}
return i, nil
}
func (r *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
h, ok := r.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, fmt.Errorf("%T is not a http.Hijacker", r.ResponseWriter)
}
c, w, err := h.Hijack()
if err != nil {
return c, w, fmt.Errorf("hijack error: %w", err)
}
return c, w, nil
}
func (r *responseWriter) Flush() {
if f, ok := r.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}