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.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"
go程序
package main
import (
"fmt"
"github.com/BurntSushi/toml"
"time"
)
type Config struct {
Title string
App app
DB mysql `toml:"mysql"`
Redis map[string]redis
Releases releases
Company Company
}
type app struct {
Author string
Org string `toml:"organization"`
Mark string
Release time.Time
}
type mysql struct {
Server string
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 {
Name string
Detail detail
}
type detail struct {
Type string
Addr string
ICP string
}
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)
}
package main
import (
"fmt"
"github.com/BurntSushi/toml"
"log"
"time"
)
type Song struct {
Name string
Dur duration `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
}
if _, err := toml.Decode(blob, &songs); err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", songs)
}
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)
}