-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoenv.go
60 lines (50 loc) · 890 Bytes
/
goenv.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
package goenv
import (
"bufio"
"io"
"os"
"strings"
)
// Env is the map
type Env map[string]string
func init() {
LoadEnv()
}
// LoadEnv is the function load .env file
func LoadEnv(filename ...string) error {
if len(filename) == 0 {
filename = []string{".env"}
}
for _, file := range filename {
f, e := os.Open(file)
if e != nil {
return e
}
defer f.Close()
env := parse(f)
for key, val := range env {
Setenv(key, val)
}
}
return nil
}
// Setenv is the function set key:value ton environment
func Setenv(key string, val string) {
os.Setenv(key, val)
}
func parse(r io.Reader) Env {
env := make(Env)
scanner := bufio.NewScanner(r)
for scanner.Scan() {
text := scanner.Text()
if strings.Contains(text, "=") {
i := strings.Index(text, "=")
if i > -1 {
key := text[:i]
val := text[i+1:]
env[key] = val
}
}
}
return env
}