gorm 是 Golang 写的一个 ORM 包, toml 在本文中指的是 Golang 中的一个 TOML 解析器包, 本文介绍下两者的结合使用。
新建一个 config.toml
1 | mkdir tomlTest && cd tomlTest |
1 2 3 4 5 6 7 | dbType="mysql" dbHost="tcp(192.168.123.236:3306)" dbUserName="root1" dbUserPassword="mysql" dbName="employee" dbCharset="utf8" teststr="teststrteststr" |
上面的文件是 toml 格式的配置文件。
创建测试文件
创建一个测试文件 main.go, 内容如下:
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | /* * @Author: suifengtec * @Date: 2018-09-21 12:42:26 * @Last Modified by: suifengtec * @Last Modified time: 2018-09-21 12:57:35 **/ /* go build -o a.exe tomlT.go */ package main import ( "fmt" "github.com/BurntSushi/toml" //"github.com/gorilla/mux" //"github.com/jinzhu/gorm" "log" ) type App struct { Router *mux.Router DB *gorm.DB } // config.toml 的数据结构 type Config1 struct { DbType string DbHost string DbUserName string DbUserPassword string DbName string DbCharset string } // 读取配置文件 // 如果想省事儿,直接定义为和下面的 DBConfig 一致的结构即可,可惜它的定义,在语义上不怎么合适 // 所以有了这个 func (c *Config1) GetConfig1() { if _, err := toml.DecodeFile("config.toml", &c); err != nil { log.Fatal(err) } } type DBConfig struct { Dialect string Host string Username string Password string Name string Charset string } type Config struct { DB *DBConfig } // 使用在 gorm 中的特定数据结构 func GetConfig() *Config { var cfg1 = Config1{} cfg1.GetConfig1() return &Config{ DB: &DBConfig{ Dialect: cfg1.DbType, Host: cfg1.DbHost, Username: cfg1.DbUserName, Password: cfg1.DbUserPassword, Name: cfg1.DbName, Charset: cfg1.DbCharset, }, } } func main() { var dbCfg DBConfig = *((*GetConfig()).DB) //仅用于测试打印,这个数据结构实际上适用于 gorm /* 示例 dbURI := fmt.Sprintf("%s:%s@%s/%s?charset=%s&parseTime=True", config.DB.Username, config.DB.Password, config.DB.Host, config.DB.Name, config.DB.Charset) db, err := gorm.Open(config.DB.Dialect, dbURI) if err != nil { log.Fatal("未能连接到数据库") } */ fmt.Printf("%#v", dbCfg) } |
读取配置文件 config.toml , 并把它解析为方便 gorm 识别的格式, 然后就可以让 gorm 和 mux 一起,做一个简单的提供 REST API 功能的小程序了。