使用Go读取TOML文件时出现空结果。

huangapple go评论62阅读模式
英文:

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结构,其中包含多个类型,例如files3等。因此,定义等效的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"`
}

https://go.dev/play/p/lfFKVL4_1zx

huangapple
  • 本文由 发表于 2022年6月15日 00:34:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/72620500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定