-
Notifications
You must be signed in to change notification settings - Fork 0
/
response_editor.go
61 lines (49 loc) · 1.21 KB
/
response_editor.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
package rewritehtml
import (
"io"
"net/http"
"strings"
"sync"
)
type ResponseEditor struct {
http.ResponseWriter
rewriteFn EditorFunc
writeOnce sync.Once
closeOnce sync.Once
body io.WriteCloser
}
func (r *ResponseEditor) Unwrap() http.ResponseWriter {
return r.ResponseWriter
}
var _ io.WriteCloser = &ResponseEditor{}
// NewResponseEditor will return a ResponseEditor that inspects the http response
// and rewrites the HTML document before passing it to w.
func NewResponseEditor(w http.ResponseWriter, rewriteFn EditorFunc) *ResponseEditor {
return &ResponseEditor{
ResponseWriter: w,
rewriteFn: rewriteFn,
}
}
func (r *ResponseEditor) Write(p []byte) (int, error) {
r.writeOnce.Do(func() {
header := r.ResponseWriter.Header()
// TODO: handle content encoding
if strings.HasPrefix(header.Get("Content-Type"), "text/html") {
header.Set("Transfer-Encoding", "chunked")
header.Del("Content-Length")
r.body = NewTokenEditor(r.ResponseWriter, r.rewriteFn)
}
})
if r.body != nil {
return r.body.Write(p)
}
return r.ResponseWriter.Write(p)
}
func (r *ResponseEditor) Close() (err error) {
r.closeOnce.Do(func() {
if r.body != nil {
err = r.body.Close()
}
})
return
}