'How to parse each HCL dictionary item by golang?

I have tried to parse HCL config using golang, but it's not working.

type cfg_dict struct {
      name     string       `hcl:",key"`
      type     string       `hcl:"type"`
}

type hcl_config struct {
      config_items    cfg_dict      `hcl:"config"`
}

func main() {
    hcl_example = `config "cfg1" {
           type = "string"
    }`

    hcl_opts := &hcl_config{}

    hcl_tree, err := hcl.Parse(hcl_example)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    if err := hcl.DecodeObject(&hcl_opts, hcl_tree); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    fmt.Println(hcl_opts)
}

When I tried to run this test code after built, it shows empty value.

&{[]}

Is there any problem what I have to fix?



Solution 1:[1]

Fields on the struct you are attempting to unmarshal from HCL need to be exported. To export the fields make the first character in the field name upper case.

type cfg_dict struct {
  Name     string       `hcl:",key"`
  Type     string       `hcl:"type"`
}

type hcl_config struct {
  Config_items    cfg_dict      `hcl:"config"`
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 duhkota