https://github.com/spf13/viper
在项目中创建一个config
文件夹,新建一个application.yml
文件
1 2 3 4 5 6 7 8 9 10
| server: port: 8099 datasource: driverName: mysql host: 127.0.0.1 port: 3306 database: gin_vue_bs username: root password: 123456 charset: utf8
|
初始化配置文件,要在初始化数据库之前调用
1 2 3 4 5 6 7 8 9 10 11
| //InitConfig 初始化配置文件. func InitConfig() { workDir, _ := os.Getwd() //工程项目目录 viper.SetConfigName("application") //配置文件名 viper.SetConfigType("yml") //配置文件类型 viper.AddConfigPath(workDir + "/config") //配置文件目录 err := viper.ReadInConfig() if err != nil { panic(err) } }
|
调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| //InitDB . func InitDB() *gorm.DB { driverName := viper.GetString("datasource.driverName") host := viper.GetString("datasource.host") port := viper.GetString("datasource.port") database := viper.GetString("datasource.database") username := viper.GetString("datasource.username") passwoed := viper.GetString("datasource.password") charset := "utf8" args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true", username, passwoed, host, port, database, charset)
db, err := gorm.Open(driverName, args) if err != nil { panic("failed to connect database,err" + err.Error()) }
//创建数据表 db.AutoMigrate(&model.User{})
DB = db return db }
|