123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- package config
-
- import (
- "io/ioutil"
- "log"
- "path"
- "strings"
-
- "github.com/Unknwon/i18n"
- "github.com/gin-gonic/gin"
- "github.com/joho/godotenv"
- "github.com/sirupsen/logrus"
- "github.com/spf13/viper"
- )
-
- // global config
- var (
- C appConfig
- )
-
- type appConfig struct {
- App struct {
- Debug bool `mapstructure:"debug"`
- Secret string `mapstructure:"secret"`
- } `mapstructure:"app"`
- Monitor struct {
- Timeout int64 `mapstructure:"timeout"`
- URLs string `mapstructure:"urls"` // url_1;url_2
- }
- Notice struct {
- SMTP struct {
- Host string `mapstructure:"host"`
- Port string `mapstructure:"port"`
- User string `mapstructure:"user"`
- Password string `mapstructure:"password"`
- } `mapstructure:"smtp"`
- Emails string `mapstructure:"emails"`
- } `mapstructure:"notice"`
- }
-
- func init() {
- // 去掉烦人的gin提示,在http模块中会根据需要打开
- gin.SetMode(gin.ReleaseMode)
-
- // load .env file for testing
- godotenv.Load()
-
- // app
- viper.SetDefault("app.debug", true)
- viper.SetDefault("app.secret", "123456")
-
- // smtp
- viper.SetDefault("notice.smtp.host", "host")
- viper.SetDefault("notice.smtp.port", "port")
- viper.SetDefault("notice.smtp.user", "user")
- viper.SetDefault("notice.smtp.password", "password")
- viper.SetDefault("notice.emails", "")
-
- // monitor
- viper.SetDefault("monitor.timeout", 500)
- viper.SetDefault("monitor.urls", "")
-
- // bind env
- viper.SetEnvPrefix("monitor")
- viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
- viper.AutomaticEnv()
-
- // unmarshal config to struct
- if err := viper.Unmarshal(&C); err != nil {
- log.Fatalf("viper.Unmarshal error: %v\n", err)
- }
-
- // set logrus debug mode
- if C.App.Debug {
- logrus.SetLevel(logrus.DebugLevel)
- }
-
- // load language file for i18n
- files, err := ioutil.ReadDir("languages")
- if err == nil {
- for _, file := range files {
- if err := i18n.SetMessage(strings.TrimSuffix(file.Name(), path.Ext(file.Name())), "languages/"+file.Name()); err != nil {
- log.Fatalf("i18n.SetMessage error: %v\n", err)
- }
- }
-
- i18n.SetDefaultLang("en-US")
- }
- }
|