@@ -9,25 +9,56 @@ import (
9
9
"reflect"
10
10
)
11
11
12
+ // Mappable represents an interface that can MapTo another interface
13
+ type Mappable interface {
14
+ MapTo (v interface {}) error
15
+ }
16
+
12
17
// toConfig will attempt to convert a given configuration cfg into the provided exemplar type.
13
18
//
14
19
// It will tolerate the cfg being passed as a []byte or string of a json representation of the
15
20
// exemplar or the correct type of the exemplar itself
16
21
func toConfig (exemplar , cfg interface {}) (interface {}, error ) {
22
+
23
+ // First of all check if we've got the same type as the exemplar - if so it's all fine.
17
24
if reflect .TypeOf (cfg ).AssignableTo (reflect .TypeOf (exemplar )) {
18
25
return cfg , nil
19
26
}
20
27
28
+ // Now if not - does it provide a MapTo function we can try?
29
+ if mappable , ok := cfg .(Mappable ); ok {
30
+ newVal := reflect .New (reflect .TypeOf (exemplar ))
31
+ if err := mappable .MapTo (newVal .Interface ()); err == nil {
32
+ return newVal .Elem ().Interface (), nil
33
+ }
34
+ // MapTo has failed us ... let's try the json route ...
35
+ }
36
+
37
+ // OK we've been passed a byte array right?
21
38
configBytes , ok := cfg .([]byte )
22
39
if ! ok {
23
- configStr , ok := cfg .( string )
24
- if ! ok {
25
- return nil , ErrInvalidConfiguration { cfg : cfg }
26
- }
40
+ // oh ... it's a string then?
41
+ var configStr string
42
+
43
+ configStr , ok = cfg .( string )
27
44
configBytes = []byte (configStr )
28
45
}
46
+ if ! ok {
47
+ // hmm ... can we marshal it to json?
48
+ var err error
49
+
50
+ configBytes , err = json .Marshal (cfg )
51
+ ok = (err == nil )
52
+ }
53
+ if ! ok {
54
+ // no ... we've tried hard enough at this point - throw an error!
55
+ return nil , ErrInvalidConfiguration {cfg : cfg }
56
+ }
57
+
58
+ // OK unmarshal the byte array into a new copy of the exemplar
29
59
newVal := reflect .New (reflect .TypeOf (exemplar ))
30
60
if err := json .Unmarshal (configBytes , newVal .Interface ()); err != nil {
61
+ // If we can't unmarshal it then return an error!
31
62
return nil , ErrInvalidConfiguration {cfg : cfg , err : err }
32
63
}
33
64
return newVal .Elem ().Interface (), nil
0 commit comments