forked from ant0ine/go-json-rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recorder.go
52 lines (40 loc) · 1.09 KB
/
recorder.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
package rest
import (
"net/http"
)
type recorderResponseWriter struct {
http.ResponseWriter
statusCode int
wroteHeader bool
}
func (self *recorderResponseWriter) WriteHeader(code int) {
self.Header().Add("X-Powered-By", "go-json-rest")
self.ResponseWriter.WriteHeader(code)
self.statusCode = code
self.wroteHeader = true
}
func (self *recorderResponseWriter) Flush() {
if !self.wroteHeader {
self.WriteHeader(http.StatusOK)
}
flusher := self.ResponseWriter.(http.Flusher)
flusher.Flush()
}
func (self *recorderResponseWriter) CloseNotify() <-chan bool {
notifier := self.ResponseWriter.(http.CloseNotifier)
return notifier.CloseNotify()
}
func (self *recorderResponseWriter) Write(b []byte) (int, error) {
if !self.wroteHeader {
self.WriteHeader(http.StatusOK)
}
return self.ResponseWriter.Write(b)
}
func (self *ResourceHandler) recorderWrapper(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
writer := &recorderResponseWriter{w, 0, false}
// call the handler
h(writer, r)
self.env.setVar(r, "statusCode", writer.statusCode)
}
}