tsviewer/config/config.go

85 lines
1.8 KiB
Go
Raw Normal View History

2019-01-14 20:07:11 +00:00
package config
import (
"os"
2019-01-31 22:00:42 +00:00
"strconv"
"github.com/spf13/viper"
2019-01-14 20:07:11 +00:00
)
type Config struct {
User struct {
Nickname string
Name string
Password string
}
ServerTS struct {
IP string
PortServer uint16
PortQuery uint16
}
ServerWeb struct {
Port uint16
}
2019-01-15 00:46:39 +00:00
}
2019-01-14 20:07:11 +00:00
const FileName = "config.json"
func New() (*Config, error) {
viper.SetConfigName("config")
viper.SetConfigFile("yaml")
viper.AddConfigPath(".")
if err := viper.ReadInConfig(); err != nil {
return nil, err
2019-01-14 20:07:11 +00:00
}
setDefaults()
2019-01-14 20:07:11 +00:00
var config Config
err := viper.Unmarshal(&config)
2019-01-31 21:07:07 +00:00
config.overrideWithEnvironmentVars()
2019-01-14 20:07:11 +00:00
return &config, err
2019-01-14 20:07:11 +00:00
}
func setDefaults() {
viper.SetDefault("User.Nickname", "serveradmin")
viper.SetDefault("User.Name", "serveradmin")
viper.SetDefault("User.Password", "<changeMe>")
viper.SetDefault("ServerTS.IP", "127.0.0.1")
viper.SetDefault("ServerTS.PortServer", "9987")
viper.SetDefault("ServerTS.PortQuery", "10011")
viper.SetDefault("ServerWeb.Port", "80")
2019-01-14 20:07:11 +00:00
}
2019-01-31 21:07:07 +00:00
func (config *Config) overrideWithEnvironmentVars() {
if nickname := os.Getenv("TS3_NICKNAME"); nickname != "" {
2019-02-03 19:08:48 +00:00
config.User.Nickname = nickname
}
if username := os.Getenv("TS3_NAME"); username != "" {
2019-01-31 22:00:42 +00:00
config.User.Name = username
}
if password := os.Getenv("TS3_PW"); password != "" {
2019-01-31 22:00:42 +00:00
config.User.Password = password
}
if tsIP := os.Getenv("TS3_IP"); tsIP != "" {
2019-01-31 22:00:42 +00:00
config.ServerTS.IP = tsIP
}
if tsPort, err := strconv.Atoi(os.Getenv("TS3_PORT")); tsPort <= 65535 && tsPort >= 0 && err == nil {
2019-01-31 22:00:42 +00:00
config.ServerTS.PortServer = uint16(tsPort)
}
if tsQuery, err := strconv.Atoi(os.Getenv("TS3_QUERY")); tsQuery <= 65535 && tsQuery >= 0 && err == nil {
2019-01-31 22:00:42 +00:00
config.ServerTS.PortQuery = uint16(tsQuery)
}
if webPort, err := strconv.Atoi(os.Getenv("WEB_PORT")); webPort <= 65535 && webPort >= 0 && err == nil {
2019-01-31 22:00:42 +00:00
config.ServerWeb.Port = uint16(webPort)
}
}