Viper: struct yaml tags are not respected

Created on 11 Sep 2017  路  5Comments  路  Source: spf13/viper

gopkg.in will treat yaml tags properly, but something is happening in viper that ignores them. Given the following main and config file, it will fail to read in the proper yaml keys...

main.go

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/pkg/errors"
    "github.com/spf13/viper"
)

type Config struct {
    Foo string `yaml:"foo-thing"`
    Bar string `yaml:"bar-thing"`
}

var Conf Config

func main() {
    initConfig()
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
    viper.SetConfigName(".conf") // name of config file (without extension)
    // add working dir path above the home dir for the config file
    path, _ := os.Getwd()
    viper.AddConfigPath(path)
    viper.AutomaticEnv() // read in environment variables that match

    // If a config file is found, read it in.
    err := viper.ReadInConfig()
    switch {
    case err != nil:
        log.Println(err)
    default:
        fmt.Println("Using config file:", viper.ConfigFileUsed())
    }

    err = viper.Unmarshal(&Conf)
    if err != nil {
        log.Println(errors.Wrap(err, "unmarshal config file"))
    }

    log.Println(Conf)
}

.conf

---
foo-thing: why
bar-thing: nowork?

Most helpful comment

Incase you are still stuck with this:

viper uses mapstructure package for unmarshalling config maps to structs. It doesn't support yaml tags used by the yaml package.

So, changing all your yaml: tags in your struct to mapstructure: should fix this.

All 5 comments

Incase you are still stuck with this:

viper uses mapstructure package for unmarshalling config maps to structs. It doesn't support yaml tags used by the yaml package.

So, changing all your yaml: tags in your struct to mapstructure: should fix this.

Oh cool thanks I will try it in the future

This worked for me!

Why not dynamicly according to config.SetConfigType("yaml")?

worked for me too!!!!

Was this page helpful?
0 / 5 - 0 ratings