-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
79 lines (65 loc) · 1.67 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
package main
import (
"errors"
"os"
"path/filepath"
"strings"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
var configPath *string = pflag.StringP("config", "C", "", "Path to config file")
func init() {
pflag.Parse()
viper.SetConfigName("config")
viper.SetConfigType("toml")
viper.SetEnvPrefix("modmail")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
var dotConfigPath string
if os.Getenv("XDG_CONFIG_HOME") != "" {
dotConfigPath = os.Getenv("XDG_CONFIG_HOME") + "/modmail"
} else {
dotConfigPath = os.Getenv("HOME") + "/.config/modmail"
}
viper.AddConfigPath(dotConfigPath)
viper.AddConfigPath("/etc/modmail")
viper.AddConfigPath(".")
// This is how Heroku provides the port number.
envPort := os.Getenv("PORT")
if envPort == "" {
envPort = "8080"
}
viper.SetDefault("discord.token", "")
viper.SetDefault("discord.pub_key", "")
viper.SetDefault("dev_mode.enabled", false)
viper.SetDefault("dev_mode.guild", 0)
viper.SetDefault("http_server.enabled", false)
viper.SetDefault("http_server.port", envPort)
viper.AutomaticEnv()
if *configPath != "" {
viper.SetConfigFile(*configPath)
}
if err := viper.ReadInConfig(); err != nil {
if errors.As(err, &viper.ConfigFileNotFoundError{}) {
//saveDefaultConfig(*configPath, dotConfigPath)
} else {
panic(err)
}
}
}
func saveDefaultConfig(configPath, dotPath string) {
var err error
if configPath != "" {
if err = os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
panic(err)
}
err = viper.SafeWriteConfigAs(configPath)
} else {
if err = os.MkdirAll(dotPath, 0755); err != nil {
panic(err)
}
err = viper.SafeWriteConfig()
}
if err != nil {
panic(err)
}
}