Repository navigation
feat: support custom types in Env and EnvOrDefault - #227
obalunenko wants to merge 2 commits into
Conversation
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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
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>
|
|
Closing without merging. Relaxing |



Description
EnvandEnvOrDefaulttook only the built-inParsabletypes, so a custom type needed a wrapper aroundEnv[string]. They now take anyT, and custom types, slices of them and named slice types use the same two functions:A custom type
Tis parsed with the first one that fits:ParseEnv(string) (T, error)method ofT, the newEnvParser[T]type Level intUnmarshalTextof*T, or ofTif it is a pointer typeslog.Level,*regexp.RegexpT, if it is a string, bool or numeric typetype Port uint16Slices 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.Durationparses1s,2m, andtype Stamps []time.Timeusesoption.WithTimeLayout. Errors are the same as for the built-in types: they wrapErrNotSetorErrInvalidValueand the error of the parser.Implementation: the built-in type switch is unchanged, except that it returns an internal
errNotBuiltininstead of panicking for other types. Only then do custom types go throughreflect(internal/custom.go).Github Issue
None.
Testing
make test(go test -race ./...) passes on Go 1.27.4, andgo test ./...passes on Go 1.26.2, the minimum ingo.mod. Coverage stays at 100% in all packages.internal/custom_test.gocover each way of parsing, named slices, pointer types, the precedence order and unsupported types.FuzzParsegained custom types and ran for 20s without failures.getenv_test.gocovers custom types and the panic for an unsupported type through the public API, including when the variable is not set.Example_customTypeandExampleEnvParserpass. Their README copies run as programs with the same output.benchstat, master vs this branch:BenchmarkParseshows no change (p=0.85), 48 B and 2 allocs/op.BenchmarkEnvOrDefaultis 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
Env[chan int]now compiles. Instead,EnvandEnvOrDefaultpanic with an error that wraps the newErrUnsupportedType. 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 becauseEnvOrDefaultwould swallow an error and quietly return the default.ParseEnvare 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. TheEnvParserdoc shows the compile-time check:var _ getenv.EnvParser[Level] = Level(0).type Timeout time.Durationis parsed as int64 nanoseconds, not as a duration. Its underlying type isint64, and reflect cannot tell it fromtype Count int64. The package doc says so and gives two fixes: implementEnvParser, whichExampleEnvParsershows, or declare an alias,type Timeout = time.Duration.anyaccepts everyParsabletype, existing calls behave the same, andParsablestays for caller-side generic helpers. Code that did not compile before now compiles, so release this as a minor version.Other notes
CustomTypeexample over fromgoreadmeoutput by hand and added itsOutputblock myself, becausegoreadmeleaves it out for whole-file examples. I did not touch the existing drift between README andgoreadmein theurl.URLexamples.🤖 Generated with Claude Code