/
resp.go
428 lines (363 loc) · 10.1 KB
/
resp.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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
package apiserv
import (
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"log"
"net/http"
"github.com/missionMeteora/apiserv/internal"
tkErrors "github.com/missionMeteora/toolkit/errors"
"go.oneofone.dev/otk"
)
var EnableCacheResponse bool
var bufPool otk.BufferPool
// Common responses
var (
RespMethodNotAllowed Response = NewJSONErrorResponse(http.StatusMethodNotAllowed)
RespNotFound Response = NewJSONErrorResponse(http.StatusNotFound)
RespForbidden Response = NewJSONErrorResponse(http.StatusForbidden)
RespBadRequest Response = NewJSONErrorResponse(http.StatusBadRequest)
RespOK Response = NewJSONResponse("OK")
RespEmpty Response = &simpleResp{code: http.StatusNoContent}
RespPlainOK Response = &simpleResp{code: http.StatusOK}
RespRedirectRoot = Redirect("/", false)
// Break can be returned from a handler to break a handler chain.
// It doesn't write anything to the connection.
// if you reassign this, a wild animal will devour your face.
Break Response = &simpleResp{}
)
// Common mime-types
const (
MimeJSON = "application/json; charset=utf-8"
MimeXML = "application/xml; charset=utf-8"
MimeJavascript = "application/javascript; charset=utf-8"
MimeHTML = "text/html; charset=utf-8"
MimePlain = "text/plain; charset=utf-8"
MimeBinary = "application/octet-stream"
)
// Response represents a generic return type for http responses.
type Response interface {
WriteToCtx(ctx *Context) error
}
// NewJSONResponse returns a new success response (code 200) with the specific data
func NewJSONResponse(data interface{}) *JSONResponse {
if !EnableCacheResponse {
return &JSONResponse{
Code: http.StatusOK,
Success: true,
Data: data,
}
}
bp := bufPool.Get()
if err := json.NewEncoder(bp).Encode(data); err != nil {
return &JSONResponse{
Code: http.StatusInternalServerError,
Errors: []Error{{Message: err.Error()}},
}
}
return &JSONResponse{
Code: http.StatusOK,
Data: bp,
}
}
// ReadJSONResponse reads a response from an io.ReadCloser and closes the body.
// dataValue is the data type you're expecting, for example:
// r, err := ReadJSONResponse(res.Body, &map[string]*Stats{})
func ReadJSONResponse(rc io.ReadCloser, dataValue interface{}) (r *JSONResponse, err error) {
defer rc.Close()
r = &JSONResponse{
Data: dataValue,
}
if err = json.NewDecoder(rc).Decode(r); err != nil {
return
}
if r.Success {
return
}
var me MultiError
for _, v := range r.Errors {
me.Push(&v)
}
if err = me.Err(); err == nil {
err = errors.New(http.StatusText(r.Code))
}
return
}
func JSONRequest(method, url string, reqData, respData interface{}) (err error) {
return otk.Request(method, "", url, reqData, func(r *http.Response) error {
_, err := ReadJSONResponse(r.Body, respData)
return err
})
}
// JSONResponse is the default standard api response
type JSONResponse struct {
Data interface{} `json:"data,omitempty"`
Errors []Error `json:"errors,omitempty"`
Code int `json:"code"`
Success bool `json:"success"`
Indent bool `json:"-"`
}
// WriteToCtx writes the response to a ResponseWriter
func (r *JSONResponse) WriteToCtx(ctx *Context) error {
switch r.Code {
case 0:
if len(r.Errors) > 0 {
r.Code = http.StatusBadRequest
} else {
r.Code = http.StatusOK
}
case http.StatusNoContent: // special case
ctx.WriteHeader(http.StatusNoContent)
return nil
}
r.Success = r.Code >= http.StatusOK && r.Code < http.StatusBadRequest
if bp, ok := r.Data.(*otk.Buffer); ok {
defer bufPool.Put(bp)
r.Data = json.RawMessage(bp.Bytes())
}
return ctx.JSON(r.Code, r.Indent, r)
}
func NewXMLResponse(data interface{}) *XMLResponse {
return &XMLResponse{
Code: http.StatusOK,
Data: data,
}
}
// XMLResponse is the default standard api response using xml from data
type XMLResponse struct {
Data interface{} `json:"data,omitempty"`
Errors []*Error `json:"errors,omitempty"`
Code int `json:"code"`
Success bool `json:"success"`
Indent bool `json:"-"`
}
type xmlErrorResponse struct {
XMLName xml.Name `xml:"errors"`
Errors []*Error `json:"errors,omitempty" xml:"errors,omitempty"`
}
// WriteToCtx writes the response to a ResponseWriter
func (r *XMLResponse) WriteToCtx(ctx *Context) error {
switch r.Code {
case 0:
if len(r.Errors) > 0 {
r.Code = http.StatusBadRequest
} else {
r.Code = http.StatusOK
}
case http.StatusNoContent: // special case
ctx.WriteHeader(http.StatusNoContent)
return nil
}
r.Success = r.Code >= http.StatusOK && r.Code < http.StatusBadRequest
ctx.SetContentType(MimeXML)
ctx.WriteHeader(r.Code)
ctx.Write([]byte(xml.Header))
enc := xml.NewEncoder(ctx)
if r.Indent {
enc.Indent("", "\t")
}
if len(r.Errors) > 0 {
er := &xmlErrorResponse{Errors: r.Errors}
return enc.Encode(er)
}
return enc.Encode(r.Data)
}
// NewJSONErrorResponse returns a new error response.
// each err can be:
// 1. string or []byte
// 2. error
// 3. Error / *Error
// 4. another response, its Errors will be appended to the returned Response.
// 5. MultiError
// 6. if errs is empty, it will call http.StatusText(code) and set that as the error.
func NewJSONErrorResponse(code int, errs ...interface{}) (r *JSONResponse) {
if len(errs) == 0 {
errs = append(errs, http.StatusText(code))
}
r = &JSONResponse{
Code: code,
Errors: make([]Error, 0, len(errs)),
}
for _, err := range errs {
r.appendErr(err)
}
return r
}
// ErrorList returns an errors.ErrorList of this response's errors or nil.
// Deprecated: handled using MultiError
func (r *JSONResponse) ErrorList() *tkErrors.ErrorList {
if len(r.Errors) == 0 {
return nil
}
var el tkErrors.ErrorList
for _, err := range r.Errors {
err := err
el.Push(&err)
}
return &el
}
func (r *JSONResponse) appendErr(err interface{}) {
switch v := err.(type) {
case Error:
r.Errors = append(r.Errors, v)
case *Error:
r.Errors = append(r.Errors, *v)
case string:
r.Errors = append(r.Errors, Error{Message: v})
case []byte:
r.Errors = append(r.Errors, Error{Message: string(v)})
case *JSONResponse:
r.Errors = append(r.Errors, v.Errors...)
case MultiError:
for _, err := range v {
r.appendErr(err)
}
case error:
r.Errors = append(r.Errors, Error{Message: v.Error()})
default:
log.Panicf("unsupported error type (%T): %v", v, v)
}
}
// Error is returned in the error field of a Response.
type Error struct {
Message string `json:"message,omitempty"`
Field string `json:"field,omitempty"`
IsMissing bool `json:"isMissing,omitempty"`
}
func (e *Error) Error() string {
j, _ := internal.MarshalIndent(e)
return string(j)
}
// Redirect returns a redirect Response.
// if perm is false it uses http.StatusFound (302), otherwise http.StatusMovedPermanently (302)
func Redirect(url string, perm bool) Response {
code := http.StatusFound
if perm {
code = http.StatusMovedPermanently
}
return RedirectWithCode(url, code)
}
// RedirectWithCode returns a redirect Response with the specified status code.
func RedirectWithCode(url string, code int) Response {
return redirResp{url, code}
}
type redirResp struct {
url string
code int
}
func (r redirResp) WriteToCtx(ctx *Context) error {
if r.url == "" {
return ErrInvalidURL
}
http.Redirect(ctx, ctx.Req, r.url, r.code)
return nil
}
// File returns a file response.
// example: return File("plain/html", "index.html")
func File(contentType, fp string) Response {
return fileResp{contentType, fp}
}
type fileResp struct {
ct string
fp string
}
func (f fileResp) WriteToCtx(ctx *Context) error {
if f.ct != "" {
ctx.SetContentType(f.ct)
}
return ctx.File(f.fp)
}
// PlainResponse returns SimpleResponse(200, contentType, val).
func PlainResponse(contentType string, val interface{}) Response {
return SimpleResponse(http.StatusOK, contentType, val)
}
// SimpleResponse is a QoL wrapper to return a response with the specified code and content-type.
// val can be: nil, []byte, string, io.Writer, anything else will be written with fmt.Printf("%v").
func SimpleResponse(code int, contentType string, val interface{}) Response {
return &simpleResp{
ct: contentType,
v: val,
code: code,
}
}
type simpleResp struct {
v interface{}
ct string
code int
}
func (r *simpleResp) WriteToCtx(ctx *Context) error {
if r.ct != "" {
ctx.SetContentType(r.ct)
}
if r.code > 0 {
ctx.WriteHeader(r.code)
}
var err error
switch v := r.v.(type) {
case nil:
case []byte:
_, err = ctx.Write(v)
case string:
_, err = io.WriteString(ctx, v)
case io.Reader:
_, err = io.Copy(ctx, v)
default:
_, err = fmt.Fprintf(ctx, "%v", r.v)
}
return err
}
// NewJSONPResponse returns a new success response (code 200) with the specific data
func NewJSONPResponse(callbackKey string, data interface{}) *JSONPResponse {
return &JSONPResponse{
Callback: callbackKey,
JSONResponse: JSONResponse{
Code: http.StatusOK,
Data: data,
},
}
}
// NewJSONPErrorResponse returns a new error response.
// each err can be:
// 1. string or []byte
// 2. error
// 3. Error / *Error
// 4. another response, its Errors will be appended to the returned Response.
// 5. if errs is empty, it will call http.StatusText(code) and set that as the error.
func NewJSONPErrorResponse(callbackKey string, code int, errs ...interface{}) *JSONPResponse {
if len(errs) == 0 {
errs = append(errs, http.StatusText(code))
}
if len(callbackKey) == 0 {
callbackKey = "console.error"
}
r := &JSONPResponse{
JSONResponse: JSONResponse{
Code: code,
Errors: make([]Error, 0, len(errs)),
},
Callback: callbackKey,
}
for _, err := range errs {
r.appendErr(err)
}
return r
}
// JSONPResponse is the default standard api response
type JSONPResponse struct {
Callback string `json:"-"`
JSONResponse
}
// WriteToCtx writes the response to a ResponseWriter
func (r *JSONPResponse) WriteToCtx(ctx *Context) error {
switch r.Code {
case 0:
r.Code = http.StatusOK
case http.StatusNoContent: // special case
ctx.WriteHeader(http.StatusNoContent)
return nil
}
r.Success = r.Code >= http.StatusOK && r.Code < http.StatusBadRequest
return ctx.JSONP(http.StatusOK, r.Callback, r)
}