本文源码 https://github.com/tothis/go-manager
- Viper Hugo作者开发的配置插件 支持
JSON
TOML
YAML
… - GORM 数据库ORM映射插件
- Gin Web插件
Viper读取TOML
- config.toml
[MySQL]
userName = "root"
password = "123456"
host = "localhost"
port = 3306
dbName = "test"
arg = "charset=utf8mb4&parseTime=True&loc=Local"
- config.go
package main
import (
"fmt"
"github.com/spf13/viper"
"go-manager/model"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
// 读取配置文件config
type Config struct {
MySQL MySQLConfig
}
type MySQLConfig struct {
Host string
Port uint16
DbName string
Arg string
UserName string
Password string
}
// 初始化配置
func initConfig() Config {
// 把配置文件读取到结构体上
var config Config
viper.SetConfigName("config")
viper.AddConfigPath(".")
viper.ReadInConfig()
// 将配置文件绑定到config上
viper.Unmarshal(&config)
fmt.Println("config : ", config)
return config
}
func main() {
fmt.Println(initConfig())
}
GORM配置和使用
...更多请看源码 https://github.com/tothis/go-manager