diff --git a/README.md b/README.md index 77b94654..9670982a 100644 --- a/README.md +++ b/README.md @@ -10,64 +10,27 @@ 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. +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` +- `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 ### 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 @@ -75,137 +38,137 @@ package main import ( "fmt" - "net" - "net/url" + "log" "os" - "time" "github.com/obalunenko/getenv" - "github.com/obalunenko/getenv/option" ) 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, option.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, option.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, option.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, option.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 @@ -220,128 +183,103 @@ package main import ( "fmt" - "net" - "net/url" + "log" "os" "time" "github.com/obalunenko/getenv" - "github.com/obalunenko/getenv/option" ) 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), - option.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}, - option.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{}, option.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{}, option.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/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..852db533 100644 --- a/getenv.go +++ b/getenv.go @@ -3,99 +3,40 @@ // 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. +// 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: -// - 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) 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 := 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) + return zero, fmt.Errorf("environment variable %q: %w", key, err) } return val, nil @@ -105,7 +46,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 +54,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..f1e45593 100644 --- a/getenv_example_test.go +++ b/getenv_example_test.go @@ -1,253 +1,113 @@ package getenv_test import ( + "errors" "fmt" - "net" + "log" "net/url" "os" "time" "github.com/obalunenko/getenv" - "github.com/obalunenko/getenv/option" ) -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), - option.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}, - option.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{}, option.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{}, option.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, option.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, option.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, option.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, option.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/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 76% rename from internal/parse.go rename to parse.go index 703f4f8d..611ea172 100644 --- a/internal/parse.go +++ b/parse.go @@ -1,7 +1,7 @@ -// Package internal provides internal implementation logic for environment variables parsing. -package internal +package getenv import ( + "errors" "fmt" "net" "net/netip" @@ -12,12 +12,12 @@ import ( "time" ) -const decimalBase = 10 +var errEmptySeparator = errors.New("empty separator") -// Parse converts the raw value of an environment variable to T. -// Slices are split by Parameters.Separator, time.Time is parsed with Parameters.Layout. +// 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 { @@ -32,7 +32,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) { @@ -71,7 +71,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: @@ -85,7 +85,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()) } @@ -93,16 +93,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") } @@ -134,8 +134,8 @@ func parseString(s string) (string, error) { return s, nil } -func parseInt[T Int](s string) (T, error) { - v, err := strconv.ParseInt(s, decimalBase, bitSize[T]()) +func parseInt[T signed](s string) (T, error) { + v, err := strconv.ParseInt(s, 10, bitSize[T]()) if err != nil { return 0, err } @@ -143,8 +143,8 @@ func parseInt[T Int](s string) (T, error) { return T(v), nil } -func parseUint[T Uint](s string) (T, error) { - v, err := strconv.ParseUint(s, decimalBase, bitSize[T]()) +func parseUint[T unsigned](s string) (T, error) { + v, err := strconv.ParseUint(s, 10, bitSize[T]()) if err != nil { return 0, err } @@ -152,7 +152,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 @@ -161,7 +161,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 @@ -171,7 +171,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() } @@ -184,6 +184,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 { + err = uerr.Err + } + return url.URL{}, err } diff --git a/internal/parse_test.go b/parse_test.go similarity index 86% rename from internal/parse_test.go rename to parse_test.go index 06fa922d..49b027cf 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,9 @@ 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"}}, + 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}}) @@ -161,7 +165,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, @@ -202,6 +206,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 := parseAs[url.URL](raw, params{}) + 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")}, @@ -259,11 +274,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") @@ -272,13 +287,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) }) @@ -305,7 +320,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) @@ -319,17 +334,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) @@ -340,7 +355,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) } }