-
Notifications
You must be signed in to change notification settings - Fork 2
/
response.go
93 lines (77 loc) · 1.8 KB
/
response.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
package binding
import (
"encoding/json"
"reflect"
"github.com/gocraft/web"
)
type response struct {
Error *string `json:",omitempty"`
ErrorCode *int `json:",omitempty"`
Success *string `json:",omitempty"`
Data interface{} `json:",omitempty"`
}
var ok = "ok"
func SuccessResponse(data interface{}) *response {
if s, ok := data.(string); ok {
return &response{
Success: &s,
}
}
return &response{
Success: &ok,
Data: data,
}
}
func ErrorResponse(err string, code int) *response {
return &response{
Error: &err,
ErrorCode: &code,
}
}
func Response(errorHandlerCustom func(web.ResponseWriter, error)) func(
interface{}, web.ResponseWriter, *web.Request, web.NextMiddlewareFunc) {
errorHandler := ErrorHandler
if errorHandlerCustom != nil {
errorHandler = errorHandlerCustom
}
return func(ctx interface{}, rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
next(rw, r)
t := reflect.ValueOf(ctx)
if t.Type().Kind() != reflect.Ptr {
panic("expected pointer to struct")
}
t = t.Elem()
var (
data []byte
err error
responseField = t.FieldByName("ResponseJSON")
)
if responseField.IsValid() && !responseField.IsNil() {
if responseField.Kind() == reflect.String {
data = []byte(responseField.String())
} else {
data, err = json.Marshal(responseField.Addr().Interface())
if err != nil {
errorHandler(rw, err)
return
}
}
}
if rw.StatusCode() == 0 {
statusCodeField := t.FieldByName("ResponseStatus")
if statusCodeField.IsValid() {
statusCode := statusCodeField.Int()
if statusCode > 0 {
rw.WriteHeader(int(statusCode))
}
}
}
if len(data) > 0 {
_, err = rw.Write(data)
if err != nil {
errorHandler(rw, err)
return
}
}
}
}