forked from improbable-eng/go-httpwares
-
Notifications
You must be signed in to change notification settings - Fork 1
/
wrapped_writer.go
109 lines (92 loc) · 1.75 KB
/
wrapped_writer.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
// Copyright 2017 Mark Nevill. All Rights Reserved.
// See LICENSE for licensing terms.
package http_metrics
import (
"io"
"net/http"
)
type wrappedWriter interface {
http.ResponseWriter
Status() int
Size() int
}
func wrapWriter(w http.ResponseWriter, started func(int)) wrappedWriter {
wrapped := &writer{
parent: w,
started: started,
}
f, isFlusher := w.(http.Flusher)
rf, isReaderFrom := w.(io.ReaderFrom)
if isFlusher && isReaderFrom {
return writerFRF{writer: wrapped, f: f, rf: rf}
}
if isFlusher {
return writerF{writer: wrapped, f: f}
}
if isReaderFrom {
return writerRF{writer: wrapped, rf: rf}
}
return wrapped
}
type writer struct {
parent http.ResponseWriter
started func(int)
status int
size int
}
type writerF struct {
*writer
f http.Flusher
}
type writerRF struct {
*writer
rf io.ReaderFrom
}
type writerFRF struct {
*writer
f http.Flusher
rf io.ReaderFrom
}
func (w *writer) Status() int {
return w.status
}
func (w *writer) Size() int {
return w.size
}
func (w *writer) Header() http.Header {
return w.parent.Header()
}
func (w *writer) WriteHeader(status int) {
if w.started != nil {
w.status = status
w.started(status)
w.started = nil
}
w.parent.WriteHeader(status)
}
func (w *writer) Write(buf []byte) (int, error) {
if w.started != nil {
w.status = http.StatusOK
w.started(w.status)
w.started = nil
}
n, err := w.parent.Write(buf)
w.size += n
return n, err
}
func (w writerF) Flush() {
w.f.Flush()
}
func (w writerFRF) Flush() {
w.f.Flush()
}
func (w writerRF) ReadFrom(r io.Reader) (int64, error) {
n, err := w.rf.ReadFrom(r)
w.size += int(n)
return n, err
}
func (w writerFRF) ReadFrom(r io.Reader) (int64, error) {
n, err := w.rf.ReadFrom(r)
w.size += int(n)
return n, err
}