envconfig icon indicating copy to clipboard operation
envconfig copied to clipboard

Possible to populate fields discretely for a slice of structs?

Open jlucktay opened this issue 4 years ago • 4 comments

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?

jlucktay avatar Mar 04 '20 10:03 jlucktay

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

MaerF0x0 avatar Jun 11 '20 01:06 MaerF0x0

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

colega avatar Jun 11 '20 16:06 colega

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

itayd avatar Feb 09 '21 05:02 itayd

any progress ?

mohammadne avatar Sep 22 '21 15:09 mohammadne