-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathenv.go
108 lines (98 loc) · 2.3 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
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
// Package env provides helpers functions to load different variable types from the environment.
package env
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"time"
)
// GetStringOrDefault value.
func GetStringOrDefault(name, defaultV string) string {
v, ok := os.LookupEnv(name)
if !ok {
return defaultV
}
return v
}
// GetIntOrDefault value. Also returns the default value if the value is not an int.
func GetIntOrDefault(name string, defaultV int) int {
v, ok := os.LookupEnv(name)
if !ok {
return defaultV
}
vAsInt, err := strconv.Atoi(v)
if err != nil {
return defaultV
}
return vAsInt
}
// GetBoolOrDefault value. Also returns the default value if the value is not a boolean.
func GetBoolOrDefault(name string, defaultV bool) bool {
v, ok := os.LookupEnv(name)
if !ok {
return defaultV
}
vAsBool, err := strconv.ParseBool(v)
if err != nil {
return defaultV
}
return vAsBool
}
// GetDurationOrDefault value. Also returns the default value if the value is not a time.Duration.
func GetDurationOrDefault(name string, defaultV time.Duration) time.Duration {
v, ok := os.LookupEnv(name)
if !ok {
return defaultV
}
vAsDuration, err := time.ParseDuration(v)
if err != nil {
return defaultV
}
return vAsDuration
}
// Load environment variables from environment files. Defaults to loading from .env.
func Load(paths ...string) error {
if len(paths) == 0 {
paths = []string{".env"}
}
for _, path := range paths {
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("error reading %v: %w", path, err)
}
s := bufio.NewScanner(file)
var i int
for s.Scan() {
i++
line := s.Text()
// Blank lines
if line == "" {
continue
}
// Comments
if strings.HasPrefix(line, "#") {
continue
}
parts := strings.SplitN(line, "=", 2)
if len(parts) < 2 {
return fmt.Errorf("missing equal sign on line %v in %v", i, path)
}
if err := os.Setenv(parts[0], parts[1]); err != nil {
return fmt.Errorf("error setting environment variable for line %v in %v: %w", i, path, err)
}
}
if err := s.Err(); err != nil {
return fmt.Errorf("error scanning %v: %w", path, err)
}
_ = file.Close()
}
return nil
}
// MustLoad calls Load and panics on errors.
func MustLoad(paths ...string) {
if err := Load(paths...); err != nil {
panic(err)
}
}