Golang toml完全解析示例

配置管理 基于TOML v0.4.0的配置管理

Toml语法可查看Toml官方文档或中文文档。
GO客户端:https://github.com/BurntSushi/toml,这里是官方使用示例。
安装Go-toml
# 安装toml-go客户端 go get github.com/BurntSushi/toml# 验证toml语法 go get github.com/BurntSushi/toml/cmd/tomlv tomlv some-toml-file.toml

示例1 example.toml
# 全局信息 title = "TOML示例"# 应用信息 [app] author = "史布斯" organization = "Mafool" mark = "第一行\n第二行."# 换行 release = 2020-05-27T07:32:00Z# 时间# 数据库配置 [mysql] server = "192.168.1.1" ports = [ 8001, 8001, 8002 ]# 数组 connection_max = 5000 enabled = true# Redis主从# 字典对象 [redis] [redis.master] host = "10.0.0.1" port = 6379 [redis.slave] host = "10.0.0.1" port = 6380# 二维数组 [releases] release = ["dev", "test", "stage", "prod"] tags = [["dev", "stage", "prod"],[2.2, 2.1]]# 公司信息#对象嵌套 [company] name = "xx科技" [company.detail] type = "game" addr = "北京朝阳" icp = "030173"

package mainimport ( "fmt" "github.com/BurntSushi/toml" "time" )type Config struct { Titlestring Appapp DBmysql `toml:"mysql"` Redismap[string]redis Releases releases CompanyCompany }type app struct { Authorstring Orgstring `toml:"organization"` Markstring Release time.Time }type mysql struct { Serverstring Ports[]int ConnMax int `toml:"connection_max"` Enabled bool }type redis struct { Host string Port int }type releases struct { Release []string Tags[][]interface{} }type Company struct { Namestring Detail detail }type detail struct { Type string Addr string ICPstring }func main() { var config Config if _, err := toml.DecodeFile("example.toml", &config); err != nil { panic(err) } fmt.Printf("全局信息: %+v\n\n", config.Title) fmt.Printf("App信息:%+v\n\n", config.App) fmt.Printf("Mysql配置:%+v\n\n", config.DB) fmt.Printf("版本信息:%+v\n\n", config.Releases) fmt.Printf("Redis主从:%+v\n\n", config.Redis) fmt.Printf("企业信息:%+v\n\n", config.Company) }

示例2
  • 自定义字段类型(重新实现encoding.Unmarshal接口)反序列化方法
  • 实现toml对象数组格式
package mainimport ( "fmt" "github.com/BurntSushi/toml" "log" "time" )type Song struct { Name string Durduration `toml:"duration"` }type duration struct { time.Duration }func (d *duration) UnmarshalText(text []byte) error { var err error d.Duration, err = time.ParseDuration(string(text)) return err }func main() { blob := ` [[song]] name = "天路" duration = "4m49s"[[song]] name = "忘情水" duration = "8m03s" ` var songs struct { Song []Song } // 使用 toml.Decode if _, err := toml.Decode(blob, &songs); err != nil { log.Fatal(err) } fmt.Printf("%+v\n", songs) }

示例3
【Golang toml完全解析示例】对象数组
type redis struct { Host string Port int Auth string }type sentinel struct { Member []redis }func main() { var rds = ` [redis] host = "127.0.0.1" port = 26379[sentinel] [[sentinel.member]] host = "127.0.0.1" port = 26379 #auth = "123456" [[sentinel.member]] host = "127.0.0.1" port = 26380 #auth = "123456"[cluster] [[cluster.member]] host = "127.0.0.1" port = 11111 [[cluster.member]] host = "127.0.0.1" port = 22222 ` var config struct{ Redis redis Sentinel sentinel } if _, err := toml.Decode(rds, &config); err != nil { panic(err) } fmt.Println(config) }

    推荐阅读