support expand config keys (#1224)

* support expand config keys

* fix bytes in convertMap
pull/1229/head
longxboy 3 years ago committed by GitHub
parent 1a0a1b8a89
commit e1228d454a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 12
      config/options.go
  2. 37
      config/options_test.go
  3. 3
      config/reader.go

@ -61,7 +61,17 @@ func WithLogger(l log.Logger) Option {
// to target map[string]interface{} using src.Format codec. // to target map[string]interface{} using src.Format codec.
func defaultDecoder(src *KeyValue, target map[string]interface{}) error { func defaultDecoder(src *KeyValue, target map[string]interface{}) error {
if src.Format == "" { if src.Format == "" {
target[src.Key] = src.Value // expand key "aaa.bbb" into map[aaa]map[bbb]interface{}
keys := strings.Split(src.Key, ".")
for i, k := range keys {
if i == len(keys)-1 {
target[k] = src.Value
} else {
sub := make(map[string]interface{})
target[k] = sub
target = sub
}
}
return nil return nil
} }
if codec := encoding.GetCodec(src.Format); codec != nil { if codec := encoding.GetCodec(src.Format); codec != nil {

@ -0,0 +1,37 @@
package config
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestDefaultDecoder(t *testing.T) {
src := &KeyValue{
Key: "service",
Value: []byte("config"),
Format: "",
}
target := make(map[string]interface{}, 0)
err := defaultDecoder(src, target)
assert.Nil(t, err)
assert.Equal(t, map[string]interface{}{
"service": []byte("config"),
}, target)
src = &KeyValue{
Key: "service.name.alias",
Value: []byte("2233"),
Format: "",
}
target = make(map[string]interface{}, 0)
err = defaultDecoder(src, target)
assert.Nil(t, err)
assert.Equal(t, map[string]interface{}{
"service": map[string]interface{}{
"name": map[string]interface{}{
"alias": []byte("2233"),
},
},
}, target)
}

@ -101,6 +101,9 @@ func convertMap(src interface{}) interface{} {
dst[k] = convertMap(v) dst[k] = convertMap(v)
} }
return dst return dst
case []byte:
// there will be no binary data in the config data
return string(m)
default: default:
return src return src
} }

Loading…
Cancel
Save