-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.go
56 lines (49 loc) · 1.3 KB
/
lib.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
package main
import (
"log"
"os"
)
// GetEnv returns the value of the environment variable or, if unset, the value of the file specified by the environment variable with the same name and "_FILE" appended.
func GetEnv(key string) string {
value := os.Getenv(key)
if value == "" {
file := os.Getenv(key + "_FILE")
if file == "" {
log.Fatalf("Environment variable %s is empty!", key)
}
content, err := os.ReadFile(file)
if err != nil {
log.Fatal("Error trying to load environment variable '", key, "' from file '", file, "': ", err)
}
newlineCount := 0
for _, char := range content {
if char == '\n' {
newlineCount++
if newlineCount > 1 {
log.Fatalf("Environment variable %s contains multiple lines!", key)
}
}
}
value = string(content)
if value == "" {
log.Fatalf("Environment variable %s is empty!", key)
}
value = removeTrailingNewlines(value)
}
return value
}
func removeTrailingNewlines(value string) string {
if value[len(value)-1] == '\n' || value[len(value)-1] == '\r' {
value = value[:len(value)-1]
}
if value[len(value)-1] == '\n' || value[len(value)-1] == '\r' {
value = value[:len(value)-1]
}
return value
}
func GetEnvOrDefault(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}