-
Notifications
You must be signed in to change notification settings - Fork 6
/
writer_proxy.go
58 lines (49 loc) · 1.24 KB
/
writer_proxy.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
package glogrus
import (
"net/http"
)
// wrapWriter returns a proxy that wraps ResponseWriter
func wrapWriter(w http.ResponseWriter) writerProxy {
bw := basicWriter{ResponseWriter: w}
return &bw
}
// writerProxy is a proxy that wraps ResponseWriter
type writerProxy interface {
http.ResponseWriter
maybeWriteHeader()
status() int
}
// basicWriter holds the status code and a
// flag in addition to http.ResponseWriter
type basicWriter struct {
http.ResponseWriter
wroteHeader bool
code int
}
// WriteHeader stores the status code and writes header
func (b *basicWriter) WriteHeader(code int) {
if !b.wroteHeader {
b.code = code
b.wroteHeader = true
b.ResponseWriter.WriteHeader(code)
}
}
// Write writes the bytes and calls MaybeWriteHeader
func (b *basicWriter) Write(buf []byte) (int, error) {
b.maybeWriteHeader()
return b.ResponseWriter.Write(buf)
}
// maybeWriteHeader writes the header if it is not alredy set
func (b *basicWriter) maybeWriteHeader() {
if !b.wroteHeader {
b.WriteHeader(http.StatusOK)
}
}
// status returns the status
func (b *basicWriter) status() int {
return b.code
}
// unwrap returns the original http.ResponseWriter
func (b *basicWriter) Unwrap() http.ResponseWriter {
return b.ResponseWriter
}