Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unmarshall viper config to struct with dash character

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:}
like image 657
Agung Pratama Avatar asked Jul 08 '18 02:07

Agung Pratama


1 Answers

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"`
}
like image 59
Agung Pratama Avatar answered Oct 30 '22 17:10

Agung Pratama