英文:
Empty result when reading TOML file with Go
问题
我正在尝试使用Go读取一个toml文件。我想要有不仅仅是filesystem.file的不同文件系统,例如filesystem.s3,它们有不同的路径定义。但是它只返回一个空的结构体{map[file:{map[]}]}。我漏掉了什么?
我正在使用这个库来读取toml文件:https://github.com/BurntSushi/toml
toml文件:
[filesystem.file]
[filesystem.file.test]
folder = "tmp/testdata"
[filesystem.file.test2]
folder = "tmp/testdata2"
[filesystem.s3]
[filesystem.s3.test]
folder = "s3folder/testdata"
我的Go代码:
package main
type File struct {
Folder string `toml:"folder"`
}
type FileSystem struct {
File map[string]File `toml:"file"`
}
type Config struct {
FileSystem map[string]FileSystem `toml:"filesystem"`
}
func main() {
var conf Config
_, err := toml.DecodeFile("test.toml", &conf)
if err != nil {
log.Fatalln("Error on loading config: ", err)
}
log.Printf("config: %v", conf)
}
英文:
I'm trying to read a toml file with Go. I want to have different filesystems not only filesystem.file but for example also filesystem.s3, which have different paths defined. But it only returns an empty struct {map[file:{map[]}]}. What am I missing?
I'm using this library for reading the toml file: https://github.com/BurntSushi/toml
toml file:
[filesystem.file]
[filesystem.file.test]
folder = "tmp/testdata"
[filesystem.file.test2]
folder = "tmp/testdata2"
[filesystem.s3]
[filesystem.s3.test]
folder = "s3folder/testdata"
My go code:
package main
type File struct {
Folder string `toml:"folder"`
}
type FileSystem struct {
File map[string]File `toml:"file"`
}
type Config struct {
FileSystem map[string]FileSystem `toml:"filesystem"`
}
func main() {
var conf Config
_, err := toml.DecodeFile("test.toml", &conf)
if err != nil {
log.Fatalln("Error on loading config: ", err)
}
log.Printf("config: %v", conf)
}
答案1
得分: 2
输入的TOML定义对应于顶层的filesystem结构,其中包含多个类型,例如file、s3等。因此,定义等效的Go结构以解码这些结构的正确方式是:
type File struct {
Folder string `toml:"folder"`
}
type FileSystem struct {
File map[string]File `toml:"file"`
S3 map[string]File `toml:"s3"`
}
type Config struct {
FileSystem FileSystem `toml:"filesystem"`
}
你可以在以下链接中查看示例代码:https://go.dev/play/p/lfFKVL4_1zx
英文:
The TOML defined in the input corresponds to a top level filesystem struct, containing multiple types i.e. file, s3 etc. So the right way to define the equivalent Go structs to decode those would be to do
type File struct {
Folder string `toml:"folder"`
}
type FileSystem struct {
File map[string]File `toml:"file"`
S3 map[string]File `toml:"s3"`
}
type Config struct {
FileSystem FileSystem `toml:"filesystem"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论