另客网go项目公用的代码库

config.go 890B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package app
  2. import (
  3. "path/filepath"
  4. "strings"
  5. "github.com/spf13/viper"
  6. )
  7. var (
  8. Config appConfig
  9. )
  10. type appConfig struct {
  11. DB struct {
  12. Host string `mapstructure:"host"`
  13. Port string `mapstructure:"port"`
  14. User string `mapstructure:"user"`
  15. Password string `mapstructure:"password"`
  16. Name string `mapstructure:"name"`
  17. MaxIdleConnections int `mapstructure:"max_idle_connections"`
  18. MaxOpenConnections int `mapstructure:"max_idle_connections"`
  19. } `mapstructure:"db"`
  20. Secret struct {
  21. AuthKey string `mapstructure:"auth_key"`
  22. } `mapstructure:"secret"`
  23. }
  24. func InitConfig(cfg string) {
  25. viper.SetConfigFile(cfg)
  26. viper.SetConfigType(strings.Trim(filepath.Ext(cfg), "."))
  27. if err := viper.ReadInConfig(); err != nil {
  28. panic(err)
  29. }
  30. if err := viper.Unmarshal(&Config); err != nil {
  31. panic(err)
  32. }
  33. }