Skip to content

dotenv: skip keys that the callback blanks, like env.Provider - #456

Merged
knadh merged 1 commit into
knadh:masterfrom
Shaisolaris:dotenv-skip-blank-key
Oct 13, 2026
Merged

knadh merged 1 commit into
knadh:masterfrom
Shaisolaris:dotenv-skip-blank-key

Conversation

@Shaisolaris

Copy link
Copy Markdown
Contributor

dotenv.ParserEnv and ParserEnvWithValue are documented as making the parser "behave like the env.Provider". env.Provider ignores a variable when its callback returns an empty key ("If the returned variable name is an empty string (""), it is ignored altogether"). The dotenv parser stored the value under the "" key instead:

p := dotenv.ParserEnv("APP_", ".", func(k string) string {
	if k == "APP_SECRET" {
		return ""
	}
	return strings.ToLower(strings.TrimPrefix(k, "APP_"))
})
m, _ := p.Unmarshal([]byte("APP_HOST=localhost\nAPP_SECRET=hunter2\n"))
// map[:hunter2 host:localhost]
out, _ := p.Marshal(m)
// APP_HOST="localhost"
// APP_SECRET="hunter2"

Because reverseCB also recorded "" -> APP_SECRET, Marshal wrote the dropped variable back out under its original name.

This change skips the entry when the callback returns an empty key, matching env.Provider.

Testing: TestUnmarshalSkipsBlankedKeys in parsers/dotenv checks both Unmarshal and Marshal for the case above. It fails on master and passes with the change. go test . and go vet . in parsers/dotenv pass. I did not run the tests of the other modules. Go 1.25 only.

ParserEnv and ParserEnvWithValue are documented to behave like
env.Provider, which drops a variable when its callback returns an empty
key. The dotenv parser stored such a variable under the "" key instead,
and Marshal then wrote it back out under its original name.
@knadh
knadh merged commit 2ebf824 into knadh:master Oct 13, 2026
4 checks passed
@knadh

knadh commented Oct 13, 2026

Copy link
Copy Markdown
Owner

Thanks. Released parsers/dotenv/v1.1.3

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

Successfully merging this pull request may close these issues.

2 participants