From 08433d7e04a7167dac7c58aa88d6b8e255c05448 Mon Sep 17 00:00:00 2001 From: FengZhang <97576419@qq.com> Date: Fri, 25 Dec 2020 11:42:19 +0800 Subject: [PATCH] add config load support env var (#309) --- core/conf/config.go | 3 ++- core/conf/config_test.go | 8 ++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/core/conf/config.go b/core/conf/config.go index e4774e0c..a98e5fd8 100644 --- a/core/conf/config.go +++ b/core/conf/config.go @@ -4,6 +4,7 @@ import ( "fmt" "io/ioutil" "log" + "os" "path" "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 { return err } else if loader, ok := loaders[path.Ext(file)]; ok { - return loader(content, v) + return loader([]byte(os.ExpandEnv(string(content))), v) } else { return fmt.Errorf("unrecoginized file type: %s", file) } diff --git a/core/conf/config_test.go b/core/conf/config_test.go index 128f4b2d..cf1c02db 100644 --- a/core/conf/config_test.go +++ b/core/conf/config_test.go @@ -17,13 +17,15 @@ func TestConfigJson(t *testing.T) { } text := `{ "a": "foo", - "b": 1 + "b": 1, + "c": "${FOO}" }` for _, test := range tests { test := test t.Run(test, func(t *testing.T) { t.Parallel() - + os.Setenv("FOO", "2") + defer os.Unsetenv("FOO") tmpfile, err := createTempFile(test, text) assert.Nil(t, err) defer os.Remove(tmpfile) @@ -31,10 +33,12 @@ func TestConfigJson(t *testing.T) { var val struct { A string `json:"a"` B int `json:"b"` + C string `json:"c"` } MustLoad(tmpfile, &val) assert.Equal(t, "foo", val.A) assert.Equal(t, 1, val.B) + assert.Equal(t, "2", val.C) }) } }