问题描述
作为标题,我想知道如何使用golang中的toml文件。在此之前,我将展示我的toml示例。是不是正确?
[datatitle]
enable = true
userids = [
12345,67890
]
[datatitle.12345]
prop1 = 30
prop2 = 10
[datatitle.67890]
prop1 = 30
prop2 = 10
然后,我想将这些数据设置为类型的结构。
结果我想访问下面的子元素。
datatitle [12345]。prop1
datatitle [67890]。prop2
$ p
首先获取BurntSushi的toml解析器:
go get github.com/BurntSushi/toml
BurntSushi解析toml并将其映射到结构,这就是你想要的。
然后执行下面的例子并从中学习:
package main
import(
github.com/BurntSushi/toml
log
)
var varldData =`title =config
[feature1]
enable = true
userids = [
12345,67890
]
[feature2]
enable = false`
type feature1 struct {
启用bool
Userids [] string
}
type feature2 struct {
启用bool
}
类型tomlConfig结构{
标题字符串
F1 feature1`toml:feature1 `
F2 feature2`toml:feature2`
}
func main(){
var conf tomlConfig
if _,err:= toml解码(tomlData,& conf); err!= nil {
log.Fatal(err)
}
log.Printf(title:%s,conf.Title)
log.Printf(Feature 1 :%#v,conf.F1)
log.Printf(Feature 2:%#v,conf.F2)
}
注意 tomlData
以及它如何映射到 tomlConfig
struct。
请参阅
As title, I want to know how to use toml files from golang.
Before that, I show my toml examples. Is it right?
[datatitle]
enable = true
userids = [
"12345", "67890"
]
[datatitle.12345]
prop1 = 30
prop2 = 10
[datatitle.67890]
prop1 = 30
prop2 = 10
And then, I want to set these data as type of struct.
As a result I want to access child element as below.
datatitle["12345"].prop1
datatitle["67890"].prop2
Thanks in advance!
First get BurntSushi's toml parser:
go get github.com/BurntSushi/toml
BurntSushi parses toml and maps it to structs, which is what you want.
Then execute the following example and learn from it:
package main
import (
"github.com/BurntSushi/toml"
"log"
)
var tomlData = `title = "config"
[feature1]
enable = true
userids = [
"12345", "67890"
]
[feature2]
enable = false`
type feature1 struct {
Enable bool
Userids []string
}
type feature2 struct {
Enable bool
}
type tomlConfig struct {
Title string
F1 feature1 `toml:"feature1"`
F2 feature2 `toml:"feature2"`
}
func main() {
var conf tomlConfig
if _, err := toml.Decode(tomlData, &conf); err != nil {
log.Fatal(err)
}
log.Printf("title: %s", conf.Title)
log.Printf("Feature 1: %#v", conf.F1)
log.Printf("Feature 2: %#v", conf.F2)
}
Notice the tomlData
and how it maps to the tomlConfig
struct.
See more examples at https://github.com/BurntSushi/toml
这篇关于(转)如何使用toml文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!