-
Notifications
You must be signed in to change notification settings - Fork 34
/
response_writer.go
107 lines (88 loc) · 2.28 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
96
97
98
99
100
101
102
103
104
105
106
107
package traffic
import (
"encoding/json"
"encoding/xml"
"fmt"
"net/http"
)
type ResponseWriter interface {
http.ResponseWriter
SetVar(string, interface{})
GetVar(string) interface{}
StatusCode() int
Written() bool
BodyWritten() bool
Render(string, ...interface{})
WriteJSON(data interface{})
WriteXML(data interface{})
WriteText(string, ...interface{})
}
type responseWriter struct {
http.ResponseWriter
written bool
bodyWritten bool
statusCode int
env map[string]interface{}
routerEnv *map[string]interface{}
beforeWriteHandlers []func()
}
func (w *responseWriter) Write(data []byte) (n int, err error) {
w.written = true
w.bodyWritten = true
return w.ResponseWriter.Write(data)
}
func (w *responseWriter) WriteHeader(statusCode int) {
w.statusCode = statusCode
w.ResponseWriter.WriteHeader(statusCode)
w.written = true
}
func (w *responseWriter) StatusCode() int {
return w.statusCode
}
func (w *responseWriter) SetVar(key string, value interface{}) {
w.env[key] = value
}
func (w *responseWriter) Written() bool {
return w.written
}
func (w *responseWriter) BodyWritten() bool {
return w.bodyWritten
}
func (w *responseWriter) GetVar(key string) interface{} {
// local env
value := w.env[key]
if value != nil {
return value
}
// router env
value = (*w.routerEnv)[key]
if value != nil {
return value
}
// global env
return GetVar(key)
}
func (w *responseWriter) Render(templateName string, data ...interface{}) {
RenderTemplate(w, templateName, data...)
}
func (w *responseWriter) WriteJSON(data interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(data)
}
func (w *responseWriter) WriteXML(data interface{}) {
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
xml.NewEncoder(w).Encode(data)
}
func (w *responseWriter) WriteText(textFormat string, data ...interface{}) {
fmt.Fprintf(w, textFormat, data...)
}
func newResponseWriter(w http.ResponseWriter, routerEnv *map[string]interface{}) *responseWriter {
rw := &responseWriter{
ResponseWriter: w,
statusCode: http.StatusOK,
env: make(map[string]interface{}),
routerEnv: routerEnv,
beforeWriteHandlers: make([]func(), 0),
}
return rw
}