chore(config/env): minor refactor (#1232)

* chore(config/env): minor refactor
pull/1235/head
徐胖 3 years ago committed by GitHub
parent 97222012e4
commit 77d2cfb653
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 9
      config/env/env.go
  2. 64
      config/env/env_test.go

9
config/env/env.go vendored

@ -16,7 +16,12 @@ func NewSource(prefixs ...string) config.Source {
}
func (e *env) Load() (kv []*config.KeyValue, err error) {
for _, envstr := range os.Environ() {
return e.load(os.Environ()), nil
}
func (e *env) load(envStrings []string) []*config.KeyValue {
var kv []*config.KeyValue
for _, envstr := range envStrings {
var k, v string
subs := strings.SplitN(envstr, "=", 2)
k = subs[0]
@ -41,7 +46,7 @@ func (e *env) Load() (kv []*config.KeyValue, err error) {
Value: []byte(v),
})
}
return
return kv
}
func (e *env) Watch() (config.Watcher, error) {

@ -245,3 +245,67 @@ func TestEnvWithoutPrefix(t *testing.T) {
})
}
}
func Test_env_load(t *testing.T) {
type fields struct {
prefixs []string
}
type args struct {
envStrings []string
}
tests := []struct {
name string
fields fields
args args
want []*config.KeyValue
}{
{
name: "without prefixes",
fields: fields{
prefixs: nil,
},
args: args{
envStrings: []string{
"SERVICE_NAME=kratos_app",
"ADDR=192.168.0.1",
"AGE=20",
},
},
want: []*config.KeyValue{
{Key: "SERVICE_NAME", Value: []byte("kratos_app"), Format: ""},
{Key: "ADDR", Value: []byte("192.168.0.1"), Format: ""},
{Key: "AGE", Value: []byte("20"), Format: ""},
},
},
{
name: "with prefixes",
fields: fields{
prefixs: []string{"KRATOS_", "FOO"},
},
args: args{
envStrings: []string{
"KRATOS_SERVICE_NAME=kratos_app",
"KRATOS_ADDR=192.168.0.1",
"FOO_AGE=20",
},
},
want: []*config.KeyValue{
{Key: "SERVICE_NAME", Value: []byte("kratos_app"), Format: ""},
{Key: "ADDR", Value: []byte("192.168.0.1"), Format: ""},
{Key: "AGE", Value: []byte("20"), Format: ""},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := &env{
prefixs: tt.fields.prefixs,
}
got := e.load(tt.args.envStrings)
if !reflect.DeepEqual(tt.want, got) {
t.Errorf("env.load() = %v, want %v", got, tt.want)
}
})
}
}

Loading…
Cancel
Save