-
Notifications
You must be signed in to change notification settings - Fork 0
/
response_writer.go
196 lines (185 loc) · 4.32 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package restruct
import (
"encoding/json"
"log"
"net/http"
"reflect"
)
type (
// ResponseWriter is called on outputs of your methods.
// slice of reflect.Type & Value is the types and returned values
ResponseWriter interface {
Write(http.ResponseWriter, *http.Request, []reflect.Type, []reflect.Value)
}
// DefaultWriter uses json.Encoder for output
// and manages error handling. Adding Errors mapping can
// help with your existing error to a proper Error{}
DefaultWriter struct {
// Optional ErrorHandler, called whenever unhandled errors occurs, defaults to logging errors
ErrorHandler func(error)
Errors map[error]Error
EscapeJsonHtml bool
}
// Response is used by DefaultWriter for custom response
Response struct {
Status int
Headers map[string]string
ContentType string
Content []byte
}
// Json response to specify a status code for default writer
Json struct {
Status int
Content interface{}
}
)
// Write implements the DefaultWriter ResponseWriter
// returning (int, any, error) will write status int, any response if error is nil
// returning (any, error) will write any response if error is nil with status 200 or 400, 500 depdening on your error
// returning (int, any, any, error) will write status int slice of [any, any] response if error is nil
func (dw *DefaultWriter) Write(w http.ResponseWriter, r *http.Request, types []reflect.Type, vals []reflect.Value) {
// no returns are not sent here so we just check if 1 or more
lt := len(types)
if lt == 1 {
val := vals[0].Interface()
if resp, ok := val.(*Response); ok {
dw.WriteResponse(w, resp)
} else {
dw.WriteJSON(w, val)
}
return
}
var (
out interface{}
j *Json
)
defer func() {
if j != nil {
j.Content = out
out = j
}
dw.WriteJSON(w, out)
}()
// return with last type error
if types[lt-1] == typeError {
errVal := vals[lt-1]
if !errVal.IsNil() {
out = errVal.Interface()
return
}
vals = vals[:lt-1]
}
// returning (int, something) means status code, response
if len(vals) > 1 && types[0] == typeInt {
j = &Json{Status: int(vals[0].Int())}
vals = vals[1:]
}
if len(vals) == 1 {
out = vals[0].Interface()
return
}
var args []interface{}
for _, v := range vals {
args = append(args, v.Interface())
}
out = args
}
func (dw *DefaultWriter) log(err error) {
if dw.ErrorHandler == nil {
dw.ErrorHandler = func(err error) {
log.Println("InternalError:", err)
}
}
dw.ErrorHandler(err)
}
// This writes application/json content type uses status code 200
// on valid ones and 500 on uncaught, 400 on malformed json, etc.
// use Json{Status, Content} to specify a code
func (dw *DefaultWriter) WriteJSON(w http.ResponseWriter, out interface{}) {
if w == nil {
return
}
status := http.StatusOK
if j, ok := out.(*Json); ok {
if j.Status > 0 {
status = j.Status
}
out = j.Content
}
if out == nil {
w.WriteHeader(status)
return
}
cType := "application/json; charset=UTF-8"
var headers map[string]string
if err, ok := out.(error); ok {
status = http.StatusInternalServerError
var (
msg string
errData interface{}
)
e, ok := err.(Error)
if dw.Errors != nil && !ok {
if ee, k := dw.Errors[err]; k {
ok = true
e = ee
}
}
if ok {
if e.Status != 0 {
status = e.Status
}
if e.Message != "" {
msg = e.Message
}
if e.Data != nil {
errData = e.Data
}
if e.Err != nil {
dw.log(e.Err)
}
} else {
dw.log(err)
}
if msg == "" {
msg = http.StatusText(status)
}
errResp := map[string]interface{}{
"error": msg,
}
if errData != nil {
errResp["data"] = errData
}
out = errResp
}
w.WriteHeader(status)
h := w.Header()
foundContentType := false
for k, v := range headers {
if k == "Content-Type" {
foundContentType = true
}
h.Add(k, v)
}
if !foundContentType {
h.Set("Content-Type", cType)
}
enc := json.NewEncoder(w)
enc.SetEscapeHTML(dw.EscapeJsonHtml)
if err := enc.Encode(out); err != nil {
dw.log(err)
}
}
func (dw *DefaultWriter) WriteResponse(w http.ResponseWriter, resp *Response) {
if resp.Status > 0 {
w.WriteHeader(resp.Status)
}
if resp.ContentType != "" && w.Header().Get("Content-Type") == "" {
w.Header().Add("Content-Type", resp.ContentType)
}
if len(resp.Content) > 0 {
if _, err := w.Write(resp.Content); err != nil {
dw.log(err)
}
}
}