-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenv.go
More file actions
110 lines (100 loc) · 2.12 KB
/
env.go
File metadata and controls
110 lines (100 loc) · 2.12 KB
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
100
101
102
103
104
105
106
107
108
109
110
package utils
import (
"io/ioutil"
"log"
"os"
"strconv"
"strings"
)
// envs a map stores all key-value pairs in .env file
var envs map[string]string
// LoadEnvs loads .env file
func LoadEnvs(path string) {
// clean envs
envs = map[string]string{}
// read file content
bytesRaw, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal("Cannot find .env file.")
return
}
rows := strings.Split(string(bytesRaw), "\n")
for i, _ := range rows {
rows[i] = strings.Trim(rows[i], " ")
// parse key and value
sepIndex := strings.Index(rows[i], "=")
if sepIndex == -1 {
continue
}
k := strings.Trim(rows[i][:sepIndex], " ")
v := strings.Trim(rows[i][sepIndex+1:], " ")
if string(k[0]) == "#" {
// pass invalid format row and comments
continue
}
envs[k] = v
}
// fmt.Println(envs)
}
// EnvString returns string value by key. If key is not exist, it returns spare value
func EnvString(key string, spare string) string {
if s := os.Getenv(key); s != "" {
return s
}
if s, ok := envs[key]; ok {
return s
}
return spare
}
// EnvBool returns bool value by key. If key is not exist, it returns spare value
func EnvBool(key string, spare bool) bool {
if s := os.Getenv(key); s != "" {
if s == "true" {
return true
}
return false
}
if s, ok := envs[key]; ok {
if s == "true" {
return true
}
return false
}
return spare
}
// EnvInt returns int value by key. If key is not exist, it returns spare value
func EnvInt(key string, spare int64) int64 {
if s := os.Getenv(key); s != "" {
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return spare
}
return i
}
if s, ok := envs[key]; ok {
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return spare
}
return i
}
return spare
}
// EnvFloat returns float value by key. If key is not exist, it returns spare value
func EnvFloat(key string, spare float64) float64 {
if s := os.Getenv(key); s != "" {
i, err := strconv.ParseFloat(s, 64)
if err != nil {
return spare
}
return i
}
if s, ok := envs[key]; ok {
i, err := strconv.ParseFloat(s, 64)
if err != nil {
return spare
}
return i
}
return spare
}