-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwriter.go
More file actions
85 lines (76 loc) · 1.56 KB
/
Copy pathwriter.go
File metadata and controls
85 lines (76 loc) · 1.56 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
package idemkit
import (
"bytes"
"net/http"
"slices"
)
type responseWriter struct {
base http.ResponseWriter
maxBytes int64
statusCode int
capturedHdr http.Header
body *bytes.Buffer
wroteHeader bool
flushed bool
oversize bool
}
func newResponseWriter(base http.ResponseWriter, maxBytes int64) *responseWriter {
return &responseWriter{
base: base,
maxBytes: maxBytes,
body: &bytes.Buffer{},
}
}
func (w *responseWriter) Header() http.Header {
return w.base.Header()
}
func (w *responseWriter) WriteHeader(code int) {
if w.wroteHeader {
return
}
w.wroteHeader = true
w.statusCode = code
w.capturedHdr = w.base.Header().Clone()
w.base.WriteHeader(code)
}
func (w *responseWriter) Write(b []byte) (int, error) {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
n, err := w.base.Write(b)
if !w.cacheable() {
return n, err
}
if int64(w.body.Len())+int64(n) > w.maxBytes {
w.oversize = true
w.body = nil
return n, err
}
w.body.Write(b[:n])
return n, err
}
func (w *responseWriter) Flush() {
w.flushed = true
w.body = nil
if f, ok := w.base.(http.Flusher); ok {
f.Flush()
}
}
func (w *responseWriter) cacheable() bool {
return !w.flushed && !w.oversize
}
func (w *responseWriter) snapshot() *Result {
code := w.statusCode
if !w.wroteHeader {
code = http.StatusOK
}
hdr := w.capturedHdr
if hdr == nil {
hdr = w.base.Header().Clone()
}
var body []byte
if w.body != nil && w.body.Len() > 0 {
body = slices.Clone(w.body.Bytes())
}
return &Result{StatusCode: code, Header: hdr, Body: body}
}