From 0034642dae2211434e929bb54d267270715b2819 Mon Sep 17 00:00:00 2001 From: seekwe Date: Tue, 29 Oct 2024 20:48:16 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20Add=20functionality=20to=20?= =?UTF-8?q?load=20environment=20variable=20files?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- zutil/env.go | 34 ++++++++++++++++++++++++++++++++++ zutil/env_test.go | 13 +++++++++++++ 2 files changed, 47 insertions(+) diff --git a/zutil/env.go b/zutil/env.go index c9ca589..c353fa4 100644 --- a/zutil/env.go +++ b/zutil/env.go @@ -3,8 +3,10 @@ package zutil import ( "os" "runtime" + "strings" "github.com/sohaha/zlsgo/zfile" + "github.com/sohaha/zlsgo/zstring" ) func GetOs() string { @@ -38,3 +40,35 @@ func Getenv(name string, def ...string) string { func GOROOT() string { return zfile.RealPath(runtime.GOROOT()) } + +func Loadenv(filenames ...string) (err error) { + filenames = filenamesOrDefault(filenames) + + for _, filename := range filenames { + err = loadFile(filename) + if err != nil { + return + } + } + return +} + +func filenamesOrDefault(filenames []string) []string { + if len(filenames) == 0 { + return []string{".env"} + } + return filenames +} + +func loadFile(filename string) error { + return zfile.ReadLineFile(filename, func(line int, data []byte) error { + e := strings.Split(zstring.Bytes2String(data), "=") + var value string + if len(e) > 1 { + value = e[1] + } + + _ = os.Setenv(zstring.TrimSpace(e[0]), strings.TrimSpace(value)) + return nil + }) +} diff --git a/zutil/env_test.go b/zutil/env_test.go index 0669e8e..8825913 100644 --- a/zutil/env_test.go +++ b/zutil/env_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/sohaha/zlsgo" + "github.com/sohaha/zlsgo/zfile" "github.com/sohaha/zlsgo/zutil" ) @@ -19,6 +20,7 @@ func TestOs(T *testing.T) { isMac := zutil.IsMac() t.Log("isMac", isMac) } + func TestEnv(T *testing.T) { t := zlsgo.NewTest(T) t.Log(zutil.Getenv("HOME")) @@ -29,3 +31,14 @@ func TestEnv(T *testing.T) { func TestGOROOT(t *testing.T) { t.Log(zutil.GOROOT()) } + +func TestLoadenv(t *testing.T) { + tt := zlsgo.NewTest(t) + _ = zfile.WriteFile(".env", []byte("myos=linux\n name=zls ")) + defer zfile.Rmdir(".env") + + tt.NoError(zutil.Loadenv()) + + tt.Equal("linux", zutil.Getenv("myos")) + tt.Equal("zls", zutil.Getenv("name")) +}