Browse Source

misc: dot env reader(#master)

master
OhYee 2 years ago
parent
commit
452fbb5671
Signed by: OhYee
GPG Key ID: 5A9E1F63ED274FBB
  1. 3
      .gitignore
  2. 3
      env/.env
  3. 41
      env/env.go
  4. 47
      env/env_test.go

3
.gitignore vendored

@ -1,3 +1,4 @@ @@ -1,3 +1,4 @@
__pycache__
*.db
.vscode
.vscode
/.env

3
env/.env vendored

@ -0,0 +1,3 @@ @@ -0,0 +1,3 @@
NAME=OhYee
secret=123456
password=A1b2c=!

41
env/env.go vendored

@ -0,0 +1,41 @@ @@ -0,0 +1,41 @@
package env
import (
"io/ioutil"
"os"
"path"
"strings"
"github.com/OhYee/rainbow/errors"
)
// GetEnv get environment from file
func GetEnv(filename string) (environments map[string]string, err error) {
defer errors.Wrapper(&err)
environments = make(map[string]string)
b, err := ioutil.ReadFile(filename)
if err != nil {
return
}
for _, line := range strings.Split(string(b), "\n") {
ss := strings.Split(line, "=")
if len(ss) >= 2 {
environments[ss[0]] = strings.Join(ss[1:], "=")
}
}
return
}
// PWDFile file in current directory
func PWDFile(filename string) (absPath string) {
var pwd string
var err error
if pwd, err = os.Getwd(); err != nil {
pwd = ""
}
absPath = path.Join(pwd, filename)
return
}

47
env/env_test.go vendored

@ -0,0 +1,47 @@ @@ -0,0 +1,47 @@
package env
import (
"reflect"
"testing"
)
func TestGetEnv(t *testing.T) {
type args struct {
filename string
}
tests := []struct {
name string
args args
wantEnvironments map[string]string
wantErr bool
}{
{
name: "test env",
args: args{filename: PWDFile(".env")},
wantEnvironments: map[string]string{
"NAME": "OhYee",
"secret": "123456",
"password": "A1b2c=!",
},
wantErr: false,
},
{
name: "error",
args: args{filename: PWDFile(".error")},
wantEnvironments: map[string]string{},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotEnvironment, err := GetEnv(tt.args.filename)
if (err != nil) != tt.wantErr {
t.Errorf("GetEnv() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(gotEnvironment, tt.wantEnvironments) {
t.Errorf("GetEnv() = %v, want %v", gotEnvironment, tt.wantEnvironments)
}
})
}
}
Loading…
Cancel
Save