go - 为 TOML 文件和 golang 解析表中的键值对
问题描述
TOML 文件的结构如下:
[database]
host = "localhost"
port = 8086
https = true
username = "root"
password = "root"
db = "test"
[cloud]
deviceType = "2be386e9bbae"
deviceId = "119a705fa3b1"
password = "test"
token = "dqpx5vNLLTR34"
endpoint = "mqtts://mqtt1.endpoint.com"
[gps]
#measurement = "gps"
[gps.msgpack]
topic = "/evt/gps/msgpack"
[gps.json]
topic = "/evt/gps/json"
[imu]
#measurement = "imu"
[imu.1]
tag = "NODE1"
topic = "/evt/imu1/msgpack"
[imu.2]
tag = "NODE2"
topic = "/evt/imu2/msgpack"
我只想在表和表中设置一次measurement
键,而不是在and和 for and中重复设置gps
imu
msgpack
json
1
2
使用注释掉的键以下代码有效
代码
package main
import (
"fmt"
"github.com/BurntSushi/toml"
)
type imu struct {
Topic string
Measurement string
Tag string
}
type gps struct {
// Measurement string
Measurement string
ETopic string `toml:"topic"`
}
type database struct {
Host string
Port int
Https bool
Username string
Password string
Dbname string
}
type cloud struct {
Devicetype string
DeviceId string
Password string
Token string
Endpoint string
}
type tomlConfig struct {
DB database `toml:"database"`
Cloud cloud `toml:"cloud"`
Gps map[string]gps `toml:"gps"`
Imu map[string]imu `toml:"imu"`
}
func main() {
var config tomlConfig
if _, err := toml.DecodeFile("cloud.toml", &config); err != nil {
fmt.Println(err)
return
}
// fmt.Printf("%#v\n", config)
for sensorName, sensor := range config.Imu {
fmt.Printf("Topic: %s %s %s %s\n", sensorName, sensor.Topic, sensor.Tag, sensor.Measurement)
}
for types, gps := range config.Gps {
fmt.Printf("%s\n", types)
fmt.Printf("%s\n", gps.ETopic)
}
}
但是,在取消注释键值对时,我得到以下信息:
toml: type mismatch for main.gps: expected table but found string
(它应该仍然是一个有效的 TOML,因为我将它翻译成 JSON 并检查了结构)
我知道我没有在其中提到struct
我需要为它添加一个字符串。但是,我对结构现在应该是什么样子感到困惑。
解决方案
你说:
我想在 gps 表中设置测量键,并且只在 msgpack 和 json 以及 1 和 2 中设置一次不可变而不是冗余
你不这样做是因为 TOML 格式的创建者说:
因为我们需要一种体面的人类可读格式,它可以明确地映射到哈希表,而 YAML 规范大约有 80 页长,这让我很生气。不,JSON 不算数。你知道为什么。
如果您需要对一个键具有相同的值,例如,measurement
您必须在每个子表中指定您想要的
您正确的 TOML 文件:
[database]
host = "localhost"
port = 8086
https = true
username = "root"
password = "root"
db = "test"
[cloud]
deviceType = "2be386e9bbae"
deviceId = "119a705fa3b1"
password = "test"
token = "dqpx5vNLLTR34"
endpoint = "mqtts://mqtt1.endpoint.com"
[gps]
[gps.msgpack]
topic = "/evt/gps/msgpack"
measurement = "gps"
[gps.json]
topic = "/evt/gps/json"
measurement = "gps"
[imu]
[imu.1]
measurement = "imu"
tag = "NODE1"
topic = "/evt/imu1/msgpack"
[imu.2]
measurement = "imu"
tag = "NODE2"
topic = "/evt/imu2/msgpack"
推荐阅读
- spring-boot - springboot-kafka java 8 时间序列化
- codeception - Codeception:调用未定义的方法 FunctionalTester::expectException
- php - request()->route()->getName() 在嵌套路由组上返回错误值
- mysql - MySQL 3 Table Union 并运行一列的 SUM
- c# - 使用 selenium 以不同的用户登录 chrome
- java - Collections.unmodifiableCollection 和 Collections.unmodifiableSet
- facebook-graph-api - Facebook Graph Api 测试应用安装
- javascript - 为什么它适用于 let 关键字但不适用于 var
- azure-webjobs - Azure WebJob 未加载本地 App.config
- c# - 构建 Xamarin 项目时出错