Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested structs are not influenced by enviroment variables #17

Open
amitelwib opened this issue May 25, 2022 · 1 comment
Open

Nested structs are not influenced by enviroment variables #17

amitelwib opened this issue May 25, 2022 · 1 comment

Comments

@amitelwib
Copy link

type MyConf struct
{
Nested struct{
NestedField string env:"THIS_DOESNT_WORK"
}
}

The nested field does not get set by the environment variable

@pergus
Copy link

pergus commented Jul 6, 2023

Using reflect.VisibleFields instead of looping over NumField should fix the issue with embedded structs.

func getFromEnvVariables(configuration interface{}) {
	typ := reflect.TypeOf(configuration)
	// if a pointer to a struct is passed, get the type of the dereferenced object
	if typ.Kind() == reflect.Ptr {
		typ = typ.Elem()
	}

	for _, field := range reflect.VisibleFields(typ) {
		if !field.Anonymous {
			// check if we've got a field name override for the environment
			tagContent := field.Tag.Get(envTagName)
			value := ""
			if len(tagContent) > 0 {
				value = os.Getenv(tagContent)
			} else {
				value = os.Getenv(field.Name)
			}

			if len(value) > 0 {
				s := reflect.ValueOf(configuration).Elem()
				if s.Kind() == reflect.Struct {
					// exported field
					f := s.FieldByName(field.Name)
					setValue(f, value)
				}
			}
		}
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants