-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_env.go
63 lines (51 loc) · 1.08 KB
/
config_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
package config
import (
"fmt"
"os"
"github.com/gomig/caster"
"github.com/gomig/utils"
"github.com/joho/godotenv"
)
type envConfig struct {
Files []string
data map[string]any
}
func (envConfig) err(format string, args ...any) error {
return utils.TaggedError([]string{"EnvConfig"}, format, args...)
}
func (ec *envConfig) Load() error {
if ec.data == nil {
ec.data = make(map[string]any)
}
if err := godotenv.Overload(ec.Files...); err != nil {
return ec.err(err.Error())
}
for k, v := range ec.data {
if err := ec.Set(k, v); err != nil {
return err
}
}
return nil
}
func (ec *envConfig) Set(key string, value any) error {
ec.data[key] = value
if err := os.Setenv(key, fmt.Sprintf("%v", value)); err != nil {
return ec.err(err.Error())
}
return nil
}
func (envConfig) Get(key string) any {
if v, ok := os.LookupEnv(key); ok {
return v
}
return nil
}
func (envConfig) Exists(key string) bool {
if _, ok := os.LookupEnv(key); ok {
return true
}
return false
}
func (ec envConfig) Cast(key string) caster.Caster {
return caster.NewCaster(ec.Get(key))
}