-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.go
190 lines (157 loc) · 4.29 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
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
package apirouter
import (
"encoding/json"
"io"
"net/http"
"reflect"
"strings"
"github.com/matryer/respond"
)
// AllowedKeys is for allowed keys
type AllowedKeys map[string]interface{}
// ReturnResponse helps return a status code and message to the end user
func ReturnResponse(w http.ResponseWriter, req *http.Request, code int, data interface{}) {
// w.Header().Set(connectionHeader, "close")
respond.With(w, req, code, data)
}
// ReturnJSONEncode is a mixture of ReturnResponse and JSONEncode
func ReturnJSONEncode(w http.ResponseWriter, code int, e *json.Encoder, objects interface{}, allowed []string) (err error) {
// Set the content if JSON
w.Header().Set(contentTypeHeader, "application/json")
// Close the connection
// w.Header().Set(connectionHeader, "close")
// Set the header status code
w.WriteHeader(code)
// Attempt to encode the objects
err = JSONEncode(e, objects, allowed)
return
}
// JSONEncodeHierarchy will execute JSONEncode for multiple nested objects
func JSONEncodeHierarchy(w io.Writer, objects interface{}, allowed interface{}) error {
if slice, ok := allowed.([]string); ok {
return JSONEncode(json.NewEncoder(w), objects, slice)
} else if obj, ok := allowed.(AllowedKeys); ok {
data := reflect.ValueOf(objects).Elem().Interface()
t := reflect.TypeOf(data)
v := reflect.ValueOf(data)
numFields := t.NumField()
_, _ = w.Write([]byte{'{'})
for i := 0; i < numFields; i++ {
field := t.Field(i)
jsonTag := field.Tag.Get("json")
if len(jsonTag) == 0 {
jsonTag = field.Name
}
keys := obj[jsonTag]
if keys != nil {
_, _ = w.Write([]byte("\""))
_, _ = w.Write([]byte(jsonTag))
_, _ = w.Write([]byte("\": "))
err := JSONEncodeHierarchy(w, v.Field(i).Interface(), keys)
if err != nil {
return err
}
if i != numFields-1 {
_, _ = w.Write([]byte{','})
}
}
}
_, _ = w.Write([]byte{'}'})
}
return nil
}
// JSONEncode will encode only the allowed fields of the models
func JSONEncode(e *json.Encoder, objects interface{}, allowed []string) error {
var data []map[string]interface{}
isMulti := false
count := 0
if reflect.TypeOf(objects).Kind() == reflect.Slice {
count = reflect.ValueOf(objects).Len()
data = make([]map[string]interface{}, count)
isMulti = true
}
if isMulti {
if count == 0 {
return e.Encode(make([]interface{}, 0))
}
raw := reflect.ValueOf(objects)
obj := jsonMap(raw.Index(0).Interface())
toRemove := make([]string, 0)
for k := range obj {
if FindString(k, allowed) == -1 {
toRemove = append(toRemove, k)
}
}
for _, k := range toRemove {
delete(obj, k)
}
if data != nil {
data[0] = obj
}
for i := 1; i < count; i++ {
obj = jsonMap(raw.Index(i).Interface())
for _, k := range toRemove {
delete(obj, k)
}
if data != nil {
data[i] = obj
}
}
return e.Encode(data)
}
obj := jsonMap(objects)
toRemove := make([]string, 0)
for k := range obj {
if FindString(k, allowed) == -1 {
toRemove = append(toRemove, k)
}
}
for _, k := range toRemove {
delete(obj, k)
}
return e.Encode(obj)
}
// jsonMap converts an object to a map of string interfaces
func jsonMap(obj interface{}) map[string]interface{} {
fieldValues := make(map[string]interface{})
var s, stringPointer reflect.Value
// Dereference the obj if it is a pointer
if reflect.ValueOf(obj).Kind() == reflect.Ptr {
stringPointer = reflect.ValueOf(obj)
s = stringPointer.Elem()
} else {
s = reflect.ValueOf(obj)
// stringPointer = reflect.ValueOf(&obj)
}
typeOfT := s.Type()
for i := 0; i < typeOfT.NumField(); i++ {
structField := typeOfT.Field(i)
fieldName := structField.Name
if fieldName[0] != strings.ToUpper(string(fieldName[0]))[0] {
continue
}
// Exclude any field starting with an underscore
if strings.Index(fieldName, "_") == 0 {
continue
}
val := s.Field(i)
// Check for embedded types
if structField.Anonymous {
subFields := jsonMap(val.Interface())
for k, v := range subFields {
fieldValues[k] = v
}
continue
}
key := SnakeCase(fieldName)
comps := strings.Split(key, ",")
key = comps[0]
fieldType := structField.Type
if fieldType.Kind() != reflect.Ptr && val.CanAddr() {
// fieldType = reflect.PtrTo(fieldType)
val = val.Addr()
}
fieldValues[key] = val.Interface()
}
return fieldValues
}