Home > Enterprise >  Why does this TOML table not parse correctly in Go
Why does this TOML table not parse correctly in Go

Time:10-23

I'm relatively new to Golang. I've been trying to solve this issue for a little while but have not found anything to help me. I am just trying to parse a config.toml file into my application.

My config.toml file is as follows:

[[trees]]
name = "test1"
tags = ["main", "dev"]

[[trees]]
name = "test2"
tags = ["main", "dev", "prod"]

And the code which I am using to read the file:

import (
    "os"
    "fmt"
    toml "github.com/pelletier/go-toml/v2"
)

type Configuration struct {
    Trees    []tree `toml:"trees"`
}
type tree struct {
    name    string `toml:"name"`
    tags    []string `toml:"tags"`
}

func main() Configuration {
    doc, e := os.ReadFile("config.toml")
    if e != nil {
        panic(e)
    }
    var cfg Configuration
    err := toml.Unmarshal(doc, &cfg)
    if err != nil {
        panic(err)
    }
    fmt.Println(cfg.Trees)
    return cfg
}

When I execute the code, I get the following empty array as an output:
> [{ []} { []}]

If anyone can tell me what I am doing wrong here, that would be much appreciated.

CodePudding user response:

You need to capitalize the struct field names:

type Configuration struct {
    Trees    []tree `toml:"trees"`
}
type tree struct {
    Name    string `toml:"name"`
    Tags    []string `toml:"tags"`
}

Here's a related explanation for json.Marshal: the structure fields need to be public (ie, uppercase names).

  • Related