1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- package config
- import (
- "log"
- "runtime"
- _ "github.com/go-sql-driver/mysql"
- "github.com/jmoiron/sqlx"
- "github.com/spf13/viper"
- )
- type Config struct {
- Port int `json:"port,omitempty"`
- DataBase *DataBase `json:"database,omitempty"`
- }
- type DataBase struct {
- Name string `json:"name,omitempty"`
- Host string `json:"host,omitempty"`
- MaxOpenConns int `json:"maxOpenConns,omitempty"`
- MaxIdleConns int `json:"maxIdleConns,omitempty"`
- }
- var Conf *Config
- var DB *sqlx.DB
- func InitConf() {
- if runtime.GOOS == "linux" {
- viper.SetConfigFile("./config-linux.yaml")
- } else {
- viper.SetConfigFile("./config.yaml")
- }
- if err := viper.ReadInConfig(); err != nil {
- panic("Read file error:" + err.Error())
- }
- var config Config
- if err := viper.Unmarshal(&config); err != nil {
- panic("File exchange error:" + err.Error())
- }
- Conf = &config
- }
- func InitDataBase() {
- var err error
- DB, err = sqlx.Connect(Conf.DataBase.Name, Conf.DataBase.Host)
- if err != nil {
- log.Fatalf("connect DB failed, err:%v\n", err)
- return
- }
- DB.SetMaxOpenConns(Conf.DataBase.MaxOpenConns)
- DB.SetMaxIdleConns(Conf.DataBase.MaxOpenConns)
- }
- func init() {
- // 1、初始化配置
- InitConf()
- // 2、初始化数据库
- InitDataBase()
- }
|