-
Notifications
You must be signed in to change notification settings - Fork 12
/
params.go
469 lines (338 loc) · 12 KB
/
params.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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package types
import (
"errors"
"fmt"
rt "github.com/graniticio/granitic/v2/reflecttools"
"net/url"
"reflect"
"strconv"
"strings"
)
// NewSingleValueParams creates a Params with only one value in it
func NewSingleValueParams(name string, value string) *Params {
contents := make(url.Values)
contents[name] = []string{value}
names := []string{name}
return &Params{paramNames: names, values: contents}
}
// NewParams creates a Params with the supplied contents
func NewParams(v url.Values, pn []string) *Params {
p := new(Params)
p.values = v
p.paramNames = pn
return p
}
// Params is an abstraction of the HTTP query parameters or path parameters with type-safe accessors.
type Params struct {
values url.Values
paramNames []string
}
// ParamNames returns the names of all of the parameters stored
func (wp *Params) ParamNames() []string {
return wp.paramNames
}
// NotEmpty returns true if a parameter with the supplied name exists and has a non-empty string representation.
func (wp *Params) NotEmpty(key string) bool {
if !wp.Exists(key) {
return false
}
s, _ := wp.StringValue(key)
return s != ""
}
// Exists returns true if a parameter with the supplied name exists, even if that parameter's value is an empty string.
func (wp *Params) Exists(key string) bool {
return wp.values[key] != nil
}
// MultipleValues returns true if the parameter with the supplied name was set more than once (allowed for HTTP query parameters).
func (wp *Params) MultipleValues(key string) bool {
value := wp.values[key]
return value != nil && len(value) > 1
}
// StringValue returns the string representation of the specified parameter or an error if no value exists for that parameter.
func (wp *Params) StringValue(key string) (string, error) {
s := wp.values[key]
if s == nil {
return "", wp.noVal(key)
}
return s[len(s)-1], nil
}
// BoolValue returns the bool representation of the specified parameter (using Go's bool conversion rules) or an error if no value exists for that parameter.
func (wp *Params) BoolValue(key string) (bool, error) {
v := wp.values[key]
if v == nil {
return false, wp.noVal(key)
}
b, err := strconv.ParseBool(v[len(v)-1])
return b, err
}
// FloatNValue returns a float representation of the specified parameter with the specified bit size, or an error if no value exists for that parameter or
// if the value could not be converted to a float.
func (wp *Params) FloatNValue(key string, bits int) (float64, error) {
v := wp.values[key]
if v == nil {
return 0.0, wp.noVal(key)
}
i, err := strconv.ParseFloat(v[len(v)-1], bits)
return i, err
}
// IntNValue returns a signed int representation of the specified parameter with the specified bit size, or an error if no value exists for that parameter or
// if the value could not be converted to an int.
func (wp *Params) IntNValue(key string, bits int) (int64, error) {
v := wp.values[key]
if v == nil {
return 0, wp.noVal(key)
}
i, err := strconv.ParseInt(v[len(v)-1], 10, bits)
return i, err
}
// IntNInterfaceValue returns a signed int representation of the specified parameter as the correct basic type (int8, int32 etc), or an error if no value exists for that parameter or
// if the value could not be converted to an int.
func (wp *Params) IntNInterfaceValue(i64 int64, bits int) interface{} {
switch bits {
case 8:
return int8(i64)
case 16:
return int16(i64)
case 32:
return int32(i64)
}
return i64
}
// UIntNInterfaceValue returns an unsigned int representation of the specified parameter as the correct basic type (uint8, uint32 etc), or an error if no value exists for that parameter or
// if the value could not be converted to an int.
func (wp *Params) UIntNInterfaceValue(u64 uint64, bits int) interface{} {
switch bits {
case 8:
return uint8(u64)
case 16:
return uint16(u64)
case 32:
return uint32(u64)
}
return u64
}
// UIntNValue returns an unsigned int representation of the specified parameter with the specified bit size, or an error if no value exists for that parameter or
// if the value could not be converted to an unsigned int.
func (wp *Params) UIntNValue(key string, bits int) (uint64, error) {
v := wp.values[key]
if v == nil {
return 0, wp.noVal(key)
}
i, err := strconv.ParseUint(v[len(v)-1], 10, bits)
return i, err
}
func (wp *Params) noVal(key string) error {
message := fmt.Sprintf("No value available for key %s", key)
return errors.New(message)
}
// GenerateMappingError is used to create an error in the context of mapping a parameter into a struct field
type GenerateMappingError func(paramName string, fieldName string, typeName string, params *Params) error
// FieldAssociatedError is implemented by types that can record which field on a struct caused a problem
type FieldAssociatedError interface {
// RecordField captures the field that was involved in the error
RecordField(string)
}
// ParamValueInjector takes a series of key/value (string/string) parameters and tries to inject them into the fields
// on a target struct
type ParamValueInjector struct {
}
// BindValueToField attempts to take a named parameter from the supplied set of parameters and inject it into a field on the supplied target,
// converting to the correct data type as it goes.
func (pb *ParamValueInjector) BindValueToField(paramName string, fieldName string, p *Params, t interface{}, errorFn GenerateMappingError, index ...int) error {
ft := rt.TypeOfField(t, fieldName)
k := ft.Kind()
if k == reflect.Slice && index != nil {
//We're setting a value in a slice
k = ft.Elem().Kind()
}
switch k {
case reflect.Int:
return pb.setIntNField(paramName, fieldName, p, t, 0, errorFn, index...)
case reflect.Int8:
return pb.setIntNField(paramName, fieldName, p, t, 8, errorFn, index...)
case reflect.Int16:
return pb.setIntNField(paramName, fieldName, p, t, 16, errorFn, index...)
case reflect.Int32:
return pb.setIntNField(paramName, fieldName, p, t, 32, errorFn, index...)
case reflect.Int64:
return pb.setIntNField(paramName, fieldName, p, t, 64, errorFn, index...)
case reflect.Bool:
return pb.setBoolField(paramName, fieldName, p, t, errorFn, index...)
case reflect.String:
return pb.setStringField(paramName, fieldName, p, t, errorFn, index...)
case reflect.Uint8:
return pb.setUintNField(paramName, fieldName, p, t, 8, errorFn, index...)
case reflect.Uint16:
return pb.setUintNField(paramName, fieldName, p, t, 16, errorFn, index...)
case reflect.Uint32:
return pb.setUintNField(paramName, fieldName, p, t, 32, errorFn, index...)
case reflect.Uint64:
return pb.setUintNField(paramName, fieldName, p, t, 64, errorFn, index...)
case reflect.Float32:
return pb.setFloatNField(paramName, fieldName, p, t, 32, errorFn, index...)
case reflect.Float64:
return pb.setFloatNField(paramName, fieldName, p, t, 64, errorFn, index...)
case reflect.Ptr:
return pb.considerStructField(paramName, fieldName, p, t, errorFn, index...)
case reflect.Slice:
return pb.populateSlice(paramName, fieldName, p, t, errorFn)
}
if index != nil {
return fmt.Errorf("field %s[%d] is not a valid type for binding into - make sure it is a basic type or a POINTER to a nilable", fieldName, index[0])
}
return fmt.Errorf("field %s is not a valid type for binding into - make sure it is a basic type or a POINTER to a nilable", fieldName)
}
func (pb *ParamValueInjector) populateSlice(paramName string, fieldName string, qp *Params, t interface{}, errorFn GenerateMappingError) error {
tf := reflect.ValueOf(t).Elem().FieldByName(fieldName)
paramValue, err := qp.StringValue(paramName)
paramValue = strings.TrimSpace(paramValue)
if err != nil {
return err
}
values := strings.Split(paramValue, ",")
vlen := len(values)
if vlen == 1 && len(paramValue) == 0 {
vlen = 0
}
refSlice := reflect.MakeSlice(tf.Type(), vlen, vlen)
tf.Set(refSlice)
if vlen == 0 {
return nil
}
for i, v := range values {
p := NewSingleValueParams(paramName, strings.TrimSpace(v))
if err := pb.BindValueToField(paramName, fieldName, p, t, errorFn, i); err != nil {
return err
}
}
return nil
}
func (pb *ParamValueInjector) considerStructField(paramName string, fieldName string, qp *Params, t interface{}, errorFn GenerateMappingError, index ...int) error {
var tv interface{}
tf := reflect.ValueOf(t).Elem().FieldByName(fieldName)
if index != nil {
t := tf.Index(0)
to := reflect.TypeOf(t.Interface())
if !(rt.IsPointer(to)) {
return fmt.Errorf("Can only bind into arrays of pointers to structs, not arrays of structs")
}
underType := to.Elem()
tv = reflect.New(underType).Interface()
} else {
tv = tf.Interface()
}
_, found := tv.(Nilable)
if found {
return pb.setNilableField(paramName, fieldName, qp, tf, tv, errorFn, t, index...)
}
return nil
}
func (pb *ParamValueInjector) setNilableField(paramName string, fieldName string, p *Params, tf reflect.Value, tv interface{}, errorFn GenerateMappingError, parent interface{}, index ...int) error {
np := new(nillableProxy)
var e error
var nv interface{}
switch tv.(type) {
case *NilableString:
e = pb.setStringField(paramName, "S", p, np, errorFn)
nv = NewNilableString(np.S)
case *NilableBool:
if p.NotEmpty(paramName) {
e = pb.setBoolField(paramName, "B", p, np, errorFn)
nv = NewNilableBool(np.B)
}
case *NilableInt64:
if p.NotEmpty(paramName) {
e = pb.setIntNField(paramName, "I", p, np, 64, errorFn)
nv = NewNilableInt64(np.I)
}
case *NilableFloat64:
if p.NotEmpty(paramName) {
e = pb.setFloatNField(paramName, "F", p, np, 64, errorFn)
nv = NewNilableFloat64(np.F)
}
}
if e == nil {
if index == nil {
rt.SetPtrToStruct(parent, fieldName, nv)
} else {
rt.SetSliceElem(parent, fieldName, nv, index[0])
}
} else {
if fe, okay := e.(FieldAssociatedError); okay {
fe.RecordField(fieldName)
}
}
return e
}
func (pb *ParamValueInjector) setStringField(paramName string, fieldName string, qp *Params, t interface{}, errorFn GenerateMappingError, index ...int) error {
s, err := qp.StringValue(paramName)
if err != nil {
return errorFn(paramName, fieldName, "string", qp)
}
if index != nil {
rt.SetSliceElem(t, fieldName, s, index[0])
} else {
rt.SetString(t, fieldName, s)
}
return nil
}
func (pb *ParamValueInjector) setBoolField(paramName string, fieldName string, qp *Params, t interface{}, errorFn GenerateMappingError, index ...int) error {
b, err := qp.BoolValue(paramName)
if err != nil {
return errorFn(paramName, fieldName, "bool", qp)
}
if index != nil {
rt.SetSliceElem(t, fieldName, b, index[0])
} else {
rt.SetBool(t, fieldName, b)
}
return nil
}
func (pb *ParamValueInjector) setIntNField(paramName string, fieldName string, qp *Params, t interface{}, bits int, errorFn GenerateMappingError, index ...int) error {
i, err := qp.IntNValue(paramName, bits)
if err != nil {
return errorFn(paramName, fieldName, pb.intTypeName("int", bits), qp)
}
if index != nil {
rt.SetSliceElem(t, fieldName, qp.IntNInterfaceValue(i, bits), index[0])
} else {
rt.SetInt64(t, fieldName, i)
}
return nil
}
func (pb *ParamValueInjector) setFloatNField(paramName string, fieldName string, qp *Params, t interface{}, bits int, errorFn GenerateMappingError, index ...int) error {
f, err := qp.FloatNValue(paramName, bits)
if err != nil {
return errorFn(paramName, fieldName, pb.intTypeName("float", bits), qp)
}
if index != nil {
rt.SetSliceElem(t, fieldName, f, index[0])
} else {
rt.SetFloat64(t, fieldName, f)
}
return nil
}
func (pb *ParamValueInjector) setUintNField(paramName string, fieldName string, qp *Params, t interface{}, bits int, errorFn GenerateMappingError, index ...int) error {
i, err := qp.UIntNValue(paramName, bits)
if err != nil {
return errorFn(paramName, fieldName, pb.intTypeName("uint", bits), qp)
}
if index != nil {
rt.SetSliceElem(t, fieldName, qp.UIntNInterfaceValue(i, bits), index[0])
} else {
rt.SetUint64(t, fieldName, i)
}
return nil
}
func (pb *ParamValueInjector) intTypeName(prefix string, bits int) string {
if bits == 0 {
return prefix
}
return prefix + strconv.Itoa(bits)
}
type nillableProxy struct {
S string
B bool
I int64
F float64
}