Home > Enterprise >  Empty result when reading TOML file with Go
Empty result when reading TOML file with Go

Time:06-15

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)
}

CodePudding user response:

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

  •  Tags:  
  • go
  • Related