kelseyhightower / envconfig

Golang library for managing configuration data from environment variables
MIT License
5.01k stars 377 forks source link

Possible to populate fields discretely for a slice of structs? #169

Open jlucktay opened 4 years ago

jlucktay commented 4 years ago

Hi there, and thanks very much for envconfig, we love it! One thing I'm not clear on whether or not is possible, and it has come up as a bit of a blocker for us, is say we have a slice of structs as one field in our base config struct, can we set different values on the fields of different structs in the slice? For example:

type FirstLevelConfig struct {
  FieldOne []SecondLevelConfig
}

type SecondLevelConfig struct {
  FieldTwo string
}

Can we put something like PREFIX_FIELDONE_0_FIELDTWO="string on first struct" and PREFIX_FIELDONE_1_FIELDTWO="string on second struct" into the environment, call .Process("PREFIX", &FirstLevelConfig) and end up with two structs?

MaerF0x0 commented 4 years ago

Could you implement Setter and do it yourself?

something like:

type cfg struct {
   Stuff StuffSlice
}

type StuffSlice []SecondLevelConfig

func (ss *StuffSlice) Set(data string) error {
    return json.Unmarshal([]byte(data), &ss) 
}

EDIT: This doesnt fit your desired env var format, but does allow slice of structs

colega commented 4 years ago

That doesn't work well with big structs and is not directly compatible with multiple env vars.

I solved this here: https://github.com/kelseyhightower/envconfig/pull/170 and merged it into my fork: https://github.com/colega/envconfig/pull/1

itayd commented 3 years ago

hi, would love to see #170 merged - is there any progress planned on that?

mohammadne commented 2 years ago

any progress ?