forked from gocraft/meta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
meta.go
476 lines (407 loc) · 13.7 KB
/
meta.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
470
471
472
473
474
475
476
package meta
import (
"fmt"
"io"
"io/ioutil"
"net/url"
"reflect"
"strconv"
)
type Valuer interface {
ParseOptions(tag reflect.StructTag) interface{}
JSONValue(path string, value interface{}, options interface{}) Errorable
}
var (
reflectTypeValuer = reflect.TypeOf((*Valuer)(nil)).Elem()
)
type Optionaler interface {
Optional() bool
}
type decoderFieldCategory int
const (
categoryValuer decoderFieldCategory = iota
categoryStruct
categorySliceOfValues
categorySliceOfStructs
categoryAllFieldsMap
)
var nullString = []byte("null")
type SliceOptions struct {
MinLengthPresent bool
MinLength int
MaxLengthPresent bool
MaxLength int
}
func ParseSliceOptions(tag reflect.StructTag) *SliceOptions {
sliceOpts := &SliceOptions{}
if minLengthString := tag.Get("meta_min_length"); minLengthString != "" {
minLength, err := strconv.ParseInt(minLengthString, 10, 0)
if err != nil {
panic(err.Error())
}
sliceOpts.MinLengthPresent = true
sliceOpts.MinLength = int(minLength)
}
if maxLengthString := tag.Get("meta_max_length"); maxLengthString != "" {
maxLength, err := strconv.ParseInt(maxLengthString, 10, 0)
if err != nil {
panic(err.Error())
}
sliceOpts.MaxLengthPresent = true
sliceOpts.MaxLength = int(maxLength)
}
return sliceOpts
}
type DecoderField struct {
Name string // key in the input
Required bool
DiscardInvalid bool
Options interface{}
needsAllocation bool // true if we need to reflect.New
Default string
Doc string
DocPattern string
*SliceOptions
// The type of field it is:
fieldCategory decoderFieldCategory
StructDecoder *Decoder // If the field is a nested struct or a slice of nested structs, this is set to the decoder.
fieldIndex []int // Given the struct Value, how can we get the field with .FieldByIndex(fieldIndex)
// Basic type information:
fieldType reflect.Type // Type of the field. Eg, TypeOf(field)
fieldKind reflect.Kind
indirectedType reflect.Type
indirectedKind reflect.Kind
// ElemXxx: Applies to Slices.
// elemType is the TypeOf each slice element. If that's a pointer, then Indirected
// It can be the case that elemType == elemIndirectedType.
elemType reflect.Type
elemKind reflect.Kind
elemIndirectedType reflect.Type
elemIndirectedKind reflect.Kind
}
type Decoder struct {
StructType reflect.Type
Fields []DecoderField
Options DecoderOptions
}
type DecoderOptions struct {
TimeFormats []string
}
func NewDecoderWithOptions(destStruct interface{}, options DecoderOptions) *Decoder {
destValue := reflect.ValueOf(destStruct)
indirectedDest := reflect.Indirect(destValue)
destType := indirectedDest.Type()
if destValue.Kind() == reflect.Ptr && indirectedDest.Kind() == reflect.Struct {
// we're good
} else if destValue.Kind() == reflect.Struct {
destType = destValue.Type()
destValue = reflect.New(destType)
indirectedDest = reflect.Indirect(destValue)
} else {
panic(fmt.Sprintf("expect ptr to struct or struct, got %s", destValue.Kind()))
}
decoder := &Decoder{StructType: destType}
fieldCount := indirectedDest.NumField()
for i := 0; i < fieldCount; i += 1 {
field := indirectedDest.Field(i)
fieldStruct := destType.Field(i) // type: StructField
fieldType := field.Type()
fieldKind := fieldType.Kind()
var indirectedType reflect.Type
var indirectedKind reflect.Kind
if fieldKind == reflect.Ptr {
indirectedType = fieldType.Elem()
indirectedKind = indirectedType.Kind()
} else {
indirectedType = fieldType
indirectedKind = fieldKind
}
var fieldInterface interface{} // This is going to be a pointer to a struct
var needsAllocation bool
if fieldKind == reflect.Struct {
fieldInterface = field.Addr().Interface()
} else if fieldKind == reflect.Ptr && indirectedKind == reflect.Struct {
fieldInterface = reflect.New(indirectedType).Interface()
needsAllocation = true
}
// Determine the key we're expecting in input
metaName := fieldStruct.Tag.Get("meta")
if metaName == "-" {
continue
} else if metaName == "" {
metaName = NameMapping(fieldStruct.Name)
}
// Determine if it's required..
required := fieldStruct.Tag.Get("meta_required") == "true"
if fieldStruct.Anonymous && indirectedKind == reflect.Struct {
// It's an embedded struct:
embeddedDecoder := NewDecoderWithOptions(fieldInterface, options)
for _, embeddedDField := range embeddedDecoder.Fields {
idx := []int{i}
idx = append(idx, embeddedDField.fieldIndex...)
embeddedDField.fieldIndex = idx
decoder.Fields = append(decoder.Fields, embeddedDField)
}
} else {
dfield := DecoderField{
Name: metaName,
Required: required,
needsAllocation: needsAllocation,
fieldIndex: []int{i},
fieldType: fieldType,
fieldKind: fieldKind,
indirectedType: indirectedType,
indirectedKind: indirectedKind,
}
dfield.Doc = fieldStruct.Tag.Get("doc")
dfield.DocPattern = fieldStruct.Tag.Get("doc_pattern")
// Determine what kind of field it is.
if metaName == "*" && indirectedKind == reflect.Map {
dfield.fieldCategory = categoryAllFieldsMap
} else if valuer, ok := fieldInterface.(Valuer); ok {
dfield.fieldCategory = categoryValuer
dfield.Options = getParsedOptions(valuer, fieldStruct, options)
if def := fieldStruct.Tag.Get("meta_default"); def != "" {
dfield.Default = def
}
dfield.DiscardInvalid = fieldStruct.Tag.Get("meta_discard_invalid") == "true"
} else if indirectedKind == reflect.Struct {
dfield.fieldCategory = categoryStruct
dfield.StructDecoder = NewDecoderWithOptions(fieldInterface, options)
} else if indirectedKind == reflect.Slice {
var elemType, elemIndirectedType reflect.Type
var elemKind, elemIndirectedKind reflect.Kind
elemType = fieldType.Elem()
elemKind = elemType.Kind()
if elemKind == reflect.Ptr {
elemIndirectedType = elemType.Elem()
elemIndirectedKind = elemIndirectedType.Kind()
} else {
elemIndirectedType = elemType
elemIndirectedKind = elemKind
}
dfield.elemType = elemType
dfield.elemKind = elemKind
dfield.elemIndirectedType = elemIndirectedType
dfield.elemIndirectedKind = elemIndirectedKind
// Set slice validation options
dfield.SliceOptions = ParseSliceOptions(fieldStruct.Tag)
if reflect.PtrTo(elemIndirectedType).Implements(reflectTypeValuer) {
dfield.fieldCategory = categorySliceOfValues
valuer := reflect.New(elemIndirectedType).Interface().(Valuer) // Make a new object so we can use it to parse values.
dfield.Options = getParsedOptions(valuer, fieldStruct, options)
} else if elemIndirectedKind == reflect.Struct {
dfield.fieldCategory = categorySliceOfStructs
if elemIndirectedType == destType {
dfield.StructDecoder = decoder
} else {
dfield.StructDecoder = NewDecoderWithOptions(reflect.New(elemIndirectedType).Interface(), options)
}
} else {
panic("unknown type of slice")
}
}
decoder.Fields = append(decoder.Fields, dfield)
}
}
return decoder
}
func getParsedOptions(valuer Valuer, fieldStruct reflect.StructField, options DecoderOptions) interface{} {
parsedOptions := valuer.ParseOptions(fieldStruct.Tag)
if timeOptions, ok := parsedOptions.(*TimeOptions); ok && len(options.TimeFormats) > 0 {
timeOptions.Format = options.TimeFormats
parsedOptions = timeOptions
}
return parsedOptions
}
func NewDecoder(destStruct interface{}) *Decoder {
return NewDecoderWithOptions(destStruct, DecoderOptions{})
}
func (d *Decoder) Decode(dest interface{}, values url.Values, b []byte) ErrorHash {
return d.decode(reflect.ValueOf(dest), newMergedSource(newJSONSource(b), newFormValueSource(values)))
}
func (d *Decoder) DecodeJSON(dest interface{}, b []byte) ErrorHash {
return d.Decode(dest, nil, b)
}
func (d *Decoder) DecodeValues(dest interface{}, values url.Values) ErrorHash {
return d.Decode(dest, values, nil)
}
func (d *Decoder) DecodeMap(dest interface{}, m map[string]interface{}) ErrorHash {
return d.decode(reflect.ValueOf(dest), newMapSource(m))
}
func (d *Decoder) decode(destValue reflect.Value, src source) ErrorHash {
var errs ErrorHash
indirectedDest := reflect.Indirect(destValue) // This should be the value of the struct
if destValue.Kind() != reflect.Ptr {
panic(fmt.Sprintf("expect ptr, got %s", destValue.Kind()))
}
if indirectedDest.Type() != d.StructType {
panic(fmt.Sprintf("expect type %s, got %s", d.StructType, indirectedDest.Type()))
}
for _, dfield := range d.Fields {
fieldValue := indirectedDest.FieldByIndex(dfield.fieldIndex)
metaName := dfield.Name
switch dfield.fieldCategory {
case categoryValuer:
nestedValues := src.Get(metaName)
if nestedValues.Malformed() {
return ErrorHash{
"error": ErrMalformed,
}
}
ok := !nestedValues.Empty()
var val interface{}
if ok {
nestedValues.Value(&val)
} else if dfield.Default != "" {
val = dfield.Default
ok = true
}
if ok {
valuerValue := fieldValue.Addr()
var err Errorable
if dfield.needsAllocation {
fieldValue.Set(reflect.New(dfield.indirectedType))
valuerValue = fieldValue
}
err = valuerValue.Interface().(Valuer).JSONValue(nestedValues.Path(), val, dfield.Options)
if err != nil && !dfield.DiscardInvalid {
errs = addError(errs, metaName, err)
}
} else if dfield.Required {
errs = addError(errs, metaName, ErrRequired)
}
case categoryStruct:
// Construct nestedValues
// if the struct name is like FooBar,
// {foo_bar.x=1, foo_bar.y=2} -> {x=1, y=2}
nestedValues := src.Get(metaName)
if nestedValues.Malformed() {
return ErrorHash{
"error": ErrMalformed,
}
}
if !nestedValues.Empty() {
var err ErrorHash
if dfield.needsAllocation {
fieldValue.Set(reflect.New(dfield.indirectedType))
err = dfield.StructDecoder.decode(fieldValue, nestedValues)
} else {
err = dfield.StructDecoder.decode(fieldValue.Addr(), nestedValues)
}
if err != nil {
errs = addError(errs, metaName, err)
}
} else if dfield.Required {
errs = addError(errs, metaName, ErrRequired)
}
case categorySliceOfValues:
sliceValue := fieldValue
var errorsInSlice ErrorSlice
sliceSrc := src.Get(metaName)
for i := 0; true; i += 1 {
nestedValues := sliceSrc.Get(fmt.Sprint(i)) // foo_bar.0, foo_bar.1, ...
if nestedValues.Malformed() {
return ErrorHash{
"error": ErrMalformed,
}
}
if nestedValues.Empty() {
break
}
var val interface{}
nestedValues.Value(&val)
elPtrValue := reflect.New(dfield.elemIndirectedType)
err := elPtrValue.Interface().(Valuer).JSONValue(nestedValues.Path(), val, dfield.Options)
if err != nil {
errorsInSlice = append(errorsInSlice, err)
} else {
errorsInSlice = append(errorsInSlice, nil)
if dfield.elemKind == reflect.Ptr {
sliceValue = reflect.Append(sliceValue, elPtrValue)
} else {
sliceValue = reflect.Append(sliceValue, reflect.Indirect(elPtrValue))
}
}
}
fieldValue.Set(sliceValue)
if errorsInSlice.Len() > 0 {
errs = addError(errs, metaName, errorsInSlice)
}
case categorySliceOfStructs:
sliceValue := fieldValue
var errorsInSlice ErrorSlice
var i int
sliceSrc := src.Get(metaName)
for ; true; i += 1 {
nestedValues := sliceSrc.Get(fmt.Sprint(i)) // foo_bar.0, foo_bar.1, ...
if nestedValues.Malformed() {
return ErrorHash{
"error": ErrMalformed,
}
}
if nestedValues.Empty() {
break
}
elPtrValue := reflect.New(dfield.elemIndirectedType)
if err := dfield.StructDecoder.decode(elPtrValue, nestedValues); err != nil {
errorsInSlice = append(errorsInSlice, err)
} else {
errorsInSlice = append(errorsInSlice, nil)
if dfield.elemKind == reflect.Ptr {
sliceValue = reflect.Append(sliceValue, elPtrValue)
} else {
sliceValue = reflect.Append(sliceValue, reflect.Indirect(elPtrValue))
}
}
}
// Validate the length of the slice
if dfield.MinLengthPresent && dfield.MinLength > i {
errs = addError(errs, metaName, ErrMinLength)
} else if dfield.MaxLengthPresent && dfield.MaxLength < i {
errs = addError(errs, metaName, ErrMaxLength)
} else {
fieldValue.Set(sliceValue)
if errorsInSlice.Len() > 0 {
errs = addError(errs, metaName, errorsInSlice)
}
}
case categoryAllFieldsMap:
fieldValue.Set(reflect.ValueOf(src.ValueMap()))
}
}
return errs
}
// Given the decoder, makes a new struct and tries to map the values onto it. If it succeeds, returns that struct. Otherwise, returns the errors.
func (d *Decoder) NewDecodedValues(values url.Values) (interface{}, ErrorHash) {
return d.NewDecoded(values, nil)
}
// NewDecoded empties io.Reader and uses its []byte to create json source.
//
// It is often common to call req.ParseForm() before calling this function to obtain url.Values from http request.
// Although ParseForm also reads http request body, it will only do so if the content type is either
// "application/x-www-form-urlencoded" or "multipart/form-data". Therefore, in this case, this function can
// handle both json and form-encoded input.
func (d *Decoder) NewDecoded(values url.Values, r io.Reader) (interface{}, ErrorHash) {
var b []byte
if r != nil {
var err error
b, err = ioutil.ReadAll(r)
if err != nil {
// error hash is used to make it compatible with DecodeValues.
return nil, NewHash("error", err.Error())
}
}
dest := reflect.New(d.StructType).Interface()
if err := d.Decode(dest, values, b); err != nil {
return nil, err
}
return dest, nil
}
func addError(errs ErrorHash, key string, value Errorable) ErrorHash {
if errs == nil {
errs = make(ErrorHash)
}
errs[key] = value
return errs
}