-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgoenv.go
More file actions
64 lines (49 loc) · 958 Bytes
/
goenv.go
File metadata and controls
64 lines (49 loc) · 958 Bytes
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
package goenv
import (
"errors"
"fmt"
"os"
"reflect"
"strings"
"github.com/joho/godotenv"
)
func Load[T any](s *T) error {
err := godotenv.Load()
if err != nil {
return err
}
v := reflect.ValueOf(*s)
ptr := reflect.ValueOf(s)
errs := []error{}
str := ptr.Elem()
if str.Kind() != reflect.Struct {
return errors.New("value should be a struct")
}
for i := range v.Type().NumField() {
env := v.Type().Field(i).Tag.Get("env")
sl := strings.Split(env, ",")
envName := sl[0]
val := os.Getenv(envName)
if isEnvRequired(env) && val == "" {
errs = append(errs, fmt.Errorf("Env %s is required", envName))
}
defaultValue := getEnvDefaultValue(env)
if val == "" {
val = defaultValue
}
f := str.Field(i)
if f.IsValid() && f.CanSet() {
f.SetString(val)
}
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
func MustLoad[T any](s *T) {
err := Load(s)
if err != nil {
panic(err)
}
}