-
Notifications
You must be signed in to change notification settings - Fork 0
/
response_writer.go
95 lines (85 loc) · 2.4 KB
/
response_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
package chain
import (
"errors"
"log/slog"
"net/http"
)
// ErrAlreadySent Error raised when trying to modify or send an already sent response
var ErrAlreadySent = errors.New("the response was already sent")
type ResponseWriterSpy struct {
http.ResponseWriter
status int // status code passed to WriteHeader
writeStarted bool
writeCalled bool
writeHeaderCalled bool
beforeWriteHeaderHooks []func()
afterWriteHooks []func()
}
func (w *ResponseWriterSpy) Status() int {
return w.status
}
func (w *ResponseWriterSpy) WriteHeader(status int) {
w.status = status
w.writeHeaderCalled = true
w.execBeforeWriteHeaderHooks()
w.ResponseWriter.WriteHeader(status)
}
func (w *ResponseWriterSpy) Write(b []byte) (int, error) {
if w.status == 0 {
w.status = http.StatusOK
}
w.writeCalled = true
if !w.writeStarted {
w.execBeforeWriteHeaderHooks()
}
return w.ResponseWriter.Write(b)
}
// beforeWriteHeader Registers a callback to be invoked before the response is sent.
//
// Callbacks are invoked in the reverse order they are defined (callbacks defined first are invoked last).
func (w *ResponseWriterSpy) beforeWriteHeader(callback func()) error {
if w.writeStarted {
return ErrAlreadySent
}
w.beforeWriteHeaderHooks = append(w.beforeWriteHeaderHooks, callback)
return nil
}
// afterWrite Registers a callback to be invoked before the response is sent.
//
// Callbacks are invoked in the reverse order they are defined (callbacks defined first are invoked last).
func (w *ResponseWriterSpy) afterWrite(callback func()) error {
if w.writeStarted {
return ErrAlreadySent
}
w.afterWriteHooks = append(w.afterWriteHooks, func() {
defer func() {
// no panic
if r := recover(); r != nil {
slog.Warn("[chain] panic occured in a after write hook", slog.Any("panic", r))
}
}()
callback()
})
return nil
}
func (w *ResponseWriterSpy) execBeforeWriteHeaderHooks() {
if w.writeStarted {
return
}
w.writeStarted = true
if w.beforeWriteHeaderHooks != nil {
for i := len(w.beforeWriteHeaderHooks) - 1; i >= 0; i-- {
w.beforeWriteHeaderHooks[i]()
}
}
w.beforeWriteHeaderHooks = nil
}
// execAfterWriteHooksCalledByRouter called by router.ServeHTTP
func (w *ResponseWriterSpy) execAfterWriteHooksCalledByRouter() {
if w.afterWriteHooks != nil {
for i := len(w.afterWriteHooks) - 1; i >= 0; i-- {
w.afterWriteHooks[i]()
}
}
w.afterWriteHooks = nil
}