Skip to content

feat: support custom types in Env and EnvOrDefault - #227

Closed
obalunenko wants to merge 2 commits into
masterfrom
feat/custom-types
Closed

obalunenko wants to merge 2 commits into
masterfrom
feat/custom-types

Conversation

@obalunenko

@obalunenko obalunenko commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

Description

Env and EnvOrDefault took only the built-in Parsable types, so a custom type needed a wrapper around Env[string]. They now take any T, and custom types, slices of them and named slice types use the same two functions:

func (Level) ParseEnv(raw string) (Level, error) { ... }

lvl, err := getenv.Env[Level]("LEVEL")
lvls, err := getenv.Env[[]Level]("LEVELS", option.WithSeparator("|"))
lvl := getenv.EnvOrDefault("LEVEL", LevelInfo)
slvls, err := getenv.Env[[]slog.Level]("LOG_LEVELS") // encoding.TextUnmarshaler
port := getenv.EnvOrDefault("PORT", Port(80))          // type Port uint16

A custom type T is parsed with the first one that fits:

Example
ParseEnv(string) (T, error) method of T, the new EnvParser[T] type Level int
UnmarshalText of *T, or of T if it is a pointer type slog.Level, *regexp.Regexp
the underlying type of T, if it is a string, bool or numeric type type Port uint16

Slices are split by the separator as before, and elements of named slice types of built-in types are parsed as those types: type Timeouts []time.Duration parses 1s,2m, and type Stamps []time.Time uses option.WithTimeLayout. Errors are the same as for the built-in types: they wrap ErrNotSet or ErrInvalidValue and the error of the parser.

Implementation: the built-in type switch is unchanged, except that it returns an internal errNotBuiltin instead of panicking for other types. Only then do custom types go through reflect (internal/custom.go).

Github Issue

None.

Testing

  • make test (go test -race ./...) passes on Go 1.27.4, and go test ./... passes on Go 1.26.2, the minimum in go.mod. Coverage stays at 100% in all packages.
  • New tests in internal/custom_test.go cover each way of parsing, named slices, pointer types, the precedence order and unsupported types. FuzzParse gained custom types and ran for 20s without failures.
  • getenv_test.go covers custom types and the panic for an unsupported type through the public API, including when the variable is not set.
  • The new whole-file examples Example_customType and ExampleEnvParser pass. Their README copies run as programs with the same output.
  • Both golangci configs report 0 issues.
  • Benchmarks, benchstat, master vs this branch: BenchmarkParse shows no change (p=0.85), 48 B and 2 allocs/op. BenchmarkEnvOrDefault is about 3 ns (~4%) slower in interleaved runs (84.4 → 87.7 ns, p=0.000), with 80 B and 3 allocs/op unchanged.

Possible failures/side-effects

  • The supported types are no longer checked at compile time. Env[chan int] now compiles. Instead, Env and EnvOrDefault panic with an error that wraps the new ErrUnsupportedType. They do it before the lookup, so the panic happens on the first call even when the variable is not set. A panic is used instead of an error because EnvOrDefault would swallow an error and quietly return the default.
  • Mistakes in ParseEnv are found only at run time. With a pointer receiver or another signature, the method is not used, and the type falls through to the next rule or becomes unsupported. The EnvParser doc shows the compile-time check: var _ getenv.EnvParser[Level] = Level(0).
  • type Timeout time.Duration is parsed as int64 nanoseconds, not as a duration. Its underlying type is int64, and reflect cannot tell it from type Count int64. The package doc says so and gives two fixes: implement EnvParser, which ExampleEnvParser shows, or declare an alias, type Timeout = time.Duration.
  • Not breaking for callers. any accepts every Parsable type, existing calls behave the same, and Parsable stays for caller-side generic helpers. Code that did not compile before now compiles, so release this as a minor version.

Other notes

  • README: I carried the package doc and the CustomType example over from goreadme output by hand and added its Output block myself, because goreadme leaves it out for whole-file examples. I did not touch the existing drift between README and goreadme in the url.URL examples.
  • The package doc now says "generic" instead of "type-safe", because type support is checked at run time.

🤖 Generated with Claude Code

Env and EnvOrDefault took only the built-in Parsable types, so a custom
type needed a wrapper around Env[string]. They now take any T and parse
a custom type, a slice of it or a named slice type such as
type Tags []string, with the same options and errors as the built-in
types. A custom type T is parsed with the first one that fits:

- the ParseEnv(string) (T, error) method of T, see the new EnvParser;
- the UnmarshalText method of *T, or of T if it is a pointer type, so
  slog.Level and other encoding.TextUnmarshaler types work as is;
- the underlying type of T, if it is a string, bool or numeric type,
  as for type Port uint16.

Whether T is supported is now checked at run time: Env and EnvOrDefault
panic with an error wrapping the new ErrUnsupportedType for any other
type, even when the variable is not set, so the bug shows up on the
first call. EnvParser documents how to check a type at compile time.

The built-in types keep their type switch: it now returns errNotBuiltin
instead of panicking for other types, and only then the custom types go
through reflect. BenchmarkParse keeps 48 B and 2 allocs/op.

Parsable stays as the constraint of the built-in types for caller-side
generic helpers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (8a2e8ae) to head (0aa9833).

Additional details and impacted files
@@            Coverage Diff            @@
##            master      #227   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            3         4    +1     
  Lines           99       189   +90     
=========================================
+ Hits            99       189   +90     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

type Timeout time.Duration has the underlying type int64 and none of
the methods of time.Duration, and reflect cannot tell it from
type Count int64, so Env parses it as int64 nanoseconds: "2s" is an
invalid value. Say why in the package doc and point to the two ways
out: implement EnvParser, or declare an alias if the type needs no
methods of its own.

Add ExampleEnvParser with such a Timeout, which also shows the
compile-time check of EnvParser, and tests that pin both behaviors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sonarqubecloud

Copy link
Copy Markdown

@obalunenko

Copy link
Copy Markdown
Owner Author

Closing without merging. Relaxing Env[T Parsable] to Env[T any] gives up compile-time type checks, and it cannot be undone in v1. Parsing through reflect also lets some mistakes return wrong values without an error, for example type Timeout time.Duration reads 30 as 30ns. Nobody has asked for this feature, and today a custom type is one conversion or one UnmarshalText call away. If it is requested, an additive EnvText/EnvFunc can come in a minor release.

@obalunenko obalunenko closed this Nov 15, 2026
@obalunenko
obalunenko deleted the feat/custom-types branch November 15, 2026 20:24
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