Viper: Use unmashal with embedded struct

Created on 19 Nov 2019  路  2Comments  路  Source: spf13/viper

I try to use unmarshal to struct and It's work great.

And now, I want to unmarshal yaml file to embedded struct. See example.

main.go

type Base struct {
    Foo string
}

type SomeStruct struct {
    Base
}

func ReturnToStruct(fileName string, dir string) SomeStruct {
    viper.SetConfigFile(fileName)
    viper.AddConfigPath(dir)
    if err := viper.ReadInConfig(); err != nil {
        xlog.Fatalf("fatal error config file: %s \n", err)
    }
    someStruct := SomeStruct{}
    if err := viper.Unmarshal(&someStruct); err != nil {
        xlog.Fatalf("%v", err)
    }

return someStruct
}

test.yml

Foo: asd

When I use

    xlog.Infof("%s", someStruct.Foo)

It will return empty string.

Can I use viper with embedded struct ?

kinquestion

Most helpful comment

Viper actually uses mapstructure.

Try mapstructure:",squash" struct tag on the embedded struct.

All 2 comments

Viper actually uses mapstructure.

Try mapstructure:",squash" struct tag on the embedded struct.

@sagikazarmark It work like a charm. Thanks you.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Giri4joyz picture Giri4joyz  路  3Comments

TWinsnes picture TWinsnes  路  3Comments

jeffwillette picture jeffwillette  路  5Comments

lllama picture lllama  路  3Comments

xh3b4sd picture xh3b4sd  路  6Comments