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
|
package env
import (
"io/ioutil"
"os"
"github.com/blang/vfs"
)
// Getenv - retrieves the value of the environment variable named by the key.
// If the variable is unset, but the same variable ending in `_FILE` is set, the
// referenced file will be read into the value.
// Otherwise the provided default (or an emptry string) is returned.
func Getenv(key string, def ...string) string {
return GetenvVFS(vfs.OS(), key, def...)
}
// GetenvVFS - a convenience function intended for internal use only!
func GetenvVFS(fs vfs.Filesystem, key string, def ...string) string {
val := getenvFile(fs, key)
if val == "" && len(def) > 0 {
return def[0]
}
return val
}
func getenvFile(fs vfs.Filesystem, key string) string {
val := os.Getenv(key)
if val != "" {
return val
}
p := os.Getenv(key + "_FILE")
if p != "" {
val, err := readFile(fs, p)
if err != nil {
return ""
}
return val
}
return ""
}
func readFile(fs vfs.Filesystem, p string) (string, error) {
f, err := fs.OpenFile(p, os.O_RDONLY, 0)
if err != nil {
return "", err
}
b, err := ioutil.ReadAll(f)
if err != nil {
return "", err
}
return string(b), nil
}
|