解析下面toml文件的内容,发现有一个坑
# test.toml
ver = "0.0.1"
serverId = 1
[servers]
# You can indent as you please. Tabs or spaces. TOML don't care.
[servers.alpha]
ip = "10.0.0.1"
dc = "eqdc10"
[beta]
ip = "10.0.0.2"
dc = "eqdc12"
[servers.omega]
ip = "10.0.0.3"
dc = "eqdc13"
[clients]
[[clients.clients]]
name = "handshake"
protoName = "bp"
etcdAddrs = ["http://127.0.0.1:1234"]
addrList = ["127.0.0.1:1010"]
balancer = "ra"
[[clients.clients]]
name = "session"
protoName = "br"
etcdAddrs = ["http://127.0.0.1:2000"]
addrList = ["127.0.0.1:1020"]
balancer = "ka"
解决代码
package main
import (
"encoding/json"
"github.com/BurntSushi/toml"
"log"
)
type Conf2 struct {
Servers map[string]Server
Clients *Clients
}
type Server struct {
IP string
DC string
}
type Clients struct {
Clients []Client
}
type Client struct {
Name string `toml:"name"`
ProtoName string `toml:"protoName"`
EtcdAddrs []string `toml:"etcdAddrs"`
AddrList []string `toml:"addrList"`
Balancer string `toml:"balancer"`
}
func main() {
var conf2 Conf2
var err2 error
if _, err2 = toml.DecodeFile("frontend.toml", &conf2); err2 != nil {
panic(err2)
}
m3, err3 := json.Marshal(conf2)
if err3 != nil {
panic(err3)
}
log.Println(string(m3))
}
输出内容
{
"Servers": {
"alpha": {
"IP": "10.0.0.1",
"DC": "eqdc10"
},
"omega": {
"IP": "10.0.0.3",
"DC": "eqdc13"
}
},
"Clients": {
"Clients": [{
"Name": "handshake",
"ProtoName": "bp",
"EtcdAddrs": ["http://127.0.0.1:1234"],
"AddrList": ["127.0.0.1:1010"],
"Balancer": "ra"
}, {
"Name": "session",
"ProtoName": "br",
"EtcdAddrs": ["http://127.0.0.1:2000"],
"AddrList": ["127.0.0.1:1020"],
"Balancer": "ka"
}]
}
}
注意问题
[beta]toml:"xxx"