golang viper & hcl config file issues

720 views Asked by At

I've written a simple go program using viper to read in a config file.

package main 
import (
    "fmt"
    "log"

    "github.com/spf13/viper"
)     

func main() {
    viper.SetConfigType("hcl")

    // # first used file
    viper.AddConfigPath(".")
    viper.SetConfigName("example.hcl")

    err := viper.ReadInConfig()
    if err != nil {
            log.Fatal(err)
    }

    fmt.Println("host.address =", viper.GetString("host.address"))
    fmt.Println("host.port =", viper.GetString("host.port"))
    viper.Reset()
}

with a ./example.hcl of

"host" = {
 "address" = "localhost"
 "port" = "5799" 
}   

The output of the program is

host.address = 
host.port =

If I switch the name of the config file to .yaml (and adjust the code accordingly) and use

{
"host": {
    "address": "localhost",
    "port": 5799
}
}

the code works. Anyone have a suggestion as to what I'm doing wrong? Or does viper not work with embedded hcl fields?

1

There are 1 answers

0
dev.meghraj On

Viper & HCL don't integrate and play well, like the example you aleady have

You can use koanf as alternative to overcome above issue

see this example.

package main
import (
  "fmt"
  "github.com/knadh/koanf"
  "github.com/knadh/koanf/parsers/hcl"
  "github.com/knadh/koanf/providers/file"
)

var Conf = koanf.New(".")

func main() {
   Conf.Load(file.Provider("/etc/app/config.hcl"),hcl.Parser(true))

   fmt.Println("host.address =", Conf.Get("host.address"))
   fmt.Println("host.port =", Conf.Get("host.port"))
  
}