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:}
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"`
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With