Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use unmashal with embedded struct #797

Closed
PePoDev opened this issue Nov 19, 2019 · 3 comments
Closed

Use unmashal with embedded struct #797

PePoDev opened this issue Nov 19, 2019 · 3 comments
Labels
kind/question A question related to the project

Comments

@PePoDev
Copy link

PePoDev commented Nov 19, 2019

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 ?

@sagikazarmark sagikazarmark added the kind/question A question related to the project label Nov 19, 2019
@sagikazarmark
Copy link
Collaborator

Viper actually uses mapstructure.

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

@PePoDev
Copy link
Author

PePoDev commented Nov 19, 2019

@sagikazarmark It work like a charm. Thanks you.

@ayanmw
Copy link

ayanmw commented Jul 1, 2024

Why should I add a tag ? Can Viper set this feature as default ?
Default to support emebeded field is a good idea!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind/question A question related to the project
Projects
None yet
Development

No branches or pull requests

3 participants