-
Notifications
You must be signed in to change notification settings - Fork 1
/
cfg.go
95 lines (84 loc) 路 2.23 KB
/
cfg.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
package cfg
import (
"os"
"reflect"
"strconv"
"strings"
"time"
)
type (
// Config holds the app config.
Config struct {
Service Service
Publisher Publisher
Store Store
Token Token
TraceAgent TraceAgent
}
// Addr holds remote server's host and port.
Addr struct {
Host string
Port uint32
}
褋onfiger interface {
validate() error
}
)
// New initializes configuration structure with environment variables and returns it.
func New() (*Config, error) {
c := &Config{
Service: Service{
AppID: os.Getenv("APP_ID"),
LogLevel: os.Getenv("LOG_LEVEL"),
RetryAttempts: uintEnv("RETRY_ATTEMPTS"),
RetryTimeout: time.Millisecond * time.Duration(uintEnv("RETRY_TIMEOUT_MS")),
PortRPC: uintEnv("PORT_RPC"),
PortREST: uintEnv("PORT_REST"),
PortWebSocket: uintEnv("PORT_WEBSOCKET"),
TerminationTimeout: time.Millisecond * time.Duration(uintEnv("TERMINATION_TIMEOUT_MS"))},
TraceAgent: TraceAgent{
Addr: Addr{
Host: os.Getenv("TRACE_HOST"),
Port: uintEnv("TRACE_PORT")},
},
Publisher: Publisher{
Addr: Addr{
Host: os.Getenv("PUB_HOST"),
Port: uintEnv("PUB_PORT")},
CfgPatchTopic: os.Getenv("PUB_CFG_PATCH_TOPIC")},
Store: Store{
Addr: Addr{
Host: os.Getenv("STORE_HOST"),
Port: uintEnv("STORE_PORT")},
Password: os.Getenv("STORE_PASSWORD"),
IdleTimeout: time.Millisecond * time.Duration(uintEnv("STORE_IDLE_TIMEOUT_MS")),
MaxIdlePoolConns: uintEnv("STORE_MAX_IDLE_POOL_CONNS")},
Token: Token{
PublicKey: strings.Replace(os.Getenv("PUBLIC_KEY"), `\n`, "\n", -1),
PrivateKey: strings.Replace(os.Getenv("PRIVATE_KEY"), `\n`, "\n", -1)}}
err := c.validate()
return c, err
}
func (c *Config) validate() error {
v := reflect.ValueOf(c).Elem()
baseConfigType := reflect.TypeOf((*褋onfiger)(nil)).Elem()
for i := 0; i < v.NumField(); i++ {
if v.Type().Field(i).Type.Implements(baseConfigType) {
if err := v.Field(i).Interface().(褋onfiger).validate(); err != nil {
return err
}
}
}
return nil
}
func uintEnv(env string) uint32 {
v := os.Getenv(env)
if v == "" {
return 0
}
u, err := strconv.ParseUint(v, 10, 64)
if err != nil {
return 0
}
return uint32(u)
}