init repo
This commit is contained in:
5
config/helper.go
Normal file
5
config/helper.go
Normal file
@@ -0,0 +1,5 @@
|
||||
package config
|
||||
|
||||
func IsDebug() bool {
|
||||
return GetSettings().Debug
|
||||
}
|
||||
95
config/settings.go
Normal file
95
config/settings.go
Normal file
@@ -0,0 +1,95 @@
|
||||
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"`
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user