-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonResponse.go
70 lines (60 loc) · 1.56 KB
/
jsonResponse.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
package httpserve
import (
"encoding/json"
"fmt"
"io"
)
// NewJSONResponse will return a new text response
func NewJSONResponse(code int, value interface{}) *JSONResponse {
var j JSONResponse
j.code = code
j.val = value
return &j
}
// JSONResponse is a basic text response
type JSONResponse struct {
code int
val interface{}
}
// ContentType returns the content type
func (j *JSONResponse) ContentType() (contentType string) {
return "application/json"
}
// StatusCode returns the status code
func (j *JSONResponse) StatusCode() (code int) {
return j.code
}
func (j *JSONResponse) newValue() (value JSONValue, err error) {
if j.code < 400 {
// Status code is not an error code, set the data as the associated value and return.
value.Data = j.val
return
}
// Switch on associated value's type
switch v := j.val.(type) {
case error:
// Type is a single error value, create new error slice with error as only item
value.Errors.Push(v)
case []error:
// Type is an error slice, set errors as the value
value.Errors.Copy(v)
default:
// Invalid error value, return error
err = fmt.Errorf("invalid type for an error response: %#v", v)
}
return
}
// WriteTo will write to a given io.Writer
func (j *JSONResponse) WriteTo(w io.Writer) (n int64, err error) {
var value JSONValue
// Initialize a new JSON value
if value, err = j.newValue(); err != nil {
// Error encountered while initializing responder, return early
return
}
// Initialize a new JSON encoder
enc := json.NewEncoder(w)
// Encode the responder
err = enc.Encode(value)
return
}