-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_file.go
129 lines (101 loc) · 1.93 KB
/
config_file.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package config
import (
"bytes"
"errors"
"io"
"io/fs"
"log"
"os"
"strconv"
"github.com/joho/godotenv"
"gopkg.in/yaml.v3"
)
// Read a ConfigFile by name from an [fs.FS].
func ReadConfigFile[T any](fsys fs.FS, name string) (T, error) {
buffer, err := getBuffer(fsys, name)
if err != nil {
var t T
return t, err
}
conf, err := getConfigFile[T](buffer)
if err != nil {
return conf, err
}
conf = GetConfigMap(conf)
return conf, nil
}
func getBuffer(fsys fs.FS, name string) (*bytes.Buffer, error) {
b, err := fs.ReadFile(fsys, name)
if err != nil {
return nil, err
}
buf := bytes.NewBuffer(b)
if buf == nil {
return nil, ErrNilReader
}
return buf, nil
}
var ErrNilReader = errors.New("nil Reader")
func getConfigFile[T any](r io.Reader) (T, error) {
var configFile T
decoder := yaml.NewDecoder(r)
err := decoder.Decode(&configFile)
return configFile, err
}
func LoadEnv(filenames ...string) error {
err := godotenv.Load(filenames...)
if err != nil {
log.Fatal("Error loading .env file")
}
return nil
}
func GetEnvString(name string, defaultValues ...string) string {
value := os.Getenv(name)
if value != "" {
return value
}
for _, newValue := range defaultValues {
value = newValue
if value != "" {
break
}
}
return value
}
func GetEnvInt[U ~int](name string, defaultValues ...*U) U {
if i, ok := getOsInt(name); ok {
return U(i)
}
for _, value := range defaultValues {
if value != nil {
return U(*value)
}
}
return 0
}
func GetEnvInt64[U ~int64](name string, defaultValues ...*U) U {
if i, ok := getOsInt(name); ok {
return U(i)
}
for _, value := range defaultValues {
if value != nil {
return U(*value)
}
}
return 0
}
func Nullable[U any](value U) *U {
return &value
}
func getOsInt(name string) (int, bool) {
var i int
s := os.Getenv(name)
if s == "" {
return 0, false
}
i, err := strconv.Atoi(s)
if err != nil {
return 0, false
}
return i, true
}