add config load support env var (#309)

master
FengZhang 4 years ago committed by GitHub
parent a3b525b50d
commit 08433d7e04
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"log" "log"
"os"
"path" "path"
"github.com/tal-tech/go-zero/core/mapping" "github.com/tal-tech/go-zero/core/mapping"
@ -19,7 +20,7 @@ func LoadConfig(file string, v interface{}) error {
if content, err := ioutil.ReadFile(file); err != nil { if content, err := ioutil.ReadFile(file); err != nil {
return err return err
} else if loader, ok := loaders[path.Ext(file)]; ok { } else if loader, ok := loaders[path.Ext(file)]; ok {
return loader(content, v) return loader([]byte(os.ExpandEnv(string(content))), v)
} else { } else {
return fmt.Errorf("unrecoginized file type: %s", file) return fmt.Errorf("unrecoginized file type: %s", file)
} }

@ -17,13 +17,15 @@ func TestConfigJson(t *testing.T) {
} }
text := `{ text := `{
"a": "foo", "a": "foo",
"b": 1 "b": 1,
"c": "${FOO}"
}` }`
for _, test := range tests { for _, test := range tests {
test := test test := test
t.Run(test, func(t *testing.T) { t.Run(test, func(t *testing.T) {
t.Parallel() t.Parallel()
os.Setenv("FOO", "2")
defer os.Unsetenv("FOO")
tmpfile, err := createTempFile(test, text) tmpfile, err := createTempFile(test, text)
assert.Nil(t, err) assert.Nil(t, err)
defer os.Remove(tmpfile) defer os.Remove(tmpfile)
@ -31,10 +33,12 @@ func TestConfigJson(t *testing.T) {
var val struct { var val struct {
A string `json:"a"` A string `json:"a"`
B int `json:"b"` B int `json:"b"`
C string `json:"c"`
} }
MustLoad(tmpfile, &val) MustLoad(tmpfile, &val)
assert.Equal(t, "foo", val.A) assert.Equal(t, "foo", val.A)
assert.Equal(t, 1, val.B) assert.Equal(t, 1, val.B)
assert.Equal(t, "2", val.C)
}) })
} }
} }

Loading…
Cancel
Save