Mapstrcture map a "path"

Viewed 39

I had a json structure like:

mongoCluster:
  group: some-group
  name: some-name 

And I have made a mapping in go like:

type Config struct {
  MongoCluster  MongoCluster `mapstructure:"mongoCluster"`
}

type MongoCluster struct {
  Group string `mapstructure:"group"`
  Name string `mapstructure:"name"`
}

This structure have changed to:

mongo:
  cluster:
    group: some-group
    name: some-name 

I was thinking that I could avoid creating a Cluster struct and just say to mapstructure that my object now lives in mongo.cluster instead of mongoCluster.

Is this possible?

1 Answers

I didn't have a full context of your intention. But I think yes you can reuse MongoCluster and tweak Config struct like the following bellow.

type Config struct {
   Mongo map[string]MongoCluster `mapstructure:"mongo"`
}

type MongoCluster struct {
  Group string `mapstructure:"group"`
  Name string `mapstructure:"name"`
}

see code example in here

Related