Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support expand config keys #1224

Merged
merged 2 commits into from
Jul 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 11 additions & 1 deletion config/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,17 @@ func WithLogger(l log.Logger) Option {
// to target map[string]interface{} using src.Format codec.
func defaultDecoder(src *KeyValue, target map[string]interface{}) error {
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
}
if codec := encoding.GetCodec(src.Format); codec != nil {
Expand Down
37 changes: 37 additions & 0 deletions config/options_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
3 changes: 3 additions & 0 deletions config/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,9 @@ func convertMap(src interface{}) interface{} {
dst[k] = convertMap(v)
}
return dst
case []byte:
// there will be no binary data in the config data
return string(m)
default:
return src
}
Expand Down