ToyBoomServer/config/settings.go
2024-09-04 18:15:49 +00:00

98 lines
2.1 KiB
Go

package config
import (
"context"
"strings"
"github.com/nose7en/ToyBoomServer/common"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
type Settings struct {
Debug bool `mapstructure:"debug"`
APIListenAddr string `mapstructure:"api_addr"`
RedisConf RedisConf `mapstructure:"redis_conf"`
CacheSize int `mapstructure:"cache_size"` // MB
DB DBConf `mapstructure:"db"`
JWTConfig JWTConfig `mapstructure:"jwt"`
AppleCfg AppleConf `mapstructure:"apple"`
}
type DBConf struct {
Type string `mapstructure:"type"`
DSN string `mapstructure:"dsn"`
}
type RedisConf struct {
Addr string
Password string
DB int
}
type JWTConfig struct {
Secret string `mapstructure:"secret"`
ExpireSec int64 `mapstructure:"expire_sec"`
}
type AppleConf struct {
Secret string `mapstructure:"secret"`
TeamID string `mapstructure:"team_id"`
ClientID string `mapstructure:"client_id"`
KeyID string `mapstructure:"key_id"`
}
var settings *Settings
func GetSettings() *Settings {
return settings
}
func InitSettings() {
c := context.Background()
setConfigParams()
fillDefaultSettings()
readAndParseConfig(c)
}
func fillDefaultSettings() {
viper.SetDefault("cache_size", 10)
viper.SetDefault("debug", false)
viper.SetDefault("db.type", "sqlite")
viper.SetDefault("db.dsn", "toyboom.db")
viper.SetDefault("jwt.expire_sec", 86400*30) // 30 days
}
func setConfigParams() {
viper.SetConfigName("config")
viper.SetConfigType("yml")
viper.AddConfigPath("/etc/toyboom/")
viper.AddConfigPath("$HOME/.toyboom")
viper.AddConfigPath(".")
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
}
func readAndParseConfig(c context.Context) {
err := viper.ReadInConfig()
if err != nil {
common.Logger(c).WithError(err).Errorf("Error reading config file:[%s], will read from env", viper.ConfigFileUsed())
}
err = viper.Unmarshal(&settings)
if err != nil {
common.Logger(c).Panic(err)
}
if IsDebug() {
logrus.SetLevel(logrus.DebugLevel)
gin.SetMode(gin.DebugMode)
} else {
logrus.SetLevel(logrus.InfoLevel)
gin.SetMode(gin.ReleaseMode)
}
}