当前位置: 首页 > 工具软件 > ka-map > 使用案例 >

GoLang toml踩的坑,map 和 slice

空慈
2023-12-01

解析下面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"
		}]
	}
}

注意问题

  • 两个[[和一个[的区别,需要多一层,并且是slice,其他的是map映射
  • 如果只有一个子集,必须名字前面带上父级的东西,否则会无法读取,比如 [beta]
  • 可以使用 修饰词toml:"xxx" 来强制指定
 类似资料: