This repository was archived by the owner on Jan 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode.go
More file actions
67 lines (60 loc) · 1.57 KB
/
decode.go
File metadata and controls
67 lines (60 loc) · 1.57 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
package berus
import (
"github.com/mitchellh/mapstructure"
"reflect"
)
type Custom interface{}
var cSlice = make(map[string]Custom)
var empty Custom
// RegisterCustom. You must register a structure.
// After parsing, you can cast the field to this structure.
func RegisterCustom(name string, c Custom) {
cSlice[name] = c
}
// CustomHookFunc decode hook for github.com/mitchellh/mapstructure
func CustomHookFunc(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if f.Kind() != reflect.Map || t.Kind() != reflect.Interface {
return data, nil
}
if of := reflect.TypeOf(&empty); of.Elem() == nil || !of.Elem().Implements(t) {
return data, nil
}
val, ok := data.(map[string]interface{})
if !ok {
return nil, newError("Unsupported data")
}
typ, ok := val["_type"]
if !ok {
return nil, newError("Custom doesn't have '_type'")
}
tt, ok := typ.(string)
if !ok {
return nil, newError("Unsupported field '_type'")
}
c, ok := cSlice[tt]
if !ok {
return nil, newError("Unregistered custom type")
}
delete(val, "_type")
value := reflect.New(reflect.TypeOf(c).Elem()).Interface()
return value, decode(val, value)
}
func decode(input interface{}, output interface{}) error {
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Metadata: nil,
Result: output,
WeaklyTypedInput: true,
DecodeHook: mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
CustomHookFunc,
),
})
if err != nil {
return err
}
return decoder.Decode(input)
}