-
Notifications
You must be signed in to change notification settings - Fork 6
/
query.go
440 lines (371 loc) · 11.3 KB
/
query.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
429
430
431
432
433
434
435
436
437
438
439
440
package jsonmap
import (
"errors"
"fmt"
"net/http"
"reflect"
"regexp"
"strconv"
"time"
)
// This is the overarching struct used to transform structs into url params
// and vice versa
type QueryMap struct {
UnderlyingType interface{}
ParameterMaps []ParameterMap
}
// Taking a struct and turning it into a url param. The precise mechanisms of doing
// so are are defined in the individual ParameterMap
func (qm QueryMap) Encode(src interface{}, urlQuery map[string][]string) error {
srcVal := reflect.ValueOf(src)
for _, p := range qm.ParameterMaps {
fieldVal := srcVal.FieldByName(p.StructFieldName)
if fieldVal.IsZero() && p.OmitEmpty {
continue
}
strVal, err := p.Mapper.Encode(fieldVal)
if err != nil {
return errors.New("error in encoding struct: " + err.Error())
}
urlQuery[p.ParameterName] = strVal
}
return nil
}
// Taking a URL Query (or any string->[]string struct) and shoving it into the struct
// as specified by qm.UnderlyingType
func (qm QueryMap) Decode(urlQuery map[string][]string, dst interface{}) error {
// First sanity check to ensure that the struct passed in matches
// the struct the QueryMap was designed to handle
if reflect.ValueOf(dst).Elem().Type() != reflect.TypeOf(qm.UnderlyingType) {
return fmt.Errorf("attempting to decode into mismatched struct: expected %s but got %s",
reflect.TypeOf(qm.UnderlyingType),
reflect.ValueOf(dst).Elem().Type(),
)
}
errs := &MultiValidationError{}
dstVal := reflect.ValueOf(dst).Elem()
for _, param := range qm.ParameterMaps {
field := dstVal.FieldByName(param.StructFieldName)
decodedParam, err := param.Mapper.Decode(urlQuery[param.ParameterName]...)
if err != nil {
errs.AddError(NewValidationError("error ocurred while reading value (%s) into param %s: %s",
urlQuery[param.ParameterName],
param.StructFieldName,
err.Error(),
))
continue
}
field.Set(reflect.ValueOf(decodedParam))
}
if len(errs.Errors()) == 0 {
return nil
}
return errs
}
// This ignores the case of parameter name in favor of the canonical format of
// http.Header
func (qm QueryMap) EncodeHeader(src interface{}, headers http.Header) error {
srcVal := reflect.ValueOf(src)
for _, p := range qm.ParameterMaps {
fieldVal := srcVal.FieldByName(p.StructFieldName)
if fieldVal.IsZero() && p.OmitEmpty {
continue
}
sliVal, err := p.Mapper.Encode(fieldVal)
if err != nil {
return errors.New("error in encoding struct: " + err.Error())
}
// Not using .Set() because it only allows strings and not slices
headers[http.CanonicalHeaderKey(p.ParameterName)] = sliVal
}
return nil
}
func (qm QueryMap) DecodeHeader(headers http.Header, dst interface{}) error {
if reflect.ValueOf(dst).Elem().Type() != reflect.TypeOf(qm.UnderlyingType) {
return errors.New("attempting to decode into the wrong struct")
}
// First sanity check to ensure that the struct passed in matches
// the struct the QueryMap was designed to handle
if reflect.ValueOf(dst).Elem().Type() != reflect.TypeOf(qm.UnderlyingType) {
return fmt.Errorf("attempting to decode into mismatched struct: expected %s but got %s",
reflect.TypeOf(qm.UnderlyingType),
reflect.ValueOf(dst).Elem().Type(),
)
}
errs := &MultiValidationError{}
dstVal := reflect.ValueOf(dst).Elem()
for _, param := range qm.ParameterMaps {
headerVal := headers[http.CanonicalHeaderKey(param.ParameterName)]
field := dstVal.FieldByName(param.StructFieldName)
decodedHeader, err := param.Mapper.Decode(headerVal...)
if err != nil {
errs.AddError(NewValidationError("error ocurred while reading value (%s) into param %s: %s",
headerVal,
param.StructFieldName,
err.Error(),
))
continue
}
field.Set(reflect.ValueOf(decodedHeader))
}
if len(errs.Errors()) == 0 {
return nil
}
return errs
}
// ParameterMap corresponds to each field in a specific struct,
// it requires struct's name and the corresponding key value in the URL query
type ParameterMap struct {
StructFieldName string
ParameterName string
Mapper QueryParameterMapper
OmitEmpty bool
}
// QueryParameterMapper defines how url.Values value ([]string) and struct are to be
// transformed into each other. It is from a slice of strings, reflecting the structure
// of url.Values. These can be specified by their type (whichever struct the Parameter
// mapper will be, and the restrictions defined on the type, defined by Validators slice
// below)
type QueryParameterMapper interface {
Encode(reflect.Value) ([]string, error)
Decode(...string) (interface{}, error)
}
// Examples of mappers
type StringQueryParameterMapper struct {
Validators []func(string) bool
}
func (sqpm StringQueryParameterMapper) Decode(src ...string) (interface{}, error) {
if len(src) > 1 {
return nil, NewValidationError("too many values")
}
if len(src) == 0 {
return "", nil
}
str := src[0]
for _, v := range sqpm.Validators {
if !v(str) {
return nil, NewValidationError("a validation test failed")
}
}
return str, nil
}
func (sqpm StringQueryParameterMapper) Encode(src reflect.Value) ([]string, error) {
if src.Kind() != reflect.String {
return nil, fmt.Errorf("expected string but got: %s", src.Kind())
}
return []string{src.String()}, nil
}
// Some useful validators
func StringRangeValidator(min, max int) func(string) bool {
return func(s string) bool {
return min <= len(s) && len(s) <= max
}
}
func StringRegexValidator(r *regexp.Regexp) func(string) bool {
return func(s string) bool {
return r.MatchString(s)
}
}
// Probably doesn't need Validators
type BoolQueryParameterMapper struct {
// Returns true on nil slices and empty strings
EmptyTrue bool
}
func (bqpm BoolQueryParameterMapper) Decode(src ...string) (interface{}, error) {
if len(src) > 1 {
return nil, NewValidationError("too many values")
}
if len(src) == 0 || src[0] == "" {
return bqpm.EmptyTrue, nil
}
b, err := strconv.ParseBool(src[0])
if err != nil {
return nil, fmt.Errorf("could not parse into bool: %s", err.Error())
}
return b, nil
}
func (bqpm BoolQueryParameterMapper) Encode(src reflect.Value) ([]string, error) {
if src.Kind() != reflect.Bool {
return nil, fmt.Errorf("expected boolean but got: %s", src.Kind())
}
return []string{strconv.FormatBool(src.Bool())}, nil
}
type IntQueryParameterMapper struct {
Validators []func(int64) bool
BitSize int
}
func (iqpm IntQueryParameterMapper) Decode(src ...string) (interface{}, error) {
if len(src) > 1 {
return nil, NewValidationError("too many values")
}
// This mildly weird flow is to ensure that 0 gets casted properly and avoids
// variable shadowing
num := int64(0)
var err error
if len(src) != 0 {
num, err = strconv.ParseInt(src[0], 10, iqpm.BitSize)
if err != nil {
return nil, NewValidationError("param could not be converted to integer: %s",
err.Error(),
)
}
for _, v := range iqpm.Validators {
if !v(num) {
return nil, NewValidationError("a validation test failed")
}
}
}
switch b := iqpm.BitSize; {
case b == 0:
return int(num), nil
case b <= 8:
return int8(num), nil
case b <= 16:
return int16(num), nil
case b <= 32:
return int32(num), nil
default:
return num, nil
}
}
func (iqpm IntQueryParameterMapper) Encode(src reflect.Value) ([]string, error) {
switch src.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return []string{strconv.FormatInt(src.Int(), 10)}, nil
default:
return nil, fmt.Errorf("expected int-type but got: %s", src.Kind())
}
}
type UintQueryParameterMapper struct {
Validators []func(uint64) bool
BitSize int
}
func (uqpm UintQueryParameterMapper) Decode(src ...string) (interface{}, error) {
if len(src) > 1 {
return nil, NewValidationError("too many values")
}
num := uint64(0)
var err error
if len(src) != 0 {
num, err = strconv.ParseUint(src[0], 10, uqpm.BitSize)
if err != nil {
return nil, NewValidationError("param could not be converted to integer: %s",
err.Error(),
)
}
for _, v := range uqpm.Validators {
if !v(num) {
return nil, NewValidationError("a validation test failed")
}
}
}
switch b := uqpm.BitSize; {
case b == 0:
return uint(num), nil
case b <= 8:
return uint8(num), nil
case b <= 16:
return uint16(num), nil
case b <= 32:
return uint32(num), nil
default:
return num, nil
}
}
func (uqpm UintQueryParameterMapper) Encode(src reflect.Value) ([]string, error) {
switch src.Kind() {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return []string{strconv.FormatUint(src.Uint(), 10)}, nil
default:
return nil, fmt.Errorf("expected uint-type but got: %s", src.Kind())
}
}
type TimeQueryParameterMapper struct {
Validators []func(time.Time) bool
}
func (tqpm TimeQueryParameterMapper) Decode(src ...string) (interface{}, error) {
if len(src) > 1 {
return nil, NewValidationError("too many values")
}
t := time.Time{}
if len(src) == 0 {
return t, nil
}
err := t.UnmarshalText([]byte(src[0]))
if err != nil {
return nil, NewValidationError("param could not be marshalled to time.Time: %s", err.Error())
}
for _, v := range tqpm.Validators {
if !v(t) {
return nil, NewValidationError("a validation test failed")
}
}
return t, nil
}
func (tqpm TimeQueryParameterMapper) Encode(src reflect.Value) ([]string, error) {
if src.Kind() != reflect.Struct {
return nil, fmt.Errorf("expected struct but got: %s", src.Kind())
}
if src.Type() != reflect.TypeOf(time.Time{}) {
return nil, fmt.Errorf("expected time.Time but got: %s", src.Type())
}
b, err := src.Interface().(time.Time).MarshalText()
if err != nil {
return nil, err
}
return []string{string(b)}, nil
}
type StrSliceQueryParameterMapper struct {
Validators []func([]string) bool
UnderlyingQueryParameterMapper QueryParameterMapper
}
func (sqpm StrSliceQueryParameterMapper) Decode(src ...string) (interface{}, error) {
for _, val := range sqpm.Validators {
if !val(src) {
return nil, NewValidationError("A validation test failed")
}
}
var retVal []string
for _, s := range src {
v, err := sqpm.UnderlyingQueryParameterMapper.Decode(s)
if err != nil {
return nil, NewValidationError("decoding a slice element failed: %s", err.Error())
}
retVal = append(retVal, v.(string))
}
return retVal, nil
}
func (sqpm StrSliceQueryParameterMapper) Encode(src reflect.Value) ([]string, error) {
if src.Kind() != reflect.Slice {
return nil, fmt.Errorf("expected slice but got: %s", src.Kind())
}
var retSlice []string
for i := 0; i < src.Len(); i++ {
s, err := sqpm.UnderlyingQueryParameterMapper.Encode(src.Index(i))
if err != nil {
return nil, errors.New("error in encoding slice internals: " + err.Error())
}
retSlice = append(retSlice, s[0])
}
return retSlice, nil
}
type StrPointerQueryParameterMapper struct {
UnderlyingQueryParameterMapper QueryParameterMapper
}
func (pqpm StrPointerQueryParameterMapper) Decode(src ...string) (interface{}, error) {
if len(src) > 1 {
return nil, NewValidationError("too many values")
}
v, err := pqpm.UnderlyingQueryParameterMapper.Decode(src...)
if err != nil {
return nil, NewValidationError("error occurred while decoding struct")
}
v2 := v.(string)
return &v2, nil
}
func (pqpm StrPointerQueryParameterMapper) Encode(src reflect.Value) ([]string, error) {
if src.Type() != reflect.PtrTo(reflect.TypeOf("")) {
return nil, fmt.Errorf("expected pointer but got: %s", src.Kind())
}
return []string{src.Elem().String()}, nil
}