config.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package config
  2. import (
  3. "log"
  4. "runtime"
  5. _ "github.com/go-sql-driver/mysql"
  6. "github.com/jmoiron/sqlx"
  7. "github.com/spf13/viper"
  8. )
  9. type Config struct {
  10. Port int `json:"port,omitempty"`
  11. DataBase *DataBase `json:"database,omitempty"`
  12. }
  13. type DataBase struct {
  14. Name string `json:"name,omitempty"`
  15. Host string `json:"host,omitempty"`
  16. MaxOpenConns int `json:"maxOpenConns,omitempty"`
  17. MaxIdleConns int `json:"maxIdleConns,omitempty"`
  18. }
  19. var Conf *Config
  20. var DB *sqlx.DB
  21. func InitConf() {
  22. if runtime.GOOS == "linux" {
  23. viper.SetConfigFile("./config-linux.yaml")
  24. } else {
  25. viper.SetConfigFile("./config.yaml")
  26. }
  27. if err := viper.ReadInConfig(); err != nil {
  28. panic("Read file error:" + err.Error())
  29. }
  30. var config Config
  31. if err := viper.Unmarshal(&config); err != nil {
  32. panic("File exchange error:" + err.Error())
  33. }
  34. Conf = &config
  35. }
  36. func InitDataBase() {
  37. var err error
  38. DB, err = sqlx.Connect(Conf.DataBase.Name, Conf.DataBase.Host)
  39. if err != nil {
  40. log.Fatalf("connect DB failed, err:%v\n", err)
  41. return
  42. }
  43. DB.SetMaxOpenConns(Conf.DataBase.MaxOpenConns)
  44. DB.SetMaxIdleConns(Conf.DataBase.MaxOpenConns)
  45. }
  46. func init() {
  47. // 1、初始化配置
  48. InitConf()
  49. // 2、初始化数据库
  50. InitDataBase()
  51. }