/
config.go
93 lines (79 loc) · 2.31 KB
/
config.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
package config
import (
"flag"
"log"
"os"
"strings"
"time"
"github.com/knadh/koanf"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/env"
"github.com/knadh/koanf/providers/file"
)
// Config - Global variable to export
var Config AppConfig
// AppConfig defines
type AppConfig struct {
Server ServerConfig `koanf:"server"`
Database DatabaseConfig `koanf:"database"`
UsageBackend UsageBackendConfig `koanf:"usagebackend"`
}
// ServerConfig defines HTTP server configurations
type ServerConfig struct {
Port int `koanf:"port"`
HTTPS struct {
Cert string `koanf:"cert"`
Key string `koanf:"key"`
}
CORSOrigins []string `koanf:"corsorigins"`
Edition string `koanf:"edition"`
DisableUsage bool `koanf:"disableusage"`
Debug bool `koanf:"debug"`
}
// DatabaseConfig related to database
type DatabaseConfig struct {
Username string `koanf:"username"`
Password string `koanf:"password"`
Host string `koanf:"host"`
Port int `koanf:"port"`
Name string `koanf:"name"`
Version uint `koanf:"version"`
TimeZone string `koanf:"timezone"`
Pool struct {
IdleConnections int `koanf:"idleconnections"`
MaxConnections int `koanf:"maxconnections"`
ConnLifeTime time.Duration `koanf:"connlifetime"`
}
}
type UsageBackendConfig struct {
Host string `koanf:"host"`
Port int `koanf:"port"`
}
// Init - Assign global config to decoded config struct
func Init() error {
k := koanf.New(".")
parser := yaml.Parser()
fs := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
fileRelativePath := fs.String("file", "config/config.yaml", "configuration file")
flag.Parse()
if err := k.Load(file.Provider(*fileRelativePath), parser); err != nil {
log.Fatal(err.Error())
}
if err := k.Load(env.ProviderWithValue("CFG_", ".", func(s, v string) (string, interface{}) {
key := strings.Replace(strings.ToLower(strings.TrimPrefix(s, "CFG_")), "_", ".", -1)
if strings.Contains(v, ",") {
return key, strings.Split(strings.TrimSpace(v), ",")
}
return key, v
}), nil); err != nil {
return err
}
if err := k.Unmarshal("", &Config); err != nil {
return err
}
return ValidateConfig(&Config)
}
// ValidateConfig is for custom validation rules for the configuration
func ValidateConfig(cfg *AppConfig) error {
return nil
}