-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.go
More file actions
285 lines (264 loc) · 7.18 KB
/
util.go
File metadata and controls
285 lines (264 loc) · 7.18 KB
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
package restruct
import (
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"reflect"
"strconv"
"strings"
"github.com/altlimit/restruct/structtag"
)
var (
MaxBodySize int64 = 10485760 // 10MB default limit
// Pre-cached slice types for BindQuery
intSlice = reflect.TypeOf([]int{})
int64Slice = reflect.TypeOf([]int64{})
stringSlice = reflect.TypeOf([]string{})
)
// Params returns map of params from url path like /{param1} will be map[param1] = value
func Params(r *http.Request) map[string]string {
return Vars(r.Context())
}
// Vars returns map of params from url from request context
func Vars(ctx context.Context) map[string]string {
if params, ok := ctx.Value(keyParams).(map[string]string); ok {
return params
}
return map[string]string{}
}
// SetVars returns a new context with the given route params set.
// Useful for testing handlers that read route parameters via Vars.
func SetVars(ctx context.Context, params map[string]string) context.Context {
return context.WithValue(ctx, keyParams, params)
}
// SetParams returns a new request with the given route params set.
// Useful for testing handlers that read route parameters via Params.
func SetParams(r *http.Request, params map[string]string) *http.Request {
return r.WithContext(SetVars(r.Context(), params))
}
// Query returns a query string value
func Query(r *http.Request, name string) string {
return r.URL.Query().Get(name)
}
// Bind checks for valid methods and tries to bind query strings and body into struct
func Bind(r *http.Request, out interface{}, methods ...string) error {
if len(methods) > 0 {
found := false
for _, m := range methods {
if r.Method == m {
found = true
break
}
}
if !found {
return Error{Status: http.StatusMethodNotAllowed}
}
}
if out == nil {
return nil
}
if len(r.URL.Query()) > 0 {
if err := BindQuery(r, out); err != nil {
return err
}
}
if r.Method == http.MethodGet {
return nil
}
cType := r.Header.Get("Content-Type")
if idx := strings.Index(cType, ";"); idx != -1 {
cType = cType[0:idx]
}
switch cType {
case "application/json":
return BindJson(r, out)
case "application/x-www-form-urlencoded", "multipart/form-data":
return BindForm(r, out)
}
return Error{Status: http.StatusUnsupportedMediaType}
}
// BindJson puts all json tagged values into struct fields
func BindJson(r *http.Request, out interface{}) error {
// Limit request body reading
reader := io.LimitReader(r.Body, MaxBodySize)
body, err := io.ReadAll(reader)
if err != nil {
return fmt.Errorf("Bind: io.ReadAll error %v", err)
}
if err := r.Body.Close(); err != nil {
return fmt.Errorf("Bind: r.Body.Close error %v", err)
}
if err := json.Unmarshal(body, out); err != nil {
return Error{
Status: http.StatusBadRequest,
Err: fmt.Errorf("Bind: json.Unmarshal error %v", err),
}
}
return nil
}
// BindQuery puts all query string values into struct fields with tag:"query"
func BindQuery(r *http.Request, out interface{}) error {
t := reflect.TypeOf(out)
v := reflect.ValueOf(out)
if t.Kind() == reflect.Ptr {
v = v.Elem()
}
toTypeSlice := func(vals reflect.Value, sliceType reflect.Type) interface{} {
if sliceType == stringSlice {
return vals.Interface()
}
newVals := reflect.New(sliceType).Elem()
for i := 0; i < vals.Len(); i++ {
val := vals.Index(i).String()
var v interface{}
switch sliceType {
case intSlice:
v, _ = strconv.Atoi(val)
case int64Slice:
v, _ = strconv.ParseInt(val, 10, 64)
default:
v = nil
}
if v != nil {
newVals = reflect.Append(newVals, reflect.ValueOf(v))
}
}
return newVals.Interface()
}
for _, field := range structtag.GetFieldsByTag(out, "query") {
tag := field.Tag
if q := Query(r, tag); q != "" {
vv := v.Field(field.Index)
vk := vv.Kind()
if vk != reflect.String {
var val interface{}
switch vk {
case reflect.Int:
val, _ = strconv.Atoi(q)
case reflect.Int64:
val, _ = strconv.ParseInt(q, 10, 64)
case reflect.Slice:
val = toTypeSlice(reflect.ValueOf(r.URL.Query()[tag]), vv.Type())
}
vv.Set(reflect.ValueOf(val))
} else {
vv.Set(reflect.ValueOf(q))
}
}
}
return nil
}
// BindForm puts all struct fields with tag:"form" from a form request
func BindForm(r *http.Request, out interface{}) error {
t := reflect.TypeOf(out)
v := reflect.ValueOf(out)
if t.Kind() == reflect.Ptr {
v = v.Elem()
}
cType := r.Header.Get("Content-Type")
formValues := make(map[string]interface{})
if strings.HasPrefix(cType, "application/x-www-form-urlencoded") {
r.ParseForm()
for k := range r.PostForm {
formValues[k] = r.PostFormValue(k)
}
} else if strings.Contains(cType, "multipart/form-data") {
r.ParseMultipartForm(32 << 20)
for k := range r.PostForm {
formValues[k] = r.FormValue(k)
}
for k, v := range r.MultipartForm.File {
if strings.HasSuffix(k, "[]") {
formValues[k[:len(k)-2]] = v
} else {
formValues[k] = v[0]
}
}
}
if len(formValues) == 0 {
return nil
}
for _, field := range structtag.GetFieldsByTag(out, "form") {
tag := field.Tag
if formVal, ok := formValues[tag]; ok {
vv := v.Field(field.Index)
vk := vv.Kind()
var val interface{}
if vk == reflect.String {
if v, ok := formVal.(string); ok {
val = v
}
} else {
switch vk {
case reflect.Int:
v := formVal.(string)
val, _ = strconv.Atoi(v)
case reflect.Int64:
v := formVal.(string)
val, _ = strconv.ParseInt(v, 10, 64)
case reflect.Float64:
v := formVal.(string)
val, _ = strconv.ParseFloat(v, 64)
case reflect.Ptr:
if vv.Type() == typeMultipartFileHeader {
if fh, ok := formVal.(*multipart.FileHeader); ok {
val = fh
}
}
case reflect.Slice:
if vv.Type() == typeMultipartFileHeaderSlice {
val = formVal
}
}
}
if val != nil {
vv.Set(reflect.ValueOf(val))
}
}
}
return nil
}
func GetVals(ctx context.Context) map[string]interface{} {
if vals, ok := ctx.Value(keyVals).(map[string]interface{}); ok {
return vals
}
return make(map[string]interface{})
}
func SetVal(ctx context.Context, key string, val interface{}) context.Context {
// Copy-on-write: get existing map, copy it, add new val, return new context
existing := GetVals(ctx)
newVals := make(map[string]interface{}, len(existing)+1)
for k, v := range existing {
newVals[k] = v
}
newVals[key] = val
return context.WithValue(ctx, keyVals, newVals)
}
func GetVal(ctx context.Context, key string) interface{} {
return GetVals(ctx)[key]
}
// GetValues returns a map of all values from context
func GetValues(r *http.Request) map[string]interface{} {
return GetVals(r.Context())
}
// SetValue stores a key value pair in context
func SetValue(r *http.Request, key string, val interface{}) *http.Request {
return r.WithContext(SetVal(r.Context(), key, val))
}
// GetValue returns the stored value from context
func GetValue(r *http.Request, key string) interface{} {
return GetVal(r.Context(), key)
}
func refTypes(types ...reflect.Type) []reflect.Type {
return types
}
func refVals(vals ...interface{}) []reflect.Value {
values := make([]reflect.Value, len(vals))
for i, v := range vals {
values[i] = reflect.ValueOf(v)
}
return values
}