-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimeoutwriter.go
69 lines (59 loc) · 1.26 KB
/
timeoutwriter.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
package mgohttp
import (
"bytes"
"net/http"
"sync"
)
func (tw *timeoutWriter) setTimedOut() {
tw.mu.Lock()
defer tw.mu.Unlock()
tw.timedOut = true
}
func (tw *timeoutWriter) copyToResponseWriter(w http.ResponseWriter) {
tw.mu.Lock()
defer tw.mu.Unlock()
dst := w.Header()
for k, vv := range tw.h {
dst[k] = vv
}
if !tw.wroteHeader {
tw.code = http.StatusOK
}
w.WriteHeader(tw.code)
w.Write(tw.wbuf.Bytes())
}
// NOTE: below is copied from net/http's TimeoutHandler code
// timeoutWriter is borrowed from the net/http package to help prevent data races.
type timeoutWriter struct {
w http.ResponseWriter
h http.Header
wbuf bytes.Buffer
mu sync.Mutex
timedOut bool
wroteHeader bool
code int
}
func (tw *timeoutWriter) Header() http.Header { return tw.h }
func (tw *timeoutWriter) Write(p []byte) (int, error) {
tw.mu.Lock()
defer tw.mu.Unlock()
if tw.timedOut {
return 0, http.ErrHandlerTimeout
}
if !tw.wroteHeader {
tw.writeHeader(http.StatusOK)
}
return tw.wbuf.Write(p)
}
func (tw *timeoutWriter) WriteHeader(code int) {
tw.mu.Lock()
defer tw.mu.Unlock()
if tw.timedOut || tw.wroteHeader {
return
}
tw.writeHeader(code)
}
func (tw *timeoutWriter) writeHeader(code int) {
tw.wroteHeader = true
tw.code = code
}