spf13 / viper

Go configuration with fangs
MIT License
27.25k stars 2.02k forks source link

Problem with HCL configuration #417

Open xocasdashdash opened 7 years ago

xocasdashdash commented 7 years ago

I'm having some issues reading an HCL configuration and I've managed to reproduce the problem with this code

package main

import (
    "bytes"
    "log"

    multierror "github.com/hashicorp/go-multierror"
    "github.com/hashicorp/hcl"
    "github.com/spf13/viper"
)

type Person struct {
    Name string `hcl:"name, omitempty" mapstructure:"name"`
    Age  int    `hcl:"age" mapstructure:"age"`
}
type World struct {
    Humanity []Person `hcl:"person" mapstructure:"person"`
}

// ParseConfig parse the given HCL string into a Config struct.
func ParseConfig(hclText string, into interface{}) error {
    var errors *multierror.Error

    hclParseTree, err := hcl.Parse(hclText)
    if err != nil {
        return err
    }

    if err := hcl.DecodeObject(into, hclParseTree); err != nil {
        return err
    }

    return errors.ErrorOrNil()

}
func main() {
    worldStr := `
        person "person1" {
            name = "foo"
            age = 28
        }
        person "person2" {
            name = "bar"
            age = 31
        }
        person "z" {
            name = "zz"
            age = 99
        }
    `
    var world World
    var world2 World
    viper.SetConfigType("hcl")
    viper.ReadConfig(bytes.NewBuffer([]byte(worldStr)))
    err := viper.Unmarshal(&world)
    if err != nil {
        panic(err)
    }
    err = ParseConfig(worldStr, &world2)
    if err != nil {
        panic(err)
    }
    log.Printf("%+v\n", world)
    log.Printf("%+v\n", world2)
}

Now if you run this you get the following output:

2017/11/19 02:06:47 {Humanity:[{Name: Age:0} {Name: Age:0} {Name: Age:0}]}
2017/11/19 02:06:47 {Humanity:[{Name:foo Age:28} {Name:bar Age:31} {Name:zz Age:99}]}

So the configuration is detecting the 3 values but it is not parsing them correctly.

Am I doing something obviously wrong? I'm pretty sure that if I have something wrong it will be the mapstructure tags.

Any examples on how to deal with this case?

dc0d commented 6 years ago

Have similar issue with hcl; not unmarshalling correctly, using main repo (Go 1.9.2, Ubuntu 16.04) - more info and code here. It works perfectly well with yaml - code is provided for this one too.

xkisu commented 5 years ago

I am also having this issue with the master branch of Viper on the latest version of Go, is there a fix?

jankremlacek commented 5 years ago

same here

sagikazarmark commented 4 months ago

HCL will be dropped from the core after 1.20.0

You can add it back from the encoding repo: https://github.com/go-viper/encoding/