From c712eca76f471172144eac2ec7974a6c466f97da Mon Sep 17 00:00:00 2001 From: Oleg Balunenko Date: Mon, 16 Nov 2026 00:26:19 +0400 Subject: [PATCH 1/7] fix: put "invalid value" before the cause in parse errors Parse wrapped the parser error first and ErrInvalidValue last, so the message read backwards: strconv.ParseInt: parsing "x": invalid syntax: invalid value Swap the operands so the message goes from the general error to its cause, as Go error chains usually do: invalid value: strconv.ParseInt: parsing "x": invalid syntax Only the text changes: errors.Is still matches both ErrInvalidValue and the cause. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- getenv_example_test.go | 2 +- internal/parse.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7597a7a6..d2abd34b 100644 --- a/README.md +++ b/README.md @@ -199,7 +199,7 @@ Output: ``` [string]: golly; err: [int]: 123; err: -[int]: 0; err: failed to parse environment variable[GH_GETENV_TEST]: strconv.ParseInt: parsing "123s4": invalid syntax: invalid value +[int]: 0; err: failed to parse environment variable[GH_GETENV_TEST]: invalid value: strconv.ParseInt: parsing "123s4": invalid syntax [time.Time]: 2022-01-20 00:00:00 +0000 UTC; err: [[]float64]: [26.89 0.67]; err: [time.Duration]: 2h35m0s; err: diff --git a/getenv_example_test.go b/getenv_example_test.go index 54d0b30a..9d0b1330 100644 --- a/getenv_example_test.go +++ b/getenv_example_test.go @@ -241,7 +241,7 @@ func ExampleEnv() { // Output: // [string]: golly; err: // [int]: 123; err: - // [int]: 0; err: failed to parse environment variable[GH_GETENV_TEST]: strconv.ParseInt: parsing "123s4": invalid syntax: invalid value + // [int]: 0; err: failed to parse environment variable[GH_GETENV_TEST]: invalid value: strconv.ParseInt: parsing "123s4": invalid syntax // [time.Time]: 2022-01-20 00:00:00 +0000 UTC; err: // [[]float64]: [26.89 0.67]; err: // [time.Duration]: 2h35m0s; err: diff --git a/internal/parse.go b/internal/parse.go index eaf5ed0e..703f4f8d 100644 --- a/internal/parse.go +++ b/internal/parse.go @@ -23,7 +23,7 @@ func Parse[T EnvParsable](raw string, p Parameters) (T, error) { if err := parseValue(&res, raw, p); err != nil { var zero T - return zero, fmt.Errorf("%w: %w", err, ErrInvalidValue) + return zero, fmt.Errorf("%w: %w", ErrInvalidValue, err) } return res, nil From 9744de6c9fb5815e321a6f71b3c5073095414ed1 Mon Sep 17 00:00:00 2001 From: Oleg Balunenko Date: Mon, 16 Nov 2026 00:26:19 +0400 Subject: [PATCH 2/7] docs(option): describe Option without the removed EnvParser The EnvParser interface was removed with the parser hierarchy in #223, but the Option comment still called it "a contract for EnvParser parameters options". Describe what an option does instead. Co-Authored-By: Claude Opus 5.5 --- option/option.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/option/option.go b/option/option.go index eab81ee7..ae8dde07 100644 --- a/option/option.go +++ b/option/option.go @@ -5,7 +5,7 @@ import ( "github.com/obalunenko/getenv/internal" ) -// Option is a contract for EnvParser parameters options. +// Option configures how Env and EnvOrDefault parse the value of a variable. type Option interface { // Apply applies the option to the parameters. Apply(params *internal.Parameters) From 3397f9dd0020f2361347d8a3b2142d96931af2cb Mon Sep 17 00:00:00 2001 From: Oleg Balunenko Date: Mon, 16 Nov 2026 00:44:58 +0400 Subject: [PATCH 3/7] fix: keep url.URL values out of parse errors url.Parse returns a *url.Error that quotes the whole input, so an invalid DSN such as postgres://user:password@host put the password into the error and from there into logs. Return the underlying cause instead. Co-Authored-By: Claude Opus 5.5 --- internal/parse.go | 6 ++++++ internal/parse_test.go | 11 +++++++++++ 2 files changed, 17 insertions(+) diff --git a/internal/parse.go b/internal/parse.go index 703f4f8d..127e8d7a 100644 --- a/internal/parse.go +++ b/internal/parse.go @@ -2,6 +2,7 @@ package internal import ( + "errors" "fmt" "net" "net/netip" @@ -184,6 +185,11 @@ func parseTime(layout string) func(string) (time.Time, error) { func parseURL(s string) (url.URL, error) { u, err := url.Parse(s) if err != nil { + // url.Error quotes the whole input, which may hold credentials. + if uerr, ok := errors.AsType[*url.Error](err); ok { + return url.URL{}, uerr.Err + } + return url.URL{}, err } diff --git a/internal/parse_test.go b/internal/parse_test.go index 06fa922d..c45610f5 100644 --- a/internal/parse_test.go +++ b/internal/parse_test.go @@ -202,6 +202,17 @@ func TestParseURL(t *testing.T) { ) } +func TestParseURLErrorHidesValue(t *testing.T) { + for _, raw := range []string{ + "postgres://admin:S3cr3t@db:5432/app%zz", + "postgres://admin:S3cr3t@db:54x32/app", + } { + _, err := Parse[url.URL](raw, Parameters{}) + require.ErrorIs(t, err, ErrInvalidValue) + assert.NotContains(t, err.Error(), "S3cr3t") + } +} + func TestParseNetwork(t *testing.T) { testParse(t, parseCase[net.IP]{name: "ipv4", raw: "192.168.8.0", want: net.ParseIP("192.168.8.0")}, From bc0dfff1001f67de5b8eea35ab18dec769bcb90a Mon Sep 17 00:00:00 2001 From: Oleg Balunenko Date: Mon, 16 Nov 2026 00:47:19 +0400 Subject: [PATCH 4/7] refactor: merge internal and option into the root package The option package could not import getenv, so the parameters it sets had to live in a third package, internal. That leaked into the public API: Option.Apply took an *internal.Parameters that callers cannot name, and Parsable was an alias of internal.EnvParsable, so godoc did not list the supported types and the package doc had to repeat them by hand. Everything now lives in package getenv: - Option, WithSeparator and WithTimeLayout. Option is sealed with an unexported method instead of by an unimportable parameter type. - Parsable spells out its types, so godoc shows them and the package doc points there instead of repeating them. Package option stays as a deprecated forwarder: option.Option is an alias of getenv.Option, so existing calls keep compiling. Option.Apply is gone; it could not be called outside the module, as internal.Parameters cannot be constructed there. Co-Authored-By: Claude Opus 5.5 --- README.md | 81 ++++++--------------- constraint.go | 42 +++++++++++ getenv.go | 91 +++--------------------- getenv_example_test.go | 17 +++-- getenv_test.go | 15 ++-- internal/constraint.go | 93 ------------------------- internal/errors.go | 14 ---- internal/options.go | 10 --- option.go | 60 ++++++++++++++++ option/option.go | 32 ++++----- option/option_test.go | 35 +++------- internal/parse.go => parse.go | 33 ++++----- internal/parse_test.go => parse_test.go | 42 +++++------ 13 files changed, 207 insertions(+), 358 deletions(-) create mode 100644 constraint.go delete mode 100644 internal/constraint.go delete mode 100644 internal/errors.go delete mode 100644 internal/options.go create mode 100644 option.go rename internal/parse.go => parse.go (81%) rename internal/parse_test.go => parse_test.go (91%) diff --git a/README.md b/README.md index d2abd34b..c6872f16 100644 --- a/README.md +++ b/README.md @@ -12,57 +12,18 @@ It's type-safe and supports built-in types and slices of them. Empty environment variable values are treated as not set. Slices are split by "," and time.Time values are parsed with the time.RFC3339 layout, -unless option.WithSeparator or option.WithTimeLayout sets another one. - -Types supported: -- string -- []string -- int -- []int -- int8 -- []int8 -- int16 -- []int16 -- int32 -- []int32 -- int64 -- []int64 -- uint8 -- []uint8 -- uint16 -- []uint16 -- uint64 -- []uint64 -- uint -- []uint -- uintptr -- []uintptr -- uint32 -- []uint32 -- float32 -- []float32 -- float64 -- []float64 -- time.Time -- []time.Time -- time.Duration -- []time.Duration -- bool -- []bool -- url.URL -- []url.URL -- net.IP -- []net.IP -- netip.Addr -- []netip.Addr -- netip.Prefix -- []netip.Prefix -- net.HardwareAddr -- []net.HardwareAddr -- complex64 -- []complex64 -- complex128 -- []complex128 +unless getenv.WithSeparator or getenv.WithTimeLayout sets another one. + +Types supported, each both as a single value and as a slice (see `Parsable`): +- `string` +- `int`, `int8`, `int16`, `int32`, `int64` +- `uint`, `uint8`, `uint16`, `uint32`, `uint64`, `uintptr` +- `float32`, `float64` +- `complex64`, `complex128` +- `bool` +- `time.Time`, `time.Duration` +- `url.URL` +- `net.IP`, `net.HardwareAddr`, `netip.Addr`, `netip.Prefix` ## Examples @@ -83,7 +44,6 @@ import ( "time" "github.com/obalunenko/getenv" - "github.com/obalunenko/getenv/option" ) func main() { @@ -131,7 +91,7 @@ func main() { panic(err) } - val, err = getenv.Env[time.Time](key, option.WithTimeLayout("2006-01-02")) + val, err = getenv.Env[time.Time](key, getenv.WithTimeLayout("2006-01-02")) fmt.Printf("[%T]: %v; err: %v\n", val, val, err) // []float64 @@ -139,7 +99,7 @@ func main() { panic(err) } - val, err = getenv.Env[[]float64](key, option.WithSeparator(",")) + val, err = getenv.Env[[]float64](key, getenv.WithSeparator(",")) fmt.Printf("[%T]: %v; err: %v\n", val, val, err) // time.Duration @@ -171,7 +131,7 @@ func main() { panic(err) } - val, err = getenv.Env[[]string](key, option.WithSeparator(",")) + val, err = getenv.Env[[]string](key, getenv.WithSeparator(",")) fmt.Printf("[%T]: %v; err: %v\n", val, val, err) // complex128 @@ -187,7 +147,7 @@ func main() { panic(err) } - val, err = getenv.Env[[]complex64](key, option.WithSeparator(",")) + val, err = getenv.Env[[]complex64](key, getenv.WithSeparator(",")) fmt.Printf("[%T]: %v; err: %v\n", val, val, err) } @@ -228,7 +188,6 @@ import ( "time" "github.com/obalunenko/getenv" - "github.com/obalunenko/getenv/option" ) func main() { @@ -267,7 +226,7 @@ func main() { val = getenv.EnvOrDefault(key, time.Date(1992, 12, 1, 0, 0, 0, 0, time.UTC), - option.WithTimeLayout("2006-01-02"), + getenv.WithTimeLayout("2006-01-02"), ) fmt.Printf("[%T]: %v\n", val, val) @@ -277,7 +236,7 @@ func main() { } val = getenv.EnvOrDefault(key, []float64{-99}, - option.WithSeparator(","), + getenv.WithSeparator(","), ) fmt.Printf("[%T]: %v\n", val, val) @@ -310,7 +269,7 @@ func main() { panic(err) } - val = getenv.EnvOrDefault(key, []string{}, option.WithSeparator(",")) + val = getenv.EnvOrDefault(key, []string{}, getenv.WithSeparator(",")) fmt.Printf("[%T]: %v\n", val, val) // complex128 @@ -326,7 +285,7 @@ func main() { panic(err) } - val = getenv.EnvOrDefault(key, []complex64{}, option.WithSeparator(",")) + val = getenv.EnvOrDefault(key, []complex64{}, getenv.WithSeparator(",")) fmt.Printf("[%T]: %v\n", val, val) } diff --git a/constraint.go b/constraint.go new file mode 100644 index 00000000..4bc1dc79 --- /dev/null +++ b/constraint.go @@ -0,0 +1,42 @@ +package getenv + +import ( + "net" + "net/netip" + "net/url" + "time" +) + +// Parsable is a constraint for the types that Env and EnvOrDefault can parse. +// Every type is supported both as a single value and as a slice. +type Parsable interface { + string | []string | + int | []int | int8 | []int8 | int16 | []int16 | int32 | []int32 | int64 | []int64 | + uint | []uint | uint8 | []uint8 | uint16 | []uint16 | uint32 | []uint32 | uint64 | []uint64 | uintptr | []uintptr | + float32 | []float32 | float64 | []float64 | + complex64 | []complex64 | complex128 | []complex128 | + bool | []bool | + time.Time | []time.Time | time.Duration | []time.Duration | + url.URL | []url.URL | + net.IP | []net.IP | net.HardwareAddr | []net.HardwareAddr | + netip.Addr | []netip.Addr | netip.Prefix | []netip.Prefix +} + +// Constraints of the number parsers. +type ( + signed interface { + int | int8 | int16 | int32 | int64 + } + + unsigned interface { + uint | uint8 | uint16 | uint32 | uint64 | uintptr + } + + float interface { + float32 | float64 + } + + complexNumber interface { + complex64 | complex128 + } +) diff --git a/getenv.go b/getenv.go index c36fe750..fcf457d6 100644 --- a/getenv.go +++ b/getenv.go @@ -3,89 +3,28 @@ // Note: empty environment variable values are treated as "not set". // // Slices are split by "," and time.Time values are parsed with the time.RFC3339 layout, -// unless option.WithSeparator or option.WithTimeLayout sets another one. +// unless WithSeparator or WithTimeLayout sets another one. // -// Types supported: -// - string -// - []string -// - int -// - []int -// - int8 -// - []int8 -// - int16 -// - []int16 -// - int32 -// - []int32 -// - int64 -// - []int64 -// - uint8 -// - []uint8 -// - uint16 -// - []uint16 -// - uint64 -// - []uint64 -// - uint -// - []uint -// - uintptr -// - []uintptr -// - uint32 -// - []uint32 -// - float32 -// - []float32 -// - float64 -// - []float64 -// - time.Time -// - []time.Time -// - time.Duration -// - []time.Duration -// - bool -// - []bool -// - url.URL -// - []url.URL -// - net.IP -// - []net.IP -// - netip.Addr -// - []netip.Addr -// - netip.Prefix -// - []netip.Prefix -// - net.HardwareAddr -// - []net.HardwareAddr -// - complex64 -// - []complex64 -// - complex128 -// - []complex128 +// The supported types are listed in Parsable. package getenv import ( + "errors" "fmt" "os" - "time" - - "github.com/obalunenko/getenv/internal" - "github.com/obalunenko/getenv/option" ) var ( // ErrNotSet is an error that is returned when the environment variable is not set. - ErrNotSet = internal.ErrNotSet + ErrNotSet = errors.New("not set") // ErrInvalidValue is an error that is returned when the environment variable is not valid. - ErrInvalidValue = internal.ErrInvalidValue -) - -// Defaults for the options that were not passed. -const ( - defaultSeparator = "," - defaultTimeLayout = time.RFC3339 + ErrInvalidValue = errors.New("invalid value") ) -// Parsable is a constraint for the types that Env and EnvOrDefault can parse. -// The list of supported types is in the package documentation. -type Parsable = internal.EnvParsable - // Env retrieves the value of the environment variable named by the key. // If the variable is present in the environment, the value will be parsed and returned. // Otherwise, an error will be returned. -func Env[T Parsable](key string, options ...option.Option) (T, error) { +func Env[T Parsable](key string, options ...Option) (T, error) { var zero T raw, ok := os.LookupEnv(key) @@ -93,7 +32,7 @@ func Env[T Parsable](key string, options ...option.Option) (T, error) { return zero, fmt.Errorf("failed to get environment variable[%s]: %w", key, ErrNotSet) } - val, err := internal.Parse[T](raw, newParseParams(options)) + val, err := parseAs[T](raw, newParams(options)) if err != nil { return zero, fmt.Errorf("failed to parse environment variable[%s]: %w", key, err) } @@ -105,7 +44,7 @@ func Env[T Parsable](key string, options ...option.Option) (T, error) { // If the variable is set and its value can be parsed, the parsed value is returned. // Otherwise, defaultVal is returned: both when the variable is not set (or empty) // and when its value is invalid. Use Env to tell these cases apart. -func EnvOrDefault[T Parsable](key string, defaultVal T, options ...option.Option) T { +func EnvOrDefault[T Parsable](key string, defaultVal T, options ...Option) T { val, err := Env[T](key, options...) if err != nil { return defaultVal @@ -113,17 +52,3 @@ func EnvOrDefault[T Parsable](key string, defaultVal T, options ...option.Option return val } - -// newParseParams creates new parameters from the defaults and options. -func newParseParams(opts []option.Option) internal.Parameters { - p := internal.Parameters{ - Separator: defaultSeparator, - Layout: defaultTimeLayout, - } - - for _, opt := range opts { - opt.Apply(&p) - } - - return p -} diff --git a/getenv_example_test.go b/getenv_example_test.go index 9d0b1330..035614c0 100644 --- a/getenv_example_test.go +++ b/getenv_example_test.go @@ -8,7 +8,6 @@ import ( "time" "github.com/obalunenko/getenv" - "github.com/obalunenko/getenv/option" ) func ExampleEnvOrDefault() { @@ -47,7 +46,7 @@ func ExampleEnvOrDefault() { val = getenv.EnvOrDefault(key, time.Date(1992, 12, 1, 0, 0, 0, 0, time.UTC), - option.WithTimeLayout("2006-01-02"), + getenv.WithTimeLayout("2006-01-02"), ) fmt.Printf("[%T]: %v\n", val, val) @@ -57,7 +56,7 @@ func ExampleEnvOrDefault() { } val = getenv.EnvOrDefault(key, []float64{-99}, - option.WithSeparator(","), + getenv.WithSeparator(","), ) fmt.Printf("[%T]: %v\n", val, val) @@ -96,7 +95,7 @@ func ExampleEnvOrDefault() { panic(err) } - val = getenv.EnvOrDefault(key, []string{}, option.WithSeparator(",")) + val = getenv.EnvOrDefault(key, []string{}, getenv.WithSeparator(",")) fmt.Printf("[%T]: %v\n", val, val) // complex128 @@ -112,7 +111,7 @@ func ExampleEnvOrDefault() { panic(err) } - val = getenv.EnvOrDefault(key, []complex64{}, option.WithSeparator(",")) + val = getenv.EnvOrDefault(key, []complex64{}, getenv.WithSeparator(",")) fmt.Printf("[%T]: %v\n", val, val) // Output: @@ -173,7 +172,7 @@ func ExampleEnv() { panic(err) } - val, err = getenv.Env[time.Time](key, option.WithTimeLayout("2006-01-02")) + val, err = getenv.Env[time.Time](key, getenv.WithTimeLayout("2006-01-02")) fmt.Printf("[%T]: %v; err: %v\n", val, val, err) // []float64 @@ -181,7 +180,7 @@ func ExampleEnv() { panic(err) } - val, err = getenv.Env[[]float64](key, option.WithSeparator(",")) + val, err = getenv.Env[[]float64](key, getenv.WithSeparator(",")) fmt.Printf("[%T]: %v; err: %v\n", val, val, err) // time.Duration @@ -219,7 +218,7 @@ func ExampleEnv() { panic(err) } - val, err = getenv.Env[[]string](key, option.WithSeparator(",")) + val, err = getenv.Env[[]string](key, getenv.WithSeparator(",")) fmt.Printf("[%T]: %v; err: %v\n", val, val, err) // complex128 @@ -235,7 +234,7 @@ func ExampleEnv() { panic(err) } - val, err = getenv.Env[[]complex64](key, option.WithSeparator(",")) + val, err = getenv.Env[[]complex64](key, getenv.WithSeparator(",")) fmt.Printf("[%T]: %v; err: %v\n", val, val, err) // Output: diff --git a/getenv_test.go b/getenv_test.go index aaf3091d..b269753d 100644 --- a/getenv_test.go +++ b/getenv_test.go @@ -9,10 +9,9 @@ import ( "github.com/stretchr/testify/require" "github.com/obalunenko/getenv" - "github.com/obalunenko/getenv/option" ) -// Parsing of every supported type is covered in the internal package; +// Parsing of every supported type is covered in parse_test.go; // these tests check the public API: lookup, errors and options. const testEnvKey = "GH_GETENV_TEST" @@ -69,7 +68,7 @@ func TestEnvOptions(t *testing.T) { t.Run("separator", func(t *testing.T) { t.Setenv(testEnvKey, "1|2|3") - got, err := getenv.Env[[]int](testEnvKey, option.WithSeparator("|")) + got, err := getenv.Env[[]int](testEnvKey, getenv.WithSeparator("|")) require.NoError(t, err) assert.Equal(t, []int{1, 2, 3}, got) }) @@ -77,7 +76,7 @@ func TestEnvOptions(t *testing.T) { t.Run("time layout", func(t *testing.T) { t.Setenv(testEnvKey, "2022-01-20") - got, err := getenv.Env[time.Time](testEnvKey, option.WithTimeLayout(time.DateOnly)) + got, err := getenv.Env[time.Time](testEnvKey, getenv.WithTimeLayout(time.DateOnly)) require.NoError(t, err) assert.Equal(t, time.Date(2022, 1, 20, 0, 0, 0, 0, time.UTC), got) }) @@ -101,13 +100,13 @@ func TestEnvOptions(t *testing.T) { t.Run("empty separator", func(t *testing.T) { t.Setenv(testEnvKey, "1,2") - _, err := getenv.Env[[]int](testEnvKey, option.WithSeparator("")) + _, err := getenv.Env[[]int](testEnvKey, getenv.WithSeparator("")) require.ErrorIs(t, err, getenv.ErrInvalidValue) assert.ErrorContains(t, err, "empty separator") }) t.Run("not set is reported before empty separator", func(t *testing.T) { - _, err := getenv.Env[[]int](testEnvKey, option.WithSeparator("")) + _, err := getenv.Env[[]int](testEnvKey, getenv.WithSeparator("")) require.ErrorIs(t, err, getenv.ErrNotSet) }) } @@ -142,7 +141,7 @@ func TestEnvOrDefaultOptions(t *testing.T) { t.Run("separator", func(t *testing.T) { t.Setenv(testEnvKey, "a|b") - got := getenv.EnvOrDefault(testEnvKey, []string{"default"}, option.WithSeparator("|")) + got := getenv.EnvOrDefault(testEnvKey, []string{"default"}, getenv.WithSeparator("|")) assert.Equal(t, []string{"a", "b"}, got) }) @@ -175,6 +174,6 @@ func BenchmarkEnvOrDefault(b *testing.B) { b.ReportAllocs() for b.Loop() { - _ = getenv.EnvOrDefault(testEnvKey, []float64{}, option.WithSeparator(",")) + _ = getenv.EnvOrDefault(testEnvKey, []float64{}, getenv.WithSeparator(",")) } } diff --git a/internal/constraint.go b/internal/constraint.go deleted file mode 100644 index 1fb52f08..00000000 --- a/internal/constraint.go +++ /dev/null @@ -1,93 +0,0 @@ -package internal - -import ( - "net" - "net/netip" - "net/url" - "time" -) - -type ( - // EnvParsable is a constraint for types that can be parsed from environment variable. - EnvParsable interface { - String | Number | NumberSlice | Time | Bool | URL | Network | Complex | ComplexSlice - } - - // String is a constraint for string and slice of strings. - String interface { - string | []string - } - - // Number is a constraint for integer, float and unsigned integer. - Number interface { - Int | Float | Uint - } - - // NumberSlice is a constraint for slice of integers, floats and unsigned integers. - NumberSlice interface { - IntSlice | FloatSlice | UintSlice - } - - // Int is a constraint for integer scalar types. - Int interface { - int | int8 | int16 | int32 | int64 - } - - // IntSlice is a constraint for slice of integers. - IntSlice interface { - []int | []int8 | []int16 | []int32 | []int64 - } - - // Uint is a constraint for unsigned integer scalar types. - Uint interface { - uint | uint8 | uint16 | uint32 | uint64 | uintptr - } - - // UintSlice is a constraint for slice of unsigned integers. - UintSlice interface { - []uint | []uint8 | []uint16 | []uint32 | []uint64 | []uintptr - } - - // Float is a constraint for floating-point scalar types. - Float interface { - float32 | float64 - } - - // FloatSlice is a constraint for slice of floats. - FloatSlice interface { - []float32 | []float64 - } - - // Time is a constraint for time.Time and time.Duration and slices of them. - Time interface { - time.Time | []time.Time | time.Duration | []time.Duration - } - - // Bool is a constraint for bool and slice of bool. - Bool interface { - bool | []bool - } - - // URL is a constraint for url.URL and slice of url.URL. - URL interface { - url.URL | []url.URL - } - - // Network is a constraint for network address types and slices of them. - Network interface { - net.IP | []net.IP | - net.HardwareAddr | []net.HardwareAddr | - netip.Addr | []netip.Addr | - netip.Prefix | []netip.Prefix - } - - // ComplexSlice is a constraint for slice of complex. - ComplexSlice interface { - []complex64 | []complex128 - } - - // Complex is a constraint for complex scalar types. - Complex interface { - complex64 | complex128 - } -) diff --git a/internal/errors.go b/internal/errors.go deleted file mode 100644 index 3d1f5d97..00000000 --- a/internal/errors.go +++ /dev/null @@ -1,14 +0,0 @@ -package internal - -import ( - "errors" -) - -var ( - // ErrNotSet is an error that is returned when the environment variable is not set. - ErrNotSet = errors.New("not set") - // ErrInvalidValue is an error that is returned when the environment variable is not valid. - ErrInvalidValue = errors.New("invalid value") - - errEmptySeparator = errors.New("empty separator") -) diff --git a/internal/options.go b/internal/options.go deleted file mode 100644 index 65c26b26..00000000 --- a/internal/options.go +++ /dev/null @@ -1,10 +0,0 @@ -package internal - -// Parameters is a struct for holding parameters for the parser. -// It is used to pass parameters to the parser. -// Separator is a separator for the environment variable that holds slice. -// Layout is a layout for the time.Time. -type Parameters struct { - Separator string - Layout string -} diff --git a/option.go b/option.go new file mode 100644 index 00000000..6099b559 --- /dev/null +++ b/option.go @@ -0,0 +1,60 @@ +package getenv + +import ( + "time" +) + +// Defaults for the options that were not passed. +const ( + defaultSeparator = "," + defaultTimeLayout = time.RFC3339 +) + +// Option configures how Env and EnvOrDefault parse the value of a variable. +type Option interface { + apply(p *params) +} + +// params holds the parameters that options set. +type params struct { + // separator splits slice values. + separator string + // layout parses time.Time values. + layout string +} + +type withSeparator string + +func (w withSeparator) apply(p *params) { + p.separator = string(w) +} + +// WithSeparator sets the separator of slice values. The default is ",". +func WithSeparator(separator string) Option { + return withSeparator(separator) +} + +type withTimeLayout string + +func (w withTimeLayout) apply(p *params) { + p.layout = string(w) +} + +// WithTimeLayout sets the layout of time.Time values. The default is time.RFC3339. +func WithTimeLayout(layout string) Option { + return withTimeLayout(layout) +} + +// newParams creates new parameters from the defaults and options. +func newParams(opts []Option) params { + p := params{ + separator: defaultSeparator, + layout: defaultTimeLayout, + } + + for _, opt := range opts { + opt.apply(&p) + } + + return p +} diff --git a/option/option.go b/option/option.go index ae8dde07..6eac2d7f 100644 --- a/option/option.go +++ b/option/option.go @@ -1,34 +1,28 @@ // Package option provides options for parsing environment variables. +// +// Deprecated: the options moved to package getenv. Use getenv.Option, +// getenv.WithSeparator and getenv.WithTimeLayout instead. package option import ( - "github.com/obalunenko/getenv/internal" + "github.com/obalunenko/getenv" ) // Option configures how Env and EnvOrDefault parse the value of a variable. -type Option interface { - // Apply applies the option to the parameters. - Apply(params *internal.Parameters) -} - -type withSeparator string - -func (w withSeparator) Apply(p *internal.Parameters) { - p.Separator = string(w) -} +// +// Deprecated: Use getenv.Option instead. +type Option = getenv.Option // WithSeparator sets the separator of slice values. The default is ",". +// +// Deprecated: Use getenv.WithSeparator instead. func WithSeparator(separator string) Option { - return withSeparator(separator) -} - -type withTimeLayout string - -func (w withTimeLayout) Apply(p *internal.Parameters) { - p.Layout = string(w) + return getenv.WithSeparator(separator) } // WithTimeLayout sets the layout of time.Time values. The default is time.RFC3339. +// +// Deprecated: Use getenv.WithTimeLayout instead. func WithTimeLayout(layout string) Option { - return withTimeLayout(layout) + return getenv.WithTimeLayout(layout) } diff --git a/option/option_test.go b/option/option_test.go index 181ffb70..6c09ae16 100644 --- a/option/option_test.go +++ b/option/option_test.go @@ -5,34 +5,21 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" - "github.com/obalunenko/getenv/internal" + "github.com/obalunenko/getenv" ) +// The options must keep working for the callers that have not moved to package getenv yet. func TestOptions(t *testing.T) { - var p internal.Parameters + const key = "GH_GETENV_TEST" - var opt Option + t.Setenv(key, "2022-01-20|2022-01-21") - opt = WithSeparator("|") - - opt.Apply(&p) - - expected := internal.Parameters{ - Separator: "|", - Layout: "", - } - - assert.Equal(t, expected, p) - - opt = WithTimeLayout(time.RFC822) - - opt.Apply(&p) - - expected = internal.Parameters{ - Separator: "|", - Layout: time.RFC822, - } - - assert.Equal(t, expected, p) + got, err := getenv.Env[[]time.Time](key, WithSeparator("|"), WithTimeLayout(time.DateOnly)) + require.NoError(t, err) + assert.Equal(t, []time.Time{ + time.Date(2022, 1, 20, 0, 0, 0, 0, time.UTC), + time.Date(2022, 1, 21, 0, 0, 0, 0, time.UTC), + }, got) } diff --git a/internal/parse.go b/parse.go similarity index 81% rename from internal/parse.go rename to parse.go index 127e8d7a..1bc7a95c 100644 --- a/internal/parse.go +++ b/parse.go @@ -1,5 +1,4 @@ -// Package internal provides internal implementation logic for environment variables parsing. -package internal +package getenv import ( "errors" @@ -15,10 +14,12 @@ import ( const decimalBase = 10 -// Parse converts the raw value of an environment variable to T. -// Slices are split by Parameters.Separator, time.Time is parsed with Parameters.Layout. +var errEmptySeparator = errors.New("empty separator") + +// parseAs converts the raw value of an environment variable to T. +// Slices are split by params.separator, time.Time is parsed with params.layout. // Every returned error wraps ErrInvalidValue. -func Parse[T EnvParsable](raw string, p Parameters) (T, error) { +func parseAs[T Parsable](raw string, p params) (T, error) { var res T if err := parseValue(&res, raw, p); err != nil { @@ -33,7 +34,7 @@ func Parse[T EnvParsable](raw string, p Parameters) (T, error) { // parseValue parses raw into the value that dst points to. // //nolint:gocyclo,funlen // Flat dispatch: one case per supported type and its slice. -func parseValue(dst any, raw string, p Parameters) error { +func parseValue(dst any, raw string, p params) error { var err error switch dst.(type) { @@ -72,7 +73,7 @@ func parseValue(dst any, raw string, p Parameters) error { case *bool, *[]bool: err = parseInto(dst, raw, p, strconv.ParseBool) case *time.Time, *[]time.Time: - err = parseInto(dst, raw, p, parseTime(p.Layout)) + err = parseInto(dst, raw, p, parseTime(p.layout)) case *time.Duration, *[]time.Duration: err = parseInto(dst, raw, p, time.ParseDuration) case *url.URL, *[]url.URL: @@ -86,7 +87,7 @@ func parseValue(dst any, raw string, p Parameters) error { case *net.HardwareAddr, *[]net.HardwareAddr: err = parseInto(dst, raw, p, net.ParseMAC) default: - // Unreachable from Parse while every EnvParsable type has a case above. + // Unreachable from parseAs while every Parsable type has a case above. panic("getenv: no parser for " + reflect.TypeOf(dst).String()) } @@ -94,16 +95,16 @@ func parseValue(dst any, raw string, p Parameters) error { } // parseInto parses raw into dst, which points to either E or []E. -func parseInto[E any](dst any, raw string, p Parameters, parse func(string) (E, error)) error { +func parseInto[E any](dst any, raw string, p params, parse func(string) (E, error)) error { var err error switch v := dst.(type) { case *E: *v, err = parse(raw) case *[]E: - *v, err = parseSlice(raw, p.Separator, parse) + *v, err = parseSlice(raw, p.separator, parse) default: - // Unreachable while every case of Parse passes the parser of its own type. + // Unreachable while every case of parseValue passes the parser of its own type. panic("getenv: parser does not match the destination type") } @@ -135,7 +136,7 @@ func parseString(s string) (string, error) { return s, nil } -func parseInt[T Int](s string) (T, error) { +func parseInt[T signed](s string) (T, error) { v, err := strconv.ParseInt(s, decimalBase, bitSize[T]()) if err != nil { return 0, err @@ -144,7 +145,7 @@ func parseInt[T Int](s string) (T, error) { return T(v), nil } -func parseUint[T Uint](s string) (T, error) { +func parseUint[T unsigned](s string) (T, error) { v, err := strconv.ParseUint(s, decimalBase, bitSize[T]()) if err != nil { return 0, err @@ -153,7 +154,7 @@ func parseUint[T Uint](s string) (T, error) { return T(v), nil } -func parseFloat[T Float](s string) (T, error) { +func parseFloat[T float](s string) (T, error) { v, err := strconv.ParseFloat(s, bitSize[T]()) if err != nil { return 0, err @@ -162,7 +163,7 @@ func parseFloat[T Float](s string) (T, error) { return T(v), nil } -func parseComplex[T Complex](s string) (T, error) { +func parseComplex[T complexNumber](s string) (T, error) { v, err := strconv.ParseComplex(s, bitSize[T]()) if err != nil { return 0, err @@ -172,7 +173,7 @@ func parseComplex[T Complex](s string) (T, error) { } // bitSize returns the size of T in bits, as the strconv parsers expect it. -func bitSize[T Number | Complex]() int { +func bitSize[T signed | unsigned | float | complexNumber]() int { return reflect.TypeFor[T]().Bits() } diff --git a/internal/parse_test.go b/parse_test.go similarity index 91% rename from internal/parse_test.go rename to parse_test.go index c45610f5..e4f59503 100644 --- a/internal/parse_test.go +++ b/parse_test.go @@ -1,4 +1,4 @@ -package internal +package getenv import ( "fmt" @@ -15,24 +15,24 @@ import ( ) // comma holds the parameters for slice cases. -var comma = Parameters{Separator: ","} +var comma = params{separator: ","} -type parseCase[T EnvParsable] struct { +type parseCase[T Parsable] struct { name string raw string - params Parameters + params params want T wantErr bool } -// testParse runs Parse[T] for every case: an error must wrap ErrInvalidValue and come with the zero value. -func testParse[T EnvParsable](t *testing.T, cases ...parseCase[T]) { +// testParse runs parseAs[T] for every case: an error must wrap ErrInvalidValue and come with the zero value. +func testParse[T Parsable](t *testing.T, cases ...parseCase[T]) { t.Helper() t.Run(fmt.Sprintf("%T", *new(T)), func(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - got, err := Parse[T](tc.raw, tc.params) + got, err := parseAs[T](tc.raw, tc.params) if tc.wantErr { require.ErrorIs(t, err, ErrInvalidValue) assert.Zero(t, got) @@ -53,7 +53,7 @@ func TestParseString(t *testing.T) { ) testParse(t, parseCase[[]string]{name: "values", raw: "true,newval", params: comma, want: []string{"true", "newval"}}, - parseCase[[]string]{name: "other separator", raw: "a,b", params: Parameters{Separator: " "}, want: []string{"a,b"}}, + parseCase[[]string]{name: "other separator", raw: "a,b", params: params{separator: " "}, want: []string{"a,b"}}, ) } @@ -161,7 +161,7 @@ func TestParseBool(t *testing.T) { func TestParseTime(t *testing.T) { const layout = "2006/02/01 15:04" - p := Parameters{Separator: ",", Layout: layout} + p := params{separator: ",", layout: layout} want := time.Date(2018, 4, 21, 22, 30, 0, 0, time.UTC) testParse(t, @@ -207,7 +207,7 @@ func TestParseURLErrorHidesValue(t *testing.T) { "postgres://admin:S3cr3t@db:5432/app%zz", "postgres://admin:S3cr3t@db:54x32/app", } { - _, err := Parse[url.URL](raw, Parameters{}) + _, err := parseAs[url.URL](raw, params{}) require.ErrorIs(t, err, ErrInvalidValue) assert.NotContains(t, err.Error(), "S3cr3t") } @@ -270,11 +270,11 @@ func TestParseNetwork(t *testing.T) { } func TestParseSliceErrors(t *testing.T) { - _, err := Parse[[]string]("a,b", Parameters{}) + _, err := parseAs[[]string]("a,b", params{}) require.ErrorIs(t, err, ErrInvalidValue) require.ErrorIs(t, err, errEmptySeparator) - _, err = Parse[[]int]("1,2,x", comma) + _, err = parseAs[[]int]("1,2,x", comma) require.ErrorIs(t, err, ErrInvalidValue) require.ErrorIs(t, err, strconv.ErrSyntax) assert.ErrorContains(t, err, "element 2") @@ -283,13 +283,13 @@ func TestParseSliceErrors(t *testing.T) { // unsupported is a type that has no parser. type unsupported struct{} -// The panics guard against programming errors in this package: Parse cannot reach them -// while every EnvParsable type has a parser of its own type. +// The panics guard against programming errors in this package: parseAs cannot reach them +// while every Parsable type has a parser of its own type. func TestParsePanics(t *testing.T) { t.Run("no parser for the type", func(t *testing.T) { var dst unsupported - assert.PanicsWithValue(t, "getenv: no parser for *internal.unsupported", func() { + assert.PanicsWithValue(t, "getenv: no parser for *getenv.unsupported", func() { err := parseValue(&dst, "1", comma) t.Errorf("returned %v instead of panicking", err) }) @@ -316,7 +316,7 @@ func FuzzParse(f *testing.F) { } f.Fuzz(func(t *testing.T, raw string) { - p := Parameters{Separator: ",", Layout: time.RFC3339} + p := params{separator: ",", layout: time.RFC3339} checkErrContract[int](t, raw, p) checkErrContract[[]uint8](t, raw, p) @@ -330,17 +330,17 @@ func FuzzParse(f *testing.F) { checkErrContract[[]netip.Prefix](t, raw, p) checkErrContract[net.HardwareAddr](t, raw, p) - got, err := Parse[[]string](raw, p) + got, err := parseAs[[]string](raw, p) require.NoError(t, err) assert.Len(t, got, strings.Count(raw, ",")+1) }) } -// checkErrContract asserts that a failed Parse returns the zero value and an error wrapping ErrInvalidValue. -func checkErrContract[T EnvParsable](t *testing.T, raw string, p Parameters) { +// checkErrContract asserts that a failed parseAs returns the zero value and an error wrapping ErrInvalidValue. +func checkErrContract[T Parsable](t *testing.T, raw string, p params) { t.Helper() - got, err := Parse[T](raw, p) + got, err := parseAs[T](raw, p) if err != nil { require.ErrorIs(t, err, ErrInvalidValue) require.Zero(t, got) @@ -351,7 +351,7 @@ func BenchmarkParse(b *testing.B) { b.ReportAllocs() for b.Loop() { - if _, err := Parse[[]float64]("1235.67,87.98", comma); err != nil { + if _, err := parseAs[[]float64]("1235.67,87.98", comma); err != nil { b.Fatal(err) } } From 189f6dd5c7d06f2cd91703f0556b8de36910cfbf Mon Sep 17 00:00:00 2001 From: Oleg Balunenko Date: Mon, 16 Nov 2026 00:47:39 +0400 Subject: [PATCH 5/7] docs: state how slice values are split Elements are not trimmed and a trailing separator adds an empty element. Both are easy to trip over, so say it in the package doc and pin it with tests. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 ++ getenv.go | 2 ++ parse_test.go | 4 ++++ 3 files changed, 8 insertions(+) diff --git a/README.md b/README.md index c6872f16..49f73c14 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,8 @@ Empty environment variable values are treated as not set. Slices are split by "," and time.Time values are parsed with the time.RFC3339 layout, unless getenv.WithSeparator or getenv.WithTimeLayout sets another one. +Slice elements are not trimmed, so "1, 2" is not a valid []int, +and a trailing separator adds an empty element: "a,b," is []string{"a", "b", ""}. Types supported, each both as a single value and as a slice (see `Parsable`): - `string` diff --git a/getenv.go b/getenv.go index fcf457d6..48f1dfc3 100644 --- a/getenv.go +++ b/getenv.go @@ -4,6 +4,8 @@ // // Slices are split by "," and time.Time values are parsed with the time.RFC3339 layout, // unless WithSeparator or WithTimeLayout sets another one. +// Slice elements are not trimmed, so "1, 2" is not a valid []int, +// and a trailing separator adds an empty element: "a,b," is []string{"a", "b", ""}. // // The supported types are listed in Parsable. package getenv diff --git a/parse_test.go b/parse_test.go index e4f59503..49b027cf 100644 --- a/parse_test.go +++ b/parse_test.go @@ -54,6 +54,8 @@ func TestParseString(t *testing.T) { testParse(t, parseCase[[]string]{name: "values", raw: "true,newval", params: comma, want: []string{"true", "newval"}}, parseCase[[]string]{name: "other separator", raw: "a,b", params: params{separator: " "}, want: []string{"a,b"}}, + parseCase[[]string]{name: "elements are not trimmed", raw: " a, b", params: comma, want: []string{" a", " b"}}, + parseCase[[]string]{name: "trailing separator adds an empty element", raw: "a,b,", params: comma, want: []string{"a", "b", ""}}, ) } @@ -81,6 +83,8 @@ func TestParseInt(t *testing.T) { testParse(t, parseCase[[]int]{name: "values", raw: "1,-2", params: comma, want: []int{1, -2}}, parseCase[[]int]{name: "invalid element", raw: "1,asd", params: comma, wantErr: true}, + parseCase[[]int]{name: "space after separator", raw: "1, 2", params: comma, wantErr: true}, + parseCase[[]int]{name: "trailing separator", raw: "1,2,", params: comma, wantErr: true}, ) testParse(t, parseCase[[]int8]{name: "values", raw: "1,2", params: comma, want: []int8{1, 2}}) testParse(t, parseCase[[]int16]{name: "values", raw: "1,2", params: comma, want: []int16{1, 2}}) From 5552837b831488e2e04ed7edfd12e3a729525b4a Mon Sep 17 00:00:00 2001 From: Oleg Balunenko Date: Mon, 16 Nov 2026 00:49:29 +0400 Subject: [PATCH 6/7] style: tidy error messages and split the examples - Errors read `environment variable "KEY": not set` instead of `failed to get environment variable[KEY]: not set`: %q is the usual way to quote a name, and "failed to" only adds length to a wrapped chain. - Use the literal base 10 for strconv: a named constant for it is noise. - Replace the two examples that printed every type through an any with one short example per use case, so godoc shows the typed results and how to tell ErrNotSet from ErrInvalidValue. - Regenerate the README examples. The old url.URL example printed the struct fields, not the URL its output claimed. Co-Authored-By: Claude Opus 5.5 --- README.md | 333 +++++++++++++++++++---------------------- getenv.go | 4 +- getenv_example_test.go | 271 ++++++++------------------------- parse.go | 6 +- 4 files changed, 225 insertions(+), 389 deletions(-) diff --git a/README.md b/README.md index 49f73c14..d0388b5b 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Types supported, each both as a single value and as a slice (see `Parsable`): ### Env Env retrieves the value of the environment variable named by the key. -If the variable is present in the environment the value will be parsed and returned. +If the variable is present in the environment, the value will be parsed and returned. Otherwise, an error will be returned. ```golang @@ -40,136 +40,137 @@ package main import ( "fmt" - "net" - "net/url" + "log" "os" - "time" "github.com/obalunenko/getenv" ) func main() { - const ( - key = "GH_GETENV_TEST" - ) - - var ( - val any - err error - ) - - defer func() { - if err = os.Unsetenv(key); err != nil { - panic(err) - } - }() - - // string - if err = os.Setenv(key, "golly"); err != nil { - panic(err) + // In a real program the variable comes from the environment. + if err := os.Setenv("PORT", "8080"); err != nil { + log.Fatal(err) } - val, err = getenv.Env[string](key) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) - - // int - if err = os.Setenv(key, "123"); err != nil { - panic(err) + port, err := getenv.Env[int]("PORT") + if err != nil { + log.Fatal(err) } - val, err = getenv.Env[int](key) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) + fmt.Println(port) +} - // int conversion error - if err = os.Setenv(key, "123s4"); err != nil { - panic(err) - } +``` - val, err = getenv.Env[int](key) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) + Output: - // time.Time - if err = os.Setenv(key, "2022-01-20"); err != nil { - panic(err) - } +``` +8080 +``` - val, err = getenv.Env[time.Time](key, getenv.WithTimeLayout("2006-01-02")) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) +### Env: errors - // []float64 - if err = os.Setenv(key, "26.89,0.67"); err != nil { - panic(err) - } +```golang +package main - val, err = getenv.Env[[]float64](key, getenv.WithSeparator(",")) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) +import ( + "errors" + "fmt" + "log" + "os" + + "github.com/obalunenko/getenv" +) - // time.Duration - if err = os.Setenv(key, "2h35m"); err != nil { - panic(err) +func main() { + if err := os.Setenv("WORKERS", "four"); err != nil { + log.Fatal(err) } - val, err = getenv.Env[time.Duration](key) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) + _, err := getenv.Env[int]("WORKERS") + fmt.Println(errors.Is(err, getenv.ErrInvalidValue), err) - // url.URL - if err = os.Setenv(key, "https://test:abcd123@golangbyexample.com:8000/tutorials/intro?type=advance&compact=false#history"); err != nil { - panic(err) - } + _, err = getenv.Env[int]("GETENV_EXAMPLE_NOT_SET") + fmt.Println(errors.Is(err, getenv.ErrNotSet), err) - val, err = getenv.Env[url.URL](key) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) +} - // net.IP - if err = os.Setenv(key, "2001:cb8::17"); err != nil { - panic(err) - } +``` - val, err = getenv.Env[net.IP](key) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) + Output: - // []string - if err = os.Setenv(key, "a,b,c,d"); err != nil { - panic(err) - } +``` +true environment variable "WORKERS": invalid value: strconv.ParseInt: parsing "four": invalid syntax +true environment variable "GETENV_EXAMPLE_NOT_SET": not set +``` + +### Env: slice + +```golang +package main + +import ( + "fmt" + "log" + "os" + + "github.com/obalunenko/getenv" +) - val, err = getenv.Env[[]string](key, getenv.WithSeparator(",")) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) +func main() { + if err := os.Setenv("HOSTS", "a.example.com,b.example.com"); err != nil { + log.Fatal(err) + } - // complex128 - if err = os.Setenv(key, "1+2i"); err != nil { - panic(err) + hosts, err := getenv.Env[[]string]("HOSTS") + if err != nil { + log.Fatal(err) } - val, err = getenv.Env[complex128](key) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) + fmt.Println(hosts) +} + +``` + + Output: + +``` +[a.example.com b.example.com] +``` + +### Env: url.URL + +```golang +package main + +import ( + "fmt" + "log" + "net/url" + "os" - // []complex64 - if err = os.Setenv(key, "1+2i,3+4i"); err != nil { - panic(err) + "github.com/obalunenko/getenv" +) + +func main() { + if err := os.Setenv("DATABASE_URL", "postgres://user:secret@db:5432/app"); err != nil { + log.Fatal(err) } - val, err = getenv.Env[[]complex64](key, getenv.WithSeparator(",")) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) + dsn, err := getenv.Env[url.URL]("DATABASE_URL") + if err != nil { + log.Fatal(err) + } + fmt.Println(dsn.Host, dsn.Redacted()) } ``` -Output: + Output: ``` -[string]: golly; err: -[int]: 123; err: -[int]: 0; err: failed to parse environment variable[GH_GETENV_TEST]: invalid value: strconv.ParseInt: parsing "123s4": invalid syntax -[time.Time]: 2022-01-20 00:00:00 +0000 UTC; err: -[[]float64]: [26.89 0.67]; err: -[time.Duration]: 2h35m0s; err: -[url.URL]: https://test:abcd123@golangbyexample.com:8000/tutorials/intro?type=advance&compact=false#history; err: -[net.IP]: 2001:cb8::17; err: -[[]string]: [a b c d]; err: -[complex128]: (1+2i); err: -[[]complex64]: [(1+2i) (3+4i)]; err: +db:5432 postgres://user:xxxxx@db:5432/app ``` ### EnvOrDefault @@ -184,8 +185,7 @@ package main import ( "fmt" - "net" - "net/url" + "log" "os" "time" @@ -193,118 +193,95 @@ import ( ) func main() { - const ( - key = "GH_GETENV_TEST" - ) + // "30" has no unit, so it is not a valid time.Duration: EnvOrDefault falls back + // to the default, the same as for a variable that is not set. Use Env to catch it. + if err := os.Setenv("TIMEOUT", "30"); err != nil { + log.Fatal(err) + } - defer func() { - if err := os.Unsetenv(key); err != nil { - panic(err) - } - }() + timeout := getenv.EnvOrDefault("TIMEOUT", 5*time.Second) + retries := getenv.EnvOrDefault("GETENV_EXAMPLE_RETRIES", 3) - var val any + fmt.Println(timeout, retries) +} - // string - if err := os.Setenv(key, "golly"); err != nil { - panic(err) - } +``` - val = getenv.EnvOrDefault(key, "golly") - fmt.Printf("[%T]: %v\n", val, val) + Output: - // int - if err := os.Setenv(key, "123"); err != nil { - panic(err) - } +``` +5s 3 +``` - val = getenv.EnvOrDefault(key, -99) - fmt.Printf("[%T]: %v\n", val, val) +### WithSeparator - // time.Time - if err := os.Setenv(key, "2022-01-20"); err != nil { - panic(err) - } +WithSeparator sets the separator of slice values. The default is ",". - val = getenv.EnvOrDefault(key, - time.Date(1992, 12, 1, 0, 0, 0, 0, time.UTC), - getenv.WithTimeLayout("2006-01-02"), - ) - fmt.Printf("[%T]: %v\n", val, val) +```golang +package main - // []float64 - if err := os.Setenv(key, "26.89,0.67"); err != nil { - panic(err) - } +import ( + "fmt" + "log" + "os" - val = getenv.EnvOrDefault(key, []float64{-99}, - getenv.WithSeparator(","), - ) - fmt.Printf("[%T]: %v\n", val, val) + "github.com/obalunenko/getenv" +) - // time.Duration - if err := os.Setenv(key, "2h35m"); err != nil { - panic(err) +func main() { + if err := os.Setenv("PORTS", "80|443"); err != nil { + log.Fatal(err) } - val = getenv.EnvOrDefault(key, time.Second) - fmt.Printf("[%T]: %v\n", val, val) - - // url.URL - if err := os.Setenv(key, "https://test:abcd123@golangbyexample.com:8000/tutorials/intro?type=advance&compact=false#history"); err != nil { - panic(err) + ports, err := getenv.Env[[]int]("PORTS", getenv.WithSeparator("|")) + if err != nil { + log.Fatal(err) } - val = getenv.EnvOrDefault(key, url.URL{}) - fmt.Printf("[%T]: %v\n", val, val) + fmt.Println(ports) +} - // net.IP - if err := os.Setenv(key, "2001:cb8::17"); err != nil { - panic(err) - } +``` - val = getenv.EnvOrDefault(key, net.IP{}) - fmt.Printf("[%T]: %v\n", val, val) + Output: - // []string - if err := os.Setenv(key, "a,b,c,d"); err != nil { - panic(err) - } +``` +[80 443] +``` - val = getenv.EnvOrDefault(key, []string{}, getenv.WithSeparator(",")) - fmt.Printf("[%T]: %v\n", val, val) +### WithTimeLayout - // complex128 - if err := os.Setenv(key, "1+2i"); err != nil { - panic(err) - } +WithTimeLayout sets the layout of time.Time values. The default is time.RFC3339. - val = getenv.EnvOrDefault(key, complex128(0)) - fmt.Printf("[%T]: %v\n", val, val) +```golang +package main + +import ( + "fmt" + "log" + "os" + "time" + + "github.com/obalunenko/getenv" +) - // []complex64 - if err := os.Setenv(key, "1+2i,3+4i"); err != nil { - panic(err) +func main() { + if err := os.Setenv("RELEASE_DATE", "2022-01-20"); err != nil { + log.Fatal(err) } - val = getenv.EnvOrDefault(key, []complex64{}, getenv.WithSeparator(",")) - fmt.Printf("[%T]: %v\n", val, val) + date, err := getenv.Env[time.Time]("RELEASE_DATE", getenv.WithTimeLayout(time.DateOnly)) + if err != nil { + log.Fatal(err) + } + fmt.Println(date) } ``` -Output: + Output: ``` -[string]: golly -[int]: 123 -[time.Time]: 2022-01-20 00:00:00 +0000 UTC -[[]float64]: [26.89 0.67] -[time.Duration]: 2h35m0s -[url.URL]: https://test:abcd123@golangbyexample.com:8000/tutorials/intro?type=advance&compact=false#history -[net.IP]: 2001:cb8::17 -[[]string]: [a b c d] -[complex128]: (1+2i) -[[]complex64]: [(1+2i) (3+4i)] +2022-01-20 00:00:00 +0000 UTC ``` diff --git a/getenv.go b/getenv.go index 48f1dfc3..852db533 100644 --- a/getenv.go +++ b/getenv.go @@ -31,12 +31,12 @@ func Env[T Parsable](key string, options ...Option) (T, error) { raw, ok := os.LookupEnv(key) if !ok || raw == "" { - return zero, fmt.Errorf("failed to get environment variable[%s]: %w", key, ErrNotSet) + return zero, fmt.Errorf("environment variable %q: %w", key, ErrNotSet) } val, err := parseAs[T](raw, newParams(options)) if err != nil { - return zero, fmt.Errorf("failed to parse environment variable[%s]: %w", key, err) + return zero, fmt.Errorf("environment variable %q: %w", key, err) } return val, nil diff --git a/getenv_example_test.go b/getenv_example_test.go index 035614c0..f1e45593 100644 --- a/getenv_example_test.go +++ b/getenv_example_test.go @@ -1,8 +1,9 @@ package getenv_test import ( + "errors" "fmt" - "net" + "log" "net/url" "os" "time" @@ -10,243 +11,103 @@ import ( "github.com/obalunenko/getenv" ) -func ExampleEnvOrDefault() { - const ( - key = "GH_GETENV_TEST" - ) - - defer func() { - if err := os.Unsetenv(key); err != nil { - panic(err) - } - }() - - var val any - - // string - if err := os.Setenv(key, "golly"); err != nil { - panic(err) - } - - val = getenv.EnvOrDefault(key, "golly") - fmt.Printf("[%T]: %v\n", val, val) - - // int - if err := os.Setenv(key, "123"); err != nil { - panic(err) - } - - val = getenv.EnvOrDefault(key, -99) - fmt.Printf("[%T]: %v\n", val, val) - - // time.Time - if err := os.Setenv(key, "2022-01-20"); err != nil { - panic(err) - } - - val = getenv.EnvOrDefault(key, - time.Date(1992, 12, 1, 0, 0, 0, 0, time.UTC), - getenv.WithTimeLayout("2006-01-02"), - ) - fmt.Printf("[%T]: %v\n", val, val) - - // []float64 - if err := os.Setenv(key, "26.89,0.67"); err != nil { - panic(err) - } - - val = getenv.EnvOrDefault(key, []float64{-99}, - getenv.WithSeparator(","), - ) - fmt.Printf("[%T]: %v\n", val, val) - - // time.Duration - if err := os.Setenv(key, "2h35m"); err != nil { - panic(err) - } - - val = getenv.EnvOrDefault(key, time.Second) - fmt.Printf("[%T]: %v\n", val, val) - - // url.URL - if err := os.Setenv(key, "https://test:abcd123@golangbyexample.com:8000/tutorials/intro?type=advance&compact=false#history"); err != nil { - panic(err) - } - - val = getenv.EnvOrDefault(key, url.URL{}) - urlVal, ok := val.(url.URL) - - if !ok { - panic("expected url.URL value") - } - - fmt.Printf("[%T]: %s\n", urlVal, urlVal.String()) - - // net.IP - if err := os.Setenv(key, "2001:cb8::17"); err != nil { - panic(err) +func ExampleEnv() { + // In a real program the variable comes from the environment. + if err := os.Setenv("PORT", "8080"); err != nil { + log.Fatal(err) } - val = getenv.EnvOrDefault(key, net.IP{}) - fmt.Printf("[%T]: %v\n", val, val) - - // []string - if err := os.Setenv(key, "a,b,c,d"); err != nil { - panic(err) + port, err := getenv.Env[int]("PORT") + if err != nil { + log.Fatal(err) } - val = getenv.EnvOrDefault(key, []string{}, getenv.WithSeparator(",")) - fmt.Printf("[%T]: %v\n", val, val) + fmt.Println(port) + // Output: 8080 +} - // complex128 - if err := os.Setenv(key, "1+2i"); err != nil { - panic(err) +func ExampleEnv_errors() { + if err := os.Setenv("WORKERS", "four"); err != nil { + log.Fatal(err) } - val = getenv.EnvOrDefault(key, complex128(0)) - fmt.Printf("[%T]: %v\n", val, val) + _, err := getenv.Env[int]("WORKERS") + fmt.Println(errors.Is(err, getenv.ErrInvalidValue), err) - // []complex64 - if err := os.Setenv(key, "1+2i,3+4i"); err != nil { - panic(err) - } - - val = getenv.EnvOrDefault(key, []complex64{}, getenv.WithSeparator(",")) - fmt.Printf("[%T]: %v\n", val, val) + _, err = getenv.Env[int]("GETENV_EXAMPLE_NOT_SET") + fmt.Println(errors.Is(err, getenv.ErrNotSet), err) // Output: - // [string]: golly - // [int]: 123 - // [time.Time]: 2022-01-20 00:00:00 +0000 UTC - // [[]float64]: [26.89 0.67] - // [time.Duration]: 2h35m0s - // [url.URL]: https://test:abcd123@golangbyexample.com:8000/tutorials/intro?type=advance&compact=false#history - // [net.IP]: 2001:cb8::17 - // [[]string]: [a b c d] - // [complex128]: (1+2i) - // [[]complex64]: [(1+2i) (3+4i)] + // true environment variable "WORKERS": invalid value: strconv.ParseInt: parsing "four": invalid syntax + // true environment variable "GETENV_EXAMPLE_NOT_SET": not set } -func ExampleEnv() { - const ( - key = "GH_GETENV_TEST" - ) - - var ( - val any - err error - ) - - defer func() { - if err = os.Unsetenv(key); err != nil { - panic(err) - } - }() - - // string - if err = os.Setenv(key, "golly"); err != nil { - panic(err) +func ExampleEnv_slice() { + if err := os.Setenv("HOSTS", "a.example.com,b.example.com"); err != nil { + log.Fatal(err) } - val, err = getenv.Env[string](key) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) - - // int - if err = os.Setenv(key, "123"); err != nil { - panic(err) - } - - val, err = getenv.Env[int](key) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) - - // int conversion error - if err = os.Setenv(key, "123s4"); err != nil { - panic(err) - } - - val, err = getenv.Env[int](key) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) - - // time.Time - if err = os.Setenv(key, "2022-01-20"); err != nil { - panic(err) + hosts, err := getenv.Env[[]string]("HOSTS") + if err != nil { + log.Fatal(err) } - val, err = getenv.Env[time.Time](key, getenv.WithTimeLayout("2006-01-02")) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) + fmt.Println(hosts) + // Output: [a.example.com b.example.com] +} - // []float64 - if err = os.Setenv(key, "26.89,0.67"); err != nil { - panic(err) +func ExampleEnv_url() { + if err := os.Setenv("DATABASE_URL", "postgres://user:secret@db:5432/app"); err != nil { + log.Fatal(err) } - val, err = getenv.Env[[]float64](key, getenv.WithSeparator(",")) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) - - // time.Duration - if err = os.Setenv(key, "2h35m"); err != nil { - panic(err) + dsn, err := getenv.Env[url.URL]("DATABASE_URL") + if err != nil { + log.Fatal(err) } - val, err = getenv.Env[time.Duration](key) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) + fmt.Println(dsn.Host, dsn.Redacted()) + // Output: db:5432 postgres://user:xxxxx@db:5432/app +} - // url.URL - if err = os.Setenv(key, "https://test:abcd123@golangbyexample.com:8000/tutorials/intro?type=advance&compact=false#history"); err != nil { - panic(err) +func ExampleEnvOrDefault() { + // "30" has no unit, so it is not a valid time.Duration: EnvOrDefault falls back + // to the default, the same as for a variable that is not set. Use Env to catch it. + if err := os.Setenv("TIMEOUT", "30"); err != nil { + log.Fatal(err) } - val, err = getenv.Env[url.URL](key) - urlVal, ok := val.(url.URL) - - if !ok { - panic("expected url.URL value") - } + timeout := getenv.EnvOrDefault("TIMEOUT", 5*time.Second) + retries := getenv.EnvOrDefault("GETENV_EXAMPLE_RETRIES", 3) - fmt.Printf("[%T]: %s; err: %v\n", urlVal, urlVal.String(), err) + fmt.Println(timeout, retries) + // Output: 5s 3 +} - // net.IP - if err = os.Setenv(key, "2001:cb8::17"); err != nil { - panic(err) +func ExampleWithSeparator() { + if err := os.Setenv("PORTS", "80|443"); err != nil { + log.Fatal(err) } - val, err = getenv.Env[net.IP](key) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) - - // []string - if err = os.Setenv(key, "a,b,c,d"); err != nil { - panic(err) + ports, err := getenv.Env[[]int]("PORTS", getenv.WithSeparator("|")) + if err != nil { + log.Fatal(err) } - val, err = getenv.Env[[]string](key, getenv.WithSeparator(",")) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) + fmt.Println(ports) + // Output: [80 443] +} - // complex128 - if err = os.Setenv(key, "1+2i"); err != nil { - panic(err) +func ExampleWithTimeLayout() { + if err := os.Setenv("RELEASE_DATE", "2022-01-20"); err != nil { + log.Fatal(err) } - val, err = getenv.Env[complex128](key) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) - - // []complex64 - if err = os.Setenv(key, "1+2i,3+4i"); err != nil { - panic(err) + date, err := getenv.Env[time.Time]("RELEASE_DATE", getenv.WithTimeLayout(time.DateOnly)) + if err != nil { + log.Fatal(err) } - val, err = getenv.Env[[]complex64](key, getenv.WithSeparator(",")) - fmt.Printf("[%T]: %v; err: %v\n", val, val, err) - - // Output: - // [string]: golly; err: - // [int]: 123; err: - // [int]: 0; err: failed to parse environment variable[GH_GETENV_TEST]: invalid value: strconv.ParseInt: parsing "123s4": invalid syntax - // [time.Time]: 2022-01-20 00:00:00 +0000 UTC; err: - // [[]float64]: [26.89 0.67]; err: - // [time.Duration]: 2h35m0s; err: - // [url.URL]: https://test:abcd123@golangbyexample.com:8000/tutorials/intro?type=advance&compact=false#history; err: - // [net.IP]: 2001:cb8::17; err: - // [[]string]: [a b c d]; err: - // [complex128]: (1+2i); err: - // [[]complex64]: [(1+2i) (3+4i)]; err: + fmt.Println(date) + // Output: 2022-01-20 00:00:00 +0000 UTC } diff --git a/parse.go b/parse.go index 1bc7a95c..c25f8837 100644 --- a/parse.go +++ b/parse.go @@ -12,8 +12,6 @@ import ( "time" ) -const decimalBase = 10 - var errEmptySeparator = errors.New("empty separator") // parseAs converts the raw value of an environment variable to T. @@ -137,7 +135,7 @@ func parseString(s string) (string, error) { } func parseInt[T signed](s string) (T, error) { - v, err := strconv.ParseInt(s, decimalBase, bitSize[T]()) + v, err := strconv.ParseInt(s, 10, bitSize[T]()) if err != nil { return 0, err } @@ -146,7 +144,7 @@ func parseInt[T signed](s string) (T, error) { } func parseUint[T unsigned](s string) (T, error) { - v, err := strconv.ParseUint(s, decimalBase, bitSize[T]()) + v, err := strconv.ParseUint(s, 10, bitSize[T]()) if err != nil { return 0, err } From 3028cf8ec17a6f3e834131f65c5d20c71af7c789 Mon Sep 17 00:00:00 2001 From: Oleg Balunenko Date: Mon, 16 Nov 2026 00:55:10 +0400 Subject: [PATCH 7/7] refactor: drop the unreachable return in parseURL url.Parse wraps every error in *url.Error, so the fallback return never ran and was the only statement left without coverage. Co-Authored-By: Claude Opus 5.5 --- parse.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parse.go b/parse.go index c25f8837..611ea172 100644 --- a/parse.go +++ b/parse.go @@ -186,7 +186,7 @@ func parseURL(s string) (url.URL, error) { if err != nil { // url.Error quotes the whole input, which may hold credentials. if uerr, ok := errors.AsType[*url.Error](err); ok { - return url.URL{}, uerr.Err + err = uerr.Err } return url.URL{}, err