Skip to content

Commit

Permalink
✨ feat: Add functionality to load environment variable files
Browse files Browse the repository at this point in the history
  • Loading branch information
sohaha committed Oct 29, 2024
1 parent f96233f commit 0034642
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
34 changes: 34 additions & 0 deletions zutil/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ package zutil
import (
"os"
"runtime"
"strings"

"github.com/sohaha/zlsgo/zfile"
"github.com/sohaha/zlsgo/zstring"
)

func GetOs() string {
Expand Down Expand Up @@ -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
})
}
13 changes: 13 additions & 0 deletions zutil/env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"testing"

"github.com/sohaha/zlsgo"
"github.com/sohaha/zlsgo/zfile"
"github.com/sohaha/zlsgo/zutil"
)

Expand All @@ -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"))
Expand All @@ -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"))
}

0 comments on commit 0034642

Please sign in to comment.