Skip to content

Commit

Permalink
chore(config/env): minor refactor (go-kratos#1232)
Browse files Browse the repository at this point in the history
* chore(config/env): minor refactor
  • Loading branch information
xuyang2 authored and elvizlai committed Aug 2, 2021
1 parent 7b76be5 commit 3f72a07
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 2 deletions.
9 changes: 7 additions & 2 deletions config/env/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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) {
Expand Down
64 changes: 64 additions & 0 deletions config/env/env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
})
}
}

0 comments on commit 3f72a07

Please sign in to comment.