forked from ddollar/forego
-
Notifications
You must be signed in to change notification settings - Fork 4
/
env.go
99 lines (77 loc) · 1.52 KB
/
env.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"fmt"
"os"
"sync"
"github.com/subosito/gotenv"
)
type Env struct {
m sync.Map
}
func (e *Env) Get(key string) string {
value, ok := e.m.Load(key)
if !ok {
return ""
}
return value.(string)
}
func (e *Env) Set(key, value string) {
e.m.Store(key, value)
}
func (e *Env) Delete(key string) {
e.m.Delete(key)
}
// NewEnv makes a new environment
func NewEnv() *Env {
return &Env{sync.Map{}}
}
type envFiles []string
func (e *envFiles) String() string {
return fmt.Sprintf("%s", *e)
}
func (e *envFiles) Set(value string) error {
*e = append(*e, value)
return nil
}
func loadEnvs(files []string) (*Env, error) {
if len(files) == 0 {
files = []string{".env"}
}
env := NewEnv()
// don't need to lock either environment
for _, file := range files {
tmpEnv, err := ReadEnv(file)
if err != nil {
return nil, err
}
// Merge the file I just read into the env.
tmpEnv.m.Range(func(key, value interface{}) bool {
env.m.Store(key, value)
return true
})
}
return env, nil
}
func ReadEnv(filename string) (*Env, error) {
env := NewEnv()
if _, err := os.Stat(filename); os.IsNotExist(err) {
return env, nil
}
fd, err := os.Open(filename)
if err != nil {
return nil, err
}
defer fd.Close()
for key, val := range gotenv.Parse(fd) {
env.Set(key, val)
}
return env, nil
}
func (e *Env) asArray() (env []string) {
env = append(env, os.Environ()...)
e.m.Range(func(name, val interface{}) bool {
env = append(env, fmt.Sprintf("%s=%s", name, val))
return true
})
return
}