How to unmarshall viper config to struct with dash character
Asked Answered
J

1

9

I have this following config file defined as toml file:

[staging]
project-id = "projectId"
cluster-name = "cluster"
zone = "asia-southeast1-a"

Then, I have this struct

type ConfigureOpts struct {
    GCPProjectID       string `json:"project-id"`
    ClusterName        string `json:"cluster-name"`
    Zone               string `json:"zone"`
}

Notice that I have different format of ConfigureOpts fieldname vs the one defined in the config file.

I've tried this code, but failed

test_opts := ConfigureOpts{}
fmt.Printf("viper.staging value %+v\n", viper.GetStringMap("staging"))
viper.UnmarshalKey("staging", &test_opts)
fmt.Printf("testUnmarshall %+v\n", test_opts)

Here is the output

viper.staging value map[zone:asia-southeast1-a project-id:projectId cluster-name:cluster]

testUnmarshall {GCPProjectID: ClusterName: Zone:asia-southeast1-a AuthMode: AuthServiceAccount:}
Jane answered 8/7, 2018 at 2:35 Comment(0)
J
18

I got the answer based on this reference https://github.com/spf13/viper/issues/258

So the solution would be to change any json: tag in ConfigureOpts struct to mapstructure:.

So this will solve the problem.

type ConfigureOpts struct {
    GCPProjectID       string `mapstructure:"project-id"`
    ClusterName        string `mapstructure:"cluster-name"`
    Zone               string `mapstructure:"zone"`
}
Jane answered 8/7, 2018 at 2:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.