diff options
Diffstat (limited to 'README.md')
| -rw-r--r-- | README.md | 205 |
1 files changed, 161 insertions, 44 deletions
@@ -1,76 +1,193 @@ # Envelope -<p> - <a href="https://godoc.org/github.com/eugenetriguba/envelope"> - <img src="https://godoc.org/github.com/eugenetriguba/envelope?status.svg" alt="GoDoc"> - </a> - <a href="https://goreportcard.com/report/github.com/eugenetriguba/envelope"> - <img src="https://goreportcard.com/badge/github.com/eugenetriguba/envelope" alt="Go Report Card Badge"> - </a> - <a href="https://codecov.io/github/eugenetriguba/envelope"> - <img src="https://codecov.io/gh/eugenetriguba/envelope/graph/badge.svg?token=1nxWoiXv66"/> - </a> - <img alt="Version Badge" src="https://img.shields.io/badge/version-0.1.0-blue" style="max-width:100%;"> -</p> - -Envelope is a Go library that enables populating Go structs from environment variables. +[](https://godoc.org/git.sr.ht/~eugenetriguba/envelope) +[](https://goreportcard.com/report/git.sr.ht/~eugenetriguba/envelope) -## Installation +Envelope is a Go library that makes it easy to populate Go structs from environment variables. -To install Envelope, use the following command: +## Installation ```bash -$ go get github.com/eugenetriguba/envelope +go get git.sr.ht/~eugenetriguba/envelope ``` -## Usage - -Envelope supports the following types to load environment variables into for a Go struct: -- `string` -- `bool` -- `float32`, `float64` -- `int`, `int8`, `int16`, `int32`, `int64` -- `uint`, `uint8`, `uint16`, `uint32`, `uint64` - -Given a struct with compatible types, we can use `LoadFromEnv` to populate the struct. +## Quick Start -`main.go` ```go package main import ( "fmt" - "os" + "log" + "time" - "github.com/eugenetriguba/envelope" + "git.sr.ht/~eugenetriguba/envelope" ) -type ExampleStruct struct { - Field string `env:"EXAMPLE_FIELD"` +type Config struct { + Host string `env:"HOST"` + Port int `env:"PORT"` + Debug bool `env:"DEBUG"` + Timeout time.Duration `env:"TIMEOUT"` + Database DatabaseConfig `env:"DB"` +} + +type DatabaseConfig struct { + URL string `env:"URL"` + Username string `env:"USERNAME"` + Password string `env:"PASSWORD"` } func main() { - var example ExampleStruct - err := envelope.LoadFromEnv(&example) - if err != nil { - fmt.Errorf("%w\n", err) - os.Exit(1) + var config Config + if err := envelope.LoadFromEnv(&config); err != nil { + log.Fatalf("Failed to load configuration: %v", err) } - fmt.Printf("Field value: %s\n", example.Field) + + fmt.Printf("Configuration: %+v\n", config) +} +``` + +Run it with: + +```bash +export HOST=localhost +export PORT=8080 +export DEBUG=true +export TIMEOUT=5s +export DB_URL=postgres://localhost:5432/mydb +export DB_USERNAME=admin +export DB_PASSWORD=secret +go run main.go +``` + +Output: +``` +Configuration: {Host:localhost Port:8080 Debug:true Timeout:5s Database:{URL:postgres://localhost:5432/mydb Username:admin Password:secret}} +``` + +## Tutorial + +### Basic Usage + +Envelope uses struct tags to map environment variables to struct fields. The tag name is `env`. + +```go +type ServerConfig struct { + Host string `env:"HOST"` + Port int `env:"PORT"` +} +``` + +When `LoadFromEnv` is used on `ServerConfig`, it will look for environment variables named `HOST` and +`PORT` and attempt to parse them into the appropriate types. + +### Supported Types + +Envelope supports these types out of the box: + +- String: `string` +- Boolean: `bool` +- Integer: `int`, `int8`, `int16`, `int32`, `int64` +- Unsigned integer: `uint`, `uint8`, `uint16`, `uint32`, `uint64` +- Floating point: `float32`, `float64` +- Time: `time.Time` (RFC3339 format) +- Duration: `time.Duration` (e.g., "5s", "1h30m") +- IP address: `net.IP` +- IP network: `net.IPNet` (CIDR notation) +- URL: `url.URL` +- String slices: `[]string` (comma-separated) +- Integer slices: `[]int` (comma-separated) + +### Nested Structs + +Envelope supports nested structs with automatic prefixing of environment variables: + +```go +type DatabaseConfig struct { + URL string `env:"URL"` + Username string `env:"USERNAME"` + Password string `env:"PASSWORD"` } + +type AppConfig struct { + Database DatabaseConfig `env:"DB"` + LogLevel string `env:"LOG_LEVEL"` +} + +// LoadFromEnv will look for: +// - DB_URL +// - DB_USERNAME +// - DB_PASSWORD +// - LOG_LEVEL ``` -Now, we can run the program to see what `Field` is set to: +If you don't want prefixing for a nested struct, omit the `env` tag on that field: +```go +type AppConfig struct { + Database DatabaseConfig // No env tag + LogLevel string `env:"LOG_LEVEL"` +} + +// This will look for: +// - URL +// - USERNAME +// - PASSWORD +// - LOG_LEVEL ``` -$ go run main.go -Field value: + +### Custom Type Parsers + +You can register custom parsers for your own types: + +```go +type CustomType struct { + Value string +} + +envelope.RegisterTypeParser(reflect.TypeOf(CustomType{}), envelope.TypeParserFunc( + func(value string) (any, error) { + return CustomType{Value: value}, nil + }, +)) + +// Now envelope can parse environment variables into CustomType fields ``` -When we run it without an environment variable set, we can see it is the default Go value for that type (in this case, an empty string). However, when we set the `EXAMPLE_FIELD` environment variable, we can see the struct's `Field` field has the value set as expected: +Furthermore, you can override the default supported type parsers by registering +your own instead. +```go +envelope.RegisterTypeParser(reflect.TypeOf(time.Time{}), envelope.TypeParserFunc( + func(value string) (any, error) { + return time.Parse("01-02-2006", value) + }, +)) + +// Now time.Time fields will be parsed using MM-DD-YYYY format +// instead of the default RFC3339 format ``` -$ EXAMPLE_FIELD=123 go run main.go -Field value: 123 + +### Error Handling + +Envelope may return the following errors from `LoadFromEnv`: + +- `NotPointerToStructError`: When the input is not a pointer to a struct +- `UnsupportedTypeError`: When a field has a type that's not supported +- `ParseError`: When a value couldn't be parsed into the target type + +Errors can be checked using Go's standard `errors.As()`: + +```go +err := envelope.LoadFromEnv(&config) +var parseErr *envelope.ParseError +if errors.As(err, &parseErr) { + fmt.Printf("Failed to parse %s from environment variable %s into %v\n", + parseErr.Value, parseErr.EnvName, parseErr.TargetType) +} ``` +## Reference Documentation + +For the full API documentation, see the [GoDoc](https://godoc.org/git.sr.ht/~eugenetriguba/envelope). |