forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decoder.go
52 lines (41 loc) · 1.13 KB
/
decoder.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
package util
import (
"reflect"
"github.com/go-playground/validator/v10"
"github.com/mitchellh/mapstructure"
)
var validate = validator.New()
// DecodeOther uses mapstructure to decode into target structure. Unused keys cause errors.
func DecodeOther(other, cc interface{}) error {
decoderConfig := &mapstructure.DecoderConfig{
Result: cc,
ErrorUnused: true,
WeaklyTypedInput: true,
DecodeHook: mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.TextUnmarshallerHookFunc(),
),
}
decoder, err := mapstructure.NewDecoder(decoderConfig)
if err != nil {
return err
}
if err := decoder.Decode(other); err != nil {
return &ConfigError{err}
}
// validate structs
if rv := reflect.ValueOf(cc); rv.Kind() == reflect.Struct || rv.Kind() == reflect.Pointer && rv.Elem().Kind() == reflect.Struct {
return validate.Struct(cc)
}
return nil
}
// ConfigError wraps yaml configuration errors from mapstructure
type ConfigError struct {
err error
}
func (e *ConfigError) Error() string {
return e.err.Error()
}
func (e *ConfigError) Unwrap() error {
return e.err
}