Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this TOML table not parse correctly in Go

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading