Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
240 changes: 239 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
# getenv

Package getenv provides a simple way to get environment variables.
It's type-safe and supports built-in types and slices of them.
It's generic and supports built-in types, custom 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,
Expand Down Expand Up @@ -64,13 +64,176 @@ Types supported:
- complex128
- []complex128

Custom types are supported as well, and so are slices of the supported types,
named slice types such as type Tags []string included.
A value of a custom type T is parsed with the first one that fits:
- the ParseEnv method of T, see EnvParser;
- the UnmarshalText method of *T, or of T if it is a pointer type, see encoding.TextUnmarshaler;
- the underlying type of T, if it is a string, bool or numeric type, as for type Port uint16.
Note that type Timeout time.Duration is parsed as int64 nanoseconds, not as a duration:
its underlying type is int64, and it does not get the methods of time.Duration.
To parse it as a duration, implement EnvParser (see its example),
or declare an alias instead, type Timeout = time.Duration, if it needs no methods of its own.

Env and EnvOrDefault panic for any other type, even when the variable is not set.

## Examples

### CustomType

This example shows how to read custom types from the environment with the same Env and EnvOrDefault:
types that implement getenv.EnvParser or encoding.TextUnmarshaler, types over basic types and slices of them.

```golang
package main

import (
"errors"
"fmt"
"log/slog"
"os"
"strings"

"github.com/obalunenko/getenv"
"github.com/obalunenko/getenv/option"
)

// Level is a custom type: it implements getenv.EnvParser.
type Level int

// Level values. The zero value is not a valid level.
const (
LevelDebug Level = iota + 1
LevelInfo
LevelWarn
LevelError
)

// Check at compile time that Level implements getenv.EnvParser.
var _ getenv.EnvParser[Level] = Level(0)

// String returns the name of the level.
func (l Level) String() string {
switch l {
case LevelDebug:
return "debug"
case LevelInfo:
return "info"
case LevelWarn:
return "warn"
case LevelError:
return "error"
default:
return fmt.Sprintf("Level(%d)", int(l))
}
}

// ParseEnv parses Level from the value of an environment variable.
// It has a value receiver: getenv calls it on the zero value.
func (Level) ParseEnv(raw string) (Level, error) {
switch strings.ToLower(raw) {
case "debug":
return LevelDebug, nil
case "info":
return LevelInfo, nil
case "warn":
return LevelWarn, nil
case "error":
return LevelError, nil
default:
return 0, fmt.Errorf("unknown level %q", raw)
}
}

// Port is a custom type over a basic type: it is parsed as uint16.
type Port uint16

// This example shows how to read custom types from the environment with the same Env and EnvOrDefault:
// types that implement getenv.EnvParser or encoding.TextUnmarshaler, types over basic types and slices of them.
func main() {
const (
key = "GH_GETENV_TEST"
)

var (
lvl Level
lvls []Level
err error
)

defer func() {
if err = os.Unsetenv(key); err != nil {
panic(err)
}
}()

// Level
if err = os.Setenv(key, "warn"); err != nil {
panic(err)
}

lvl, err = getenv.Env[Level](key)
fmt.Printf("[%T]: %v; err: %v\n", lvl, lvl, err)

// []Level
if err = os.Setenv(key, "debug|error"); err != nil {
panic(err)
}

lvls, err = getenv.Env[[]Level](key, option.WithSeparator("|"))
fmt.Printf("[%T]: %v; err: %v\n", lvls, lvls, err)

// Level parse error
if err = os.Setenv(key, "verbose"); err != nil {
panic(err)
}

lvl, err = getenv.Env[Level](key)
fmt.Printf("[%T]: %v; err: %v\n", lvl, lvl, err)
fmt.Printf("is invalid value: %t\n", errors.Is(err, getenv.ErrInvalidValue))

// Level default
lvl = getenv.EnvOrDefault(key, LevelInfo)
fmt.Printf("[%T]: %v\n", lvl, lvl)

// slog.Level implements encoding.TextUnmarshaler
if err = os.Setenv(key, "WARN,ERROR"); err != nil {
panic(err)
}

slvls, err := getenv.Env[[]slog.Level](key)
fmt.Printf("[%T]: %v; err: %v\n", slvls, slvls, err)

// Port
if err = os.Setenv(key, "8080"); err != nil {
panic(err)
}

port := getenv.EnvOrDefault(key, Port(80))
fmt.Printf("[%T]: %v\n", port, port)

}

```

Output:

```
[main.Level]: warn; err: <nil>
[[]main.Level]: [debug error]; err: <nil>
[main.Level]: Level(0); err: failed to parse environment variable[GH_GETENV_TEST]: unknown level "verbose": invalid value
is invalid value: true
[main.Level]: info
[[]slog.Level]: [WARN ERROR]; err: <nil>
[main.Port]: 8080
```

### 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.
Otherwise, an error will be returned.
Env panics if T is not supported (see the package documentation), even when the variable is not set.

```golang
package main
Expand Down Expand Up @@ -216,6 +379,7 @@ EnvOrDefault retrieves the value of the environment variable named by the key.
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.
EnvOrDefault panics if T is not supported, like Env.

```golang
package main
Expand Down Expand Up @@ -347,3 +511,77 @@ Output:
[complex128]: (1+2i)
[[]complex64]: [(1+2i) (3+4i)]
```

### EnvParser

This example shows how to parse a type defined over time.Duration as a duration.

```golang
package main

import (
"fmt"
"os"
"time"

"github.com/obalunenko/getenv"
)

// Timeout is defined over time.Duration: without ParseEnv it would be parsed as int64 nanoseconds.
type Timeout time.Duration

// Check at compile time that Timeout implements getenv.EnvParser.
var _ getenv.EnvParser[Timeout] = Timeout(0)

// ParseEnv parses Timeout as a duration.
func (Timeout) ParseEnv(raw string) (Timeout, error) {
d, err := time.ParseDuration(raw)

return Timeout(d), err
}

// String returns Timeout as a duration.
func (t Timeout) String() string {
return time.Duration(t).String()
}

// This example shows how to parse a type defined over time.Duration as a duration.
func main() {
const (
key = "GH_GETENV_TEST"
)

var err error

defer func() {
if err = os.Unsetenv(key); err != nil {
panic(err)
}
}()

// Timeout
if err = os.Setenv(key, "2m30s"); err != nil {
panic(err)
}

timeout, err := getenv.Env[Timeout](key)
fmt.Printf("[%T]: %v; err: %v\n", timeout, timeout, err)

// []Timeout
if err = os.Setenv(key, "1s,500ms"); err != nil {
panic(err)
}

timeouts := getenv.EnvOrDefault(key, []Timeout{Timeout(time.Second)})
fmt.Printf("[%T]: %v\n", timeouts, timeouts)

}

```

Output:

```
[main.Timeout]: 2m30s; err: <nil>
[[]main.Timeout]: [1s 500ms]
```
39 changes: 35 additions & 4 deletions getenv.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Package getenv provides a simple way to get environment variables.
// It's type-safe and supports built-in types and slices of them.
// It's generic and supports built-in types, custom types and slices of them.
// 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,
Expand Down Expand Up @@ -54,6 +54,19 @@
// - []complex64
// - complex128
// - []complex128
//
// Custom types are supported as well, and so are slices of the supported types,
// named slice types such as type Tags []string included.
// A value of a custom type T is parsed with the first one that fits:
// - the ParseEnv method of T, see EnvParser;
// - the UnmarshalText method of *T, or of T if it is a pointer type, see encoding.TextUnmarshaler;
// - the underlying type of T, if it is a string, bool or numeric type, as for type Port uint16.
// Note that type Timeout time.Duration is parsed as int64 nanoseconds, not as a duration:
// its underlying type is int64, and it does not get the methods of time.Duration.
// To parse it as a duration, implement EnvParser (see its example),
// or declare an alias instead, type Timeout = time.Duration, if it needs no methods of its own.
//
// Env and EnvOrDefault panic for any other type, even when the variable is not set.
package getenv

import (
Expand All @@ -70,6 +83,8 @@ var (
ErrNotSet = internal.ErrNotSet
// ErrInvalidValue is an error that is returned when the environment variable is not valid.
ErrInvalidValue = internal.ErrInvalidValue
// ErrUnsupportedType is wrapped by the value that Env and EnvOrDefault panic with for a type they cannot parse.
ErrUnsupportedType = internal.ErrUnsupportedType
)

// Defaults for the options that were not passed.
Expand All @@ -78,18 +93,33 @@ const (
defaultTimeLayout = time.RFC3339
)

// Parsable is a constraint for the types that Env and EnvOrDefault can parse.
// Parsable is a constraint for the built-in types that Env and EnvOrDefault can parse.
// The list of supported types is in the package documentation.
type Parsable = internal.EnvParsable

// EnvParser is implemented by custom types that parse themselves from an environment variable.
// ParseEnv is called on the zero value of T, so it needs a value receiver, unless T is a pointer type.
//
// Implementing EnvParser is checked at run time.
// To check it at compile time, assign a value of the type to an EnvParser variable:
//
// var _ getenv.EnvParser[Level] = Level(0)
type EnvParser[T EnvParser[T]] interface {
ParseEnv(raw string) (T, error)
}

// 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) {
// Env panics if T is not supported (see the package documentation), even when the variable is not set.
func Env[T any](key string, options ...option.Option) (T, error) {
var zero T

raw, ok := os.LookupEnv(key)
if !ok || raw == "" {
// An unsupported T is reported even when there is nothing to parse.
internal.MustSupport[T]()

return zero, fmt.Errorf("failed to get environment variable[%s]: %w", key, ErrNotSet)
}

Expand All @@ -105,7 +135,8 @@ 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 {
// EnvOrDefault panics if T is not supported, like Env.
func EnvOrDefault[T any](key string, defaultVal T, options ...option.Option) T {
val, err := Env[T](key, options...)
if err != nil {
return defaultVal
Expand Down
Loading