-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
90 lines (75 loc) · 2.06 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
package main
import (
"strings"
"github.com/spf13/viper"
)
type Config struct {
Debug bool `mapstructure:"debug"`
Storage ConfigStorage `mapstructure:"storage"`
SyntaxDefault string `mapstructure:"syntax_default"`
Syntax []ConfigSyntax `mapstructure:"syntax"`
ExpiresDefault string `mapstructure:"expires_default"`
Expires []ConfigExpires `mapstructure:"expires"`
}
type ConfigStorage struct {
SQL ConfigStorageSQL `mapstructure:"sql"`
}
type ConfigStorageSQL struct {
Host string `mapstructure:"host"`
DB string `mapstructure:"db"`
Port int `mapstructure:"port"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
}
type ConfigSyntax struct {
Label string `mapstructure:"label"`
Syntax string `mapstructure:"syntax"`
Aliases []string `mapstructure:"aliases"`
}
type ConfigExpires struct {
Label string `mapstructure:"label"`
Expires int `mapstructure:"expires"`
}
func (c *Config) ResolveSyntax(s string) (bool, ConfigSyntax) {
for _, syntax := range c.Syntax {
if syntax.Syntax == s || inArray(syntax.Aliases, s) {
return true, syntax
}
}
return false, ConfigSyntax{}
}
func inArray(a []string, s string) bool {
for _, item := range a {
if item == s {
return true
}
}
return false
}
func InitConfig() (*Config, error) {
viper.AddConfigPath(".")
viper.SetConfigName("config")
viper.SetEnvPrefix("paste")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
setConfigDefaults()
config := Config{}
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
return nil, err
}
}
err := viper.Unmarshal(&config)
if err != nil {
return nil, err
}
return &config, nil
}
func setConfigDefaults() {
viper.SetDefault("debug", false)
viper.SetDefault("storage.sql.host", "")
viper.SetDefault("storage.sql.port", 3306)
viper.SetDefault("storage.sql.db", "paste")
viper.SetDefault("storage.sql.user", "")
viper.SetDefault("storage.sql.password", "")
}