-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
61 lines (50 loc) · 1.38 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
package main
import (
"context"
"flag"
"github.com/asdfzxcvbn/tgmessenger"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
type Config struct {
BotToken string `mapstructure:"bot_token"`
DbPath string `mapstructure:"db_path"`
ChatId string `mapstructure:"chat_id"`
TopicId int64 `mapstructure:"topic_id"`
Template string `mapstructure:"template"`
Apps []string `mapstructure:"apps"`
}
var (
uViper = viper.New()
uCtx context.Context
uCtxCancel context.CancelFunc
config Config
configPath string
)
// first time config load
func init() {
flag.StringVar(&configPath, "config", "./config.toml", "path to config file")
flag.Parse()
uCtx, uCtxCancel = context.WithCancel(context.Background())
uViper.SetConfigFile(configPath)
reloadConfig(false)
uViper.OnConfigChange(func(in fsnotify.Event) {
reloadConfig(false)
uCtxCancel()
})
uViper.WatchConfig()
}
// reloadConfig parses the config file and makes a new [tgmessenger.Messenger] instance, only validating at startup.
// reloadConfig panics on error.
func reloadConfig(validateToken bool) {
err := uViper.ReadInConfig()
if err != nil {
panic(err)
}
if err = uViper.Unmarshal(&config); err != nil {
panic(err)
}
if messenger, err = tgmessenger.NewMessenger(config.BotToken, config.ChatId, config.TopicId, tgmessenger.ParseHTML, validateToken); err != nil {
panic(err)
}
}