@@ -9,25 +9,56 @@ import (
99 "reflect"
1010)
1111
12+ // Mappable represents an interface that can MapTo another interface
13+ type Mappable interface {
14+ MapTo (v interface {}) error
15+ }
16+
1217// toConfig will attempt to convert a given configuration cfg into the provided exemplar type.
1318//
1419// It will tolerate the cfg being passed as a []byte or string of a json representation of the
1520// exemplar or the correct type of the exemplar itself
1621func 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.
1724 if reflect .TypeOf (cfg ).AssignableTo (reflect .TypeOf (exemplar )) {
1825 return cfg , nil
1926 }
2027
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?
2138 configBytes , ok := cfg .([]byte )
2239 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 )
2744 configBytes = []byte (configStr )
2845 }
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
2959 newVal := reflect .New (reflect .TypeOf (exemplar ))
3060 if err := json .Unmarshal (configBytes , newVal .Interface ()); err != nil {
61+ // If we can't unmarshal it then return an error!
3162 return nil , ErrInvalidConfiguration {cfg : cfg , err : err }
3263 }
3364 return newVal .Elem ().Interface (), nil
0 commit comments