-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathenv.go
74 lines (64 loc) · 1.32 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
package main
import (
"github.com/kylelemons/go-gypsy/yaml"
"log"
"sync"
)
var Env *Environment
var s sync.Once
func getEnvInstance() *Environment {
s.Do(func() {
Env := new(Environment)
Env.m = make(map[string]string)
})
return Env
}
type Environment struct {
sync.RWMutex
m map[string]string
}
func (e *Environment) Set(key, value string) {
e.Lock()
defer e.Unlock()
e.m[key] = value
}
func (e *Environment) Get(key string) string {
if v, exist := e.m[key]; exist {
return v
} else {
// 从yaml中获取数据,如果存在 .env.yaml文件,则从里面查找
path, exist := getEnvPath()
if exist { // 存在,获取数据
file, _ := yaml.ReadFile(path)
res, err := file.Get(key)
if err != nil {
log.Fatal(err)
}
return res
} else {
// 不存在这个文件,返回空字符串
return ""
}
}
return ""
}
func (e *Environment) GetWithDefault(key, def string) string {
if v, exist := e.m[key]; exist {
return v
} else {
// 从yaml中获取数据,如果存在 .env.yaml文件,则从里面查找
path, exist := getEnvPath()
if exist { // 存在,获取数据
file, _ := yaml.ReadFile(path)
res, err := file.Get(key)
if err != nil {
return def
}
return res
} else {
// 不存在这个文件,返回空字符串
return def
}
}
return def
}