Skip to content

Conversation

SkArchon
Copy link

@SkArchon SkArchon commented Jun 4, 2025

This PR adds support for complex map types, enabling users to configure environment variables that map to Go map structures. References #361 (Note: This is the same as this PR #362, The source branch was changed thus the PR was reopened separately)

This is useful when users might have a structure such as

type SubEntry struct {
	Str string `env:"DAT_STR"`
	Num int    `env:"DAT_NUM"`
}
type ComplexConfig struct {
	Bar map[string]Test `envPrefix:"BAR_"`
}

Where the key to access the SubEntry struct can be dynamic.

We need to figure out the key of the map, the algorithm for this essentially reads as follows

Traverse the struct of the map and find out the sub keys it has and use the matching key to trim the suffix of the map environment variable to find the key.

This results in the following restrictions, if a user was to use "A map of structs inside a map of structs", it becomes harder to figure out the key, thus in these cases instead of trimming the suffix, we split the string using the envPrefix of the sub (inner) map of the last recurring (rightmost) substring. Users should be more aware with the naming of the tags (env and envPrefix) and should make them unique, when there are nested maps involved.

Test cases with examples for these cases are available, e.g. :- https://github.com/caarlos0/env/pull/362/files#diff-19e9f6a4b37808acd7acef7094d89f6f9ca8e7c6409ab9b583fa3fac69000ec6R2529

We also ignore env tag options like ,init etc on the map field itself, this is similar to how slices of structs behaves

@SkArchon SkArchon changed the title Milinda/add map serializer feat: support complex map types Jun 4, 2025
@SkArchon SkArchon closed this Jun 4, 2025
@SkArchon SkArchon reopened this Jun 4, 2025
@SkArchon
Copy link
Author

SkArchon commented Jun 4, 2025

@caarlos0 Do let me know your thoughts on this proposal

@SkArchon SkArchon marked this pull request as ready for review June 4, 2025 20:10
@SkArchon SkArchon closed this Aug 19, 2025
@SkArchon SkArchon reopened this Aug 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant