-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
104 lines (91 loc) · 2.54 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
94
95
96
97
98
99
100
101
102
103
104
package config
import (
"encoding/json"
"fmt"
"log"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/spf13/viper"
"github.com/artnoi43/fngobot/adapter/handler/clihandler"
"github.com/artnoi43/fngobot/adapter/handler/tghandler"
)
type Config struct {
Telegram tghandler.Config `mapstructure:"telegram" json:"telegram"`
CLI clihandler.Config `mapstructure:"cli" json:"cli"`
}
type Location struct {
Dir string
Name string
Ext string
}
func ParsePath(rawPath string) *Location {
dir, configFile := filepath.Split(rawPath)
name := strings.Split(configFile, ".")[0] // remove ext from filename
ext := filepath.Ext(configFile)[1:] // remove dot
return &Location{
Dir: dir,
Name: name,
Ext: ext,
}
}
func InitConfig(dir string, file string, ext string) (conf *Config, err error) {
// Defaults
// TrackInterval int `mapstructure:"track_interval"`
// AlertInterval int `mapstructure:"alert_interval"`
// AlertTimes int `mapstructure:"alert_times"`
viper.SetDefault("cli.handler.track_interval", 60)
viper.SetDefault("cli.handler.alert_interval", 60)
viper.SetDefault("cli.handler.alert_times", 5)
viper.SetDefault("telegram.handler.track_interval", 60)
viper.SetDefault("telegram.handler.alert_interval", 60)
viper.SetDefault("telegram.handler.alert_times", 5)
viper.SetDefault("telegram.client.bot_token", "123456789:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
viper.SetDefault("telegram.client.timeout_seconds", 10)
viper.SetDefault("telegram.client.verbose", false)
// ENV
if err := viper.BindEnv("bot_token"); err != nil {
return nil, err
}
err = loadConf(dir, file, ext)
if err != nil {
return nil, err
}
conf, err = unmarshal()
if err != nil {
return nil, err
}
j, _ := json.Marshal(conf)
log.Printf("%s\n", j)
fmt.Printf("\n\n")
return conf, nil
}
func loadConf(dir string, file string, ext string) error {
// Default config file dir is $HOME/config/fngobot
// From CLI: -c <path>
viper.AddConfigPath(dir)
viper.SetConfigName(file)
viper.SetConfigType(ext)
// Parse config from both env and file
viper.AutomaticEnv()
err := viper.ReadInConfig()
if err != nil {
// Config file not found
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// WriteConfig() just won't create new file if doesn't exist
if err := viper.SafeWriteConfig(); err != nil {
return errors.Wrap(err, "failed to write config")
}
} else {
return err
}
}
return nil
}
func unmarshal() (conf *Config, err error) {
err = viper.Unmarshal(&conf)
if err != nil {
return nil, err
}
return conf, nil
}