config.go
2.2 KB
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
package utils
import (
"github.com/beego/beego/v2/server/web"
"os"
"strconv"
)
type Configurator interface {
DefaultString(key string, defaultVal string) string
DefaultInt(key string, defaultVal int) int
DefaultInt64(key string, defaultVal int64) int64
DefaultBool(key string, defaultVal bool) bool
DefaultFloat(key string, defaultVal float64) float64
}
// EnvConfigurator read config from env param with default value
type EnvConfigurator struct{}
func (c EnvConfigurator) DefaultString(key string, defaultVal string) string {
if os.Getenv(key) != "" {
return os.Getenv(key)
}
return defaultVal
}
func (c EnvConfigurator) DefaultInt(key string, defaultVal int) int {
if os.Getenv(key) == "" {
return defaultVal
}
v, err := strconv.Atoi(os.Getenv(key))
if err != nil {
return defaultVal
}
return v
}
func (c EnvConfigurator) DefaultInt64(key string, defaultVal int64) int64 {
if os.Getenv(key) == "" {
return defaultVal
}
v, err := strconv.ParseInt(os.Getenv(key), 10, 64)
if err != nil {
return defaultVal
}
return v
}
func (c EnvConfigurator) DefaultBool(key string, defaultVal bool) bool {
if os.Getenv(key) == "" {
return defaultVal
}
v, err := strconv.ParseBool(os.Getenv(key))
if err != nil {
return defaultVal
}
return v
}
func (c EnvConfigurator) DefaultFloat(key string, defaultVal float64) float64 {
if os.Getenv(key) == "" {
return defaultVal
}
v, err := strconv.ParseFloat(os.Getenv(key), 64)
if err != nil {
return defaultVal
}
return v
}
// BeegoAppConfigurator read config from beego config file with default value
type BeegoAppConfigurator struct{}
func (c BeegoAppConfigurator) DefaultString(key string, defaultVal string) string {
return web.AppConfig.DefaultString(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultInt(key string, defaultVal int) int {
return web.AppConfig.DefaultInt(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultInt64(key string, defaultVal int64) int64 {
return web.AppConfig.DefaultInt64(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultBool(key string, defaultVal bool) bool {
return web.AppConfig.DefaultBool(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultFloat(key string, defaultVal float64) float64 {
return web.AppConfig.DefaultFloat(key, defaultVal)
}