-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil_api.go
73 lines (60 loc) · 1.65 KB
/
util_api.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
package goenv
import (
"log"
"os"
)
// Export config struct to default.yml, variables with prefix
func Export(prefix string, config interface{}) error {
err := CallSetDefaults(config)
if err != nil {
return err
}
b, err := Marshal(config, prefix)
if err != nil {
return err
}
return os.WriteFile("default.yml", b, os.ModePerm)
}
// MustExport export config struct to default.yml, variables with prefix
// panic if error
func MustExport(prefix string, config interface{}) {
err := Export(prefix, config)
if err != nil {
panic(err)
}
}
// Import variables from config.yml and additional config files to config struct
// then import variable from env to config struct
// overwrite if variable already exists
// notice: call CallInitialize after importing
func Import(prefix string, config interface{}, cfgs ...string) error {
// read variables from files
files := append([]string{"config.yml"}, cfgs...)
for _, file := range files {
err := UnmarshalFile(config, prefix, file)
if err != nil {
if os.IsNotExist(err) {
log.Printf("WARN: skip, %v\n", err)
continue
}
return err
}
}
// read variables from environment
err := UnmarshalEnv(config, prefix)
if err != nil {
return err
}
// set default and initial
// return CallMethods(config, "SetDefaults", "Initialize")
return CallSetDefaults(config)
}
// MustImport import variable from config.yml and additional config files and environment, panic if error
// Get more detail, see Import API
// notice: call CallInitialize after importing
func MustImport(prefix string, config interface{}, cfgs ...string) {
err := Import(prefix, config, cfgs...)
if err != nil {
panic(err)
}
}