-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
73 lines (60 loc) · 2.35 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
package config
import (
"fmt"
"strings"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
)
// returns a slice of the supported db names
// a function is used to access this list instead of a global slice to prevent accidental mutation of the slice
func getSupportedDbs() []string {
return []string{"sqlite", "firestore"}
}
// reads the config file
// returns an error if the file couldn't be read or is invalid
func ParseConfig() (Config, error) {
viper.AddConfigPath(".")
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.SetDefault("poll_interval_secs", 300)
viper.SetDefault("database.type", "")
viper.SetDefault("database.firestore.project_id", "")
viper.SetDefault("database.firestore.credentials_file", "")
viper.SetDefault("database.firestore.section_collection_id", "sections")
viper.SetDefault("database.firestore.watcher_collection_id", "watchers")
viper.SetDefault("database.sqlite.connection_string", "")
viper.SetDefault("notifications.emailsmtp.port", 0)
viper.SetDefault("notifications.emailsmtp.host", "")
viper.SetDefault("notifications.emailsmtp.username", "")
viper.SetDefault("notifications.emailsmtp.password", "")
viper.SetDefault("notifications.emailsmtp.from", "")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Info().Msg("No config file found, continuing with env and defaults")
} else {
// Config file was found but another error was produced
return Config{}, fmt.Errorf("failed to read config file: %s", err)
}
}
var cfg Config
if err := viper.Unmarshal(&cfg); err != nil {
return Config{}, fmt.Errorf("failed to unmarshal config: %s", err)
}
if err := validateConfig(cfg); err != nil {
return Config{}, fmt.Errorf("invalid config: %w", err)
}
return cfg, nil
}
func validateConfig(cfg Config) error {
if cfg.Database.Type == "" {
return fmt.Errorf("no database type set. database type can be one of: %v", getSupportedDbs())
} else if cfg.Database.Type != "sqlite" && cfg.Database.Type != "firestore" {
return fmt.Errorf("bad database type. database type can be one of: %v", getSupportedDbs())
}
if cfg.Database.Type == "sqlite" && cfg.Database.SQLite.ConnectionString == "" {
log.Info().Msgf("warn: sqlite connection string is empty")
}
return nil
}