aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEugene Triguba <eugenetriguba@gmail.com>2025-07-19 16:59:53 -0400
committerEugene Triguba <eugenetriguba@gmail.com>2025-07-19 16:59:53 -0400
commit566b9f7fde255a2307113f6b6fdf0979751ecc83 (patch)
treee53935076e2c856f33011ffb2fa1004d05b447ab
parentAdd .DS_Store to gitignore (diff)
downloadenvelope-566b9f7fde255a2307113f6b6fdf0979751ecc83.zip
Add support for nested structs and additional types
-rw-r--r--.gitignore5
-rw-r--r--CHANGELOG.md27
-rw-r--r--README.md205
-rw-r--r--doc.go13
-rw-r--r--env.go154
-rw-r--r--env_test.go305
-rw-r--r--errors.go96
-rw-r--r--errors_test.go80
-rw-r--r--go.mod4
-rw-r--r--go.sum4
-rw-r--r--parsers.go251
-rw-r--r--parsers_test.go436
12 files changed, 1437 insertions, 143 deletions
diff --git a/.gitignore b/.gitignore
index a90471d..c22da67 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,8 @@
-.git
+# Editors
/tags
# macOS
.DS_Store
+
+# Go
+/coverage.out
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 86f903e..cf6f86d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,33 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.2.0] - 2025-07-19
+
+### Added
+- Support for nested struct handling
+ - Structs within structs are now processed recursively, allowing for nested configuration
+ - A parent struct field with an `env` tag acts as a prefix for all fields in its nested struct
+ - When a parent has no `env` tag, nested fields are accessed without prefixing
+- Custom error types
+ - `NotPointerToStructError`: When input is not a pointer to a struct
+ - `UnsupportedTypeError`: When a field type cannot be parsed
+ - `ParseError`: When a value cannot be parsed into the target type
+- Support for additional standard library types:
+ - `time.Duration`
+ - `net.IP` and `net.IPNet` (CIDR notation)
+ - `url.URL`
+ - `[]string` and `[]int` slices with comma-separated values
+- Extensible type parser system
+ - `RegisterTypeParser` function to register parsers for custom types
+ - Ability to override default parsers for built-in types
+
+### Changed
+- Improved error messages with more context about failure points
+
+### Fixed
+- Boolean parsing now supports additional formats (on/off, yes/no, y/n)
+- Proper handling of unexported fields in structs
+
## [0.1.0] - 2024-08-31
- Initial Release
diff --git a/README.md b/README.md
index 13c9bf5..d076a4d 100644
--- a/README.md
+++ b/README.md
@@ -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.
+[![GoDoc](https://godoc.org/git.sr.ht/~eugenetriguba/envelope?status.svg)](https://godoc.org/git.sr.ht/~eugenetriguba/envelope)
+[![Go Report Card](https://goreportcard.com/badge/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).
diff --git a/doc.go b/doc.go
index 834d87a..1a9f0c1 100644
--- a/doc.go
+++ b/doc.go
@@ -1,3 +1,12 @@
-// Envelope is a library designed to enable easily populating a Go struct
-// based on environment variables.
+// Envelope provides functionality to populate Go structs from environment variables.
+//
+// The main function, LoadFromEnv, takes a pointer to a struct and looks for fields
+// with the `env` tag. It then attempts to load the corresponding environment variables
+// and parse them into the appropriate types.
+//
+// This package supports a wide range of built-in types and allows for extension through
+// custom type parsers. It also handles nested structs, with the parent field's `env` tag
+// serving as a prefix for all fields in the nested struct.
+//
+// See the documentation for LoadFromEnv for more details and examples.
package envelope
diff --git a/env.go b/env.go
index 5de9148..4d7e273 100644
--- a/env.go
+++ b/env.go
@@ -1,72 +1,142 @@
package envelope
import (
- "fmt"
"os"
"reflect"
- "strconv"
)
-func LoadFromEnv(ptr interface{}) error {
+// LoadFromEnv populates a struct with values from environment variables.
+//
+// The function takes a pointer to a struct and looks for fields with the `env` tag.
+// For each field with an `env` tag, it attempts to load the corresponding environment
+// variable and parse it into the field's type.
+//
+// Supported types include:
+// - string
+// - bool
+// - int, int8, int16, int32, int64
+// - uint, uint8, uint16, uint32, uint64
+// - float32, float64
+// - time.Time (RFC3339 format)
+// - time.Duration
+// - net.IP
+// - net.IPNet (CIDR notation)
+// - url.URL
+// - []string, []int (comma-separated)
+// - Nested structs
+// - Custom types (via registered type parsers)
+//
+// For nested structs, the parent field's `env` tag is used as a prefix for all fields
+// in the nested struct. If the parent field doesn't have an `env` tag, no prefix is added.
+//
+// You can override the default parsers or add support for custom types using
+// RegisterTypeParser. This allows you to customize how environment variable values
+// are converted to specific types, including the built-in types.
+//
+// Example:
+//
+// type Config struct {
+// Host string `env:"HOST"`
+// Port int `env:"PORT"`
+// Timeout time.Duration `env:"TIMEOUT"`
+// Server struct {
+// MaxConns int `env:"MAX_CONNS"`
+// } `env:"SERVER"`
+// }
+//
+// // This would look for environment variables:
+// // HOST, PORT, TIMEOUT, SERVER_MAX_CONNS
+//
+// Returns an error if the input is not a pointer to a struct, or if any value
+// cannot be parsed into the corresponding field type.
+func LoadFromEnv(ptr any) error {
v := reflect.ValueOf(ptr)
if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
- return fmt.Errorf("ptr must be a pointer to a struct")
+ return newNotPointerToStructError(v.Type())
}
v = v.Elem()
- t := v.Type()
+ return loadStructFromEnv(v, "")
+}
- for i := 0; i < t.NumField(); i++ {
+func loadStructFromEnv(v reflect.Value, prefix string) error {
+ t := v.Type()
+ for i := range t.NumField() {
field := t.Field(i)
fieldValue := v.Field(i)
- envName := field.Tag.Get("env")
- if envName == "" {
- continue // Skip if the tag isn't set.
+ if !fieldValue.CanSet() {
+ continue
}
- envValue := os.Getenv(envName)
- if envValue == "" {
- continue // Skip if the environment variable is not set.
+ if fieldValue.Kind() == reflect.Struct {
+ if _, hasParser := typeParserRegistry[fieldValue.Type()]; !hasParser {
+ if err := loadNestedStructFromEnv(fieldValue, field, prefix); err != nil {
+ return err
+ }
+ continue
+ }
}
- if err := setFieldValue(fieldValue, envValue); err != nil {
- return fmt.Errorf("error while setting field %s from environment variable %s: %w", field.Name, envName, err)
+ envTag := field.Tag.Get("env")
+ if envTag == "" {
+ continue
+ }
+ if err := loadFieldFromEnv(fieldValue, field, envTag, prefix); err != nil {
+ return err
}
}
return nil
}
-func setFieldValue(field reflect.Value, value string) error {
- switch field.Kind() {
- case reflect.String:
- field.SetString(value)
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- intValue, err := strconv.ParseInt(value, 10, 64)
- if err != nil {
- return fmt.Errorf("unable to parse %s as an integer: %w", value, err)
+func loadNestedStructFromEnv(fieldValue reflect.Value, field reflect.StructField, parentPrefix string) error {
+ // For nested structs, they can have 'env' struct tags
+ // that indicate a prefix for their nested fields when
+ // parsing them.
+ //
+ // e.g. if the parent struct has a tag of "USER" and it
+ // has an inner field with a tag of "NAME", the environment
+ // variable would be "USER_NAME".
+ var nestedPrefix string
+ envTag := field.Tag.Get("env")
+ if envTag != "" {
+ if parentPrefix != "" {
+ nestedPrefix = parentPrefix + "_" + envTag
+ } else {
+ nestedPrefix = envTag
}
- field.SetInt(intValue)
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- uintValue, err := strconv.ParseUint(value, 10, 64)
- if err != nil {
- return fmt.Errorf("unable to parse %s as an unsigned integer: %w", value, err)
- }
- field.SetUint(uintValue)
- case reflect.Bool:
- boolValue, err := strconv.ParseBool(value)
- if err != nil {
- return fmt.Errorf("unable to parse %s as an boolean: %w", value, err)
- }
- field.SetBool(boolValue)
- case reflect.Float32, reflect.Float64:
- floatValue, err := strconv.ParseFloat(value, 64)
+ } else {
+ nestedPrefix = parentPrefix
+ }
+
+ return loadStructFromEnv(fieldValue, nestedPrefix)
+}
+
+func loadFieldFromEnv(fieldValue reflect.Value, field reflect.StructField, envTag string, prefix string) error {
+ envName := buildEnvVarName(envTag, prefix)
+ envValue := os.Getenv(envName)
+ if envValue == "" {
+ return nil
+ }
+ return parseAndSetFieldValue(fieldValue, field, envValue, envName)
+}
+
+func buildEnvVarName(envTag string, prefix string) string {
+ if prefix != "" {
+ return prefix + "_" + envTag
+ }
+ return envTag
+}
+
+func parseAndSetFieldValue(fieldValue reflect.Value, field reflect.StructField, envValue string, envName string) error {
+ if parser, exists := typeParserRegistry[fieldValue.Type()]; exists {
+ val, err := parser.Parse(envValue)
if err != nil {
- return fmt.Errorf("unable to parse %s as an float: %w", value, err)
+ return newParseError(field.Name, envName, envValue, fieldValue.Type(), err)
}
- field.SetFloat(floatValue)
- default:
- return fmt.Errorf("unsupported field type: %s", field.Kind())
+ fieldValue.Set(reflect.ValueOf(val))
+ return nil
}
- return nil
+
+ return newUnsupportedTypeError(field.Name, fieldValue.Type())
}
diff --git a/env_test.go b/env_test.go
index 4009b59..984ef2a 100644
--- a/env_test.go
+++ b/env_test.go
@@ -1,12 +1,14 @@
package envelope
import (
+ "errors"
+ "fmt"
"os"
+ "reflect"
"testing"
- "time"
- "github.com/eugenetriguba/checkmate/assert"
- "github.com/eugenetriguba/checkmate/check"
+ "git.sr.ht/~eugenetriguba/checkmate/assert"
+ "git.sr.ht/~eugenetriguba/checkmate/check"
)
type TestStruct struct {
@@ -16,15 +18,20 @@ type TestStruct struct {
Bool bool `env:"TEST_BOOL"`
Float float64 `env:"TEST_FLOAT"`
Untagged string
- Unexported string `env:"TEST_UNEXPORTED"`
+ unexported string `env:"TEST_UNEXPORTED"`
}
+// GIVEN a struct with environment variables set for its tagged fields
+// WHEN we call LoadFromEnv with a pointer to that struct
+// THEN it should load all the values from environment variables
+// into the struct fields
func TestLoadFromEnv(t *testing.T) {
os.Setenv("TEST_STRING", "hello")
os.Setenv("TEST_INT", "-42")
os.Setenv("TEST_UINT", "42")
os.Setenv("TEST_BOOL", "true")
os.Setenv("TEST_FLOAT", "3.14")
+ os.Setenv("TEST_UNEXPORTED", "unexported")
defer func() {
os.Unsetenv("TEST_STRING")
@@ -45,79 +52,277 @@ func TestLoadFromEnv(t *testing.T) {
check.True(t, ts.Bool)
check.Equal(t, ts.Float, 3.14)
check.Equal(t, ts.Untagged, "")
- check.Equal(t, ts.Unexported, "")
+ check.Equal(t, ts.unexported, "")
}
-func TestLoadFromEnvErrors(t *testing.T) {
+// GIVEN the string "not a pointer"
+// WHEN we call LoadFromEnv with the string
+// THEN it should return a NotPointerToStructError
+func TestLoadFromEnvWithNonPointerToStruct(t *testing.T) {
+ var notPtrToStructErr *NotPointerToStructError
+ value := "not a pointer"
+
+ err := LoadFromEnv(value)
+ assert.True(t, errors.As(err, &notPtrToStructErr))
+ assert.Equal(t, reflect.TypeOf(""), notPtrToStructErr.ActualType)
+ assert.Equal(t, "value must be a pointer to a struct", notPtrToStructErr.Error())
+
+ err = LoadFromEnv(&value)
+ assert.True(t, errors.As(err, &notPtrToStructErr))
+ assert.Equal(t, reflect.TypeOf(""), notPtrToStructErr.ActualType.Elem())
+}
+
+// GIVEN an unsupported type in a struct
+// WHEN we call LoadFromEnv with that struct
+// THEN it should return an UnsupportedTypeError
+func TestLoadFromEnvWithUnsupportedType(t *testing.T) {
+ type StructWithUnsupportedType struct {
+ Complex complex128 `env:"COMPLEX"`
+ }
+ os.Setenv("COMPLEX", "1+2i")
+ defer os.Unsetenv("COMPLEX")
+
+ err := LoadFromEnv(&StructWithUnsupportedType{})
+
+ var unsupportedErr *UnsupportedTypeError
+ assert.True(t, errors.As(err, &unsupportedErr))
+ assert.Equal(t, "Complex", unsupportedErr.FieldName)
+ assert.Equal(t, reflect.TypeOf(complex128(0)), unsupportedErr.FieldType)
+}
+
+// GIVEN invalid values for different types in environment variables
+// WHEN we call LoadFromEnv with those values
+// THEN it should return a ParseError with the correct field name, env name,
+// value, and target type
+func TestLoadFromEnvParseErrors(t *testing.T) {
tests := []struct {
- name string
- input interface{}
- envVars map[string]string
- expectedErr string
+ name string
+ envName string
+ envValue string
+ input any
+ fieldName string
+ targetType reflect.Type
}{
{
- name: "Non-pointer input",
- input: TestStruct{},
- expectedErr: "ptr must be a pointer to a struct",
- },
- {
- name: "Pointer to non-struct",
- input: new(string),
- expectedErr: "ptr must be a pointer to a struct",
- },
- {
- name: "Invalid int",
- input: &struct {
- Int int `env:"TEST_INT"`
- }{},
- envVars: map[string]string{"TEST_INT": "not an int"},
- expectedErr: "error while setting field Int from environment variable TEST_INT",
- },
- {
- name: "Invalid uint",
+ name: "Invalid int",
+ envName: "TEST_INT",
+ envValue: "not-an-int",
input: &struct {
- Uint uint `env:"TEST_UINT"`
+ Value int `env:"TEST_INT"`
}{},
- envVars: map[string]string{"TEST_UINT": "-42"},
- expectedErr: "error while setting field Uint from environment variable TEST_UINT",
+ fieldName: "Value",
+ targetType: reflect.TypeOf(int(0)),
},
{
- name: "Invalid bool",
+ name: "Invalid uint (negative)",
+ envName: "TEST_UINT",
+ envValue: "-42",
input: &struct {
- Bool bool `env:"TEST_BOOL"`
+ Value uint `env:"TEST_UINT"`
}{},
- envVars: map[string]string{"TEST_BOOL": "not a bool"},
- expectedErr: "error while setting field Bool from environment variable TEST_BOOL",
+ fieldName: "Value",
+ targetType: reflect.TypeOf(uint(0)),
},
{
- name: "Invalid float",
+ name: "Invalid bool",
+ envName: "TEST_BOOL",
+ envValue: "not-a-bool",
input: &struct {
- Float float64 `env:"TEST_FLOAT"`
+ Value bool `env:"TEST_BOOL"`
}{},
- envVars: map[string]string{"TEST_FLOAT": "not a float"},
- expectedErr: "error while setting field Float from environment variable TEST_FLOAT",
+ fieldName: "Value",
+ targetType: reflect.TypeOf(bool(false)),
},
{
- name: "Unsupported type",
+ name: "Invalid float",
+ envName: "TEST_FLOAT",
+ envValue: "not-a-float",
input: &struct {
- Unsupported time.Time `env:"TEST_UNSUPPORTED"`
+ Value float64 `env:"TEST_FLOAT"`
}{},
- envVars: map[string]string{"TEST_UNSUPPORTED": "2023-08-31T12:34:56Z"},
- expectedErr: "error while setting field Unsupported from environment variable TEST_UNSUPPORTED",
+ fieldName: "Value",
+ targetType: reflect.TypeOf(float64(0)),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- for k, v := range tt.envVars {
- os.Setenv(k, v)
- defer os.Unsetenv(k)
- }
+ os.Setenv(tt.envName, tt.envValue)
+ defer os.Unsetenv(tt.envName)
err := LoadFromEnv(tt.input)
- assert.NotNil(t, err)
- assert.ErrorContains(t, err, tt.expectedErr)
+ var parseErr *ParseError
+ assert.True(t, errors.As(err, &parseErr))
+
+ assert.Equal(t, tt.fieldName, parseErr.FieldName)
+ assert.Equal(t, tt.envName, parseErr.EnvName)
+ assert.Equal(t, tt.envValue, parseErr.Value)
+ assert.Equal(t, tt.targetType, parseErr.TargetType)
+
+ assert.ErrorContains(t, err,
+ fmt.Sprintf("error parsing value '%s' to '%v' for field '%s' from environment variable '%s'",
+ tt.envValue, tt.targetType, tt.fieldName, tt.envName))
})
}
}
+
+// GIVEN a struct with nested structs and a prefix
+// for the parent struct
+// WHEN we call LoadFromEnv with that struct
+// THEN we expect it to load all nested fields correctly
+func TestNestedStructs(t *testing.T) {
+ type ServerConfig struct {
+ Host string `env:"HOST"`
+ Port int `env:"PORT"`
+ }
+ type DatabaseConfig struct {
+ URL string `env:"URL"`
+ Username string `env:"USERNAME"`
+ Password string `env:"PASSWORD"`
+ }
+ type AppConfig struct {
+ Server ServerConfig `env:"SERVER"`
+ Database DatabaseConfig `env:"DB"`
+ LogLevel string `env:"LOG_LEVEL"`
+ }
+ os.Setenv("SERVER_HOST", "localhost")
+ os.Setenv("SERVER_PORT", "8080")
+ os.Setenv("DB_URL", "postgres://localhost:5432/mydb")
+ os.Setenv("DB_USERNAME", "admin")
+ os.Setenv("DB_PASSWORD", "secret")
+ os.Setenv("LOG_LEVEL", "debug")
+ defer func() {
+ os.Unsetenv("SERVER_HOST")
+ os.Unsetenv("SERVER_PORT")
+ os.Unsetenv("DB_URL")
+ os.Unsetenv("DB_USERNAME")
+ os.Unsetenv("DB_PASSWORD")
+ os.Unsetenv("LOG_LEVEL")
+ }()
+
+ var config AppConfig
+ err := LoadFromEnv(&config)
+
+ check.Nil(t, err)
+ check.Equal(t, "localhost", config.Server.Host)
+ check.Equal(t, 8080, config.Server.Port)
+ check.Equal(t, "postgres://localhost:5432/mydb", config.Database.URL)
+ check.Equal(t, "admin", config.Database.Username)
+ check.Equal(t, "secret", config.Database.Password)
+ check.Equal(t, "debug", config.LogLevel)
+}
+
+// GIVEN a multi-level nested struct with prefixes
+// WHEN we call LoadFromEnv with that struct
+// THEN it should load all nested fields correctly
+func TestDeepNestedStructs(t *testing.T) {
+ type DeepestConfig struct {
+ Value string `env:"VALUE"`
+ }
+ type MiddleConfig struct {
+ Inner DeepestConfig `env:"INNER"`
+ Setting bool `env:"SETTING"`
+ }
+ type RootConfig struct {
+ Middle MiddleConfig `env:"MIDDLE"`
+ Name string `env:"NAME"`
+ }
+ os.Setenv("MIDDLE_INNER_VALUE", "deeply_nested_value")
+ os.Setenv("MIDDLE_SETTING", "true")
+ os.Setenv("NAME", "root_name")
+ defer func() {
+ os.Unsetenv("MIDDLE_INNER_VALUE")
+ os.Unsetenv("MIDDLE_SETTING")
+ os.Unsetenv("NAME")
+ }()
+
+ var config RootConfig
+ err := LoadFromEnv(&config)
+
+ check.Nil(t, err)
+ check.Equal(t, "deeply_nested_value", config.Middle.Inner.Value)
+ check.Equal(t, true, config.Middle.Setting)
+ check.Equal(t, "root_name", config.Name)
+}
+
+// GIVEN structs that do not have all environments variables
+// set to populate them fully
+// WHEN we call LoadFromEnv with those structs
+// THEN it should load only the set fields and leave others at their zero values
+func TestPartialNestedStructs(t *testing.T) {
+ type ServerConfig struct {
+ Host string `env:"HOST"`
+ Port int `env:"PORT"`
+ Timeout int `env:"TIMEOUT"` // Missing cooresponding environment variable
+ }
+ type AppConfig struct {
+ Server ServerConfig `env:"SERVER"`
+ LogLevel string `env:"LOG_LEVEL"`
+ Debug bool `env:"DEBUG"` // Missing cooresponding environment variable
+ }
+ os.Setenv("SERVER_HOST", "localhost")
+ os.Setenv("SERVER_PORT", "8080")
+ os.Setenv("LOG_LEVEL", "info")
+ defer func() {
+ os.Unsetenv("SERVER_HOST")
+ os.Unsetenv("SERVER_PORT")
+ os.Unsetenv("LOG_LEVEL")
+ }()
+
+ var config AppConfig
+ err := LoadFromEnv(&config)
+
+ check.Nil(t, err)
+ check.Equal(t, "localhost", config.Server.Host)
+ check.Equal(t, 8080, config.Server.Port)
+ check.Equal(t, 0, config.Server.Timeout) // Default 'zero' value
+ check.Equal(t, "info", config.LogLevel)
+ check.Equal(t, false, config.Debug) // Default 'zero' value
+}
+
+// GIVEN nested structs without any prefixes
+// WHEN we call LoadFromEnv with those structs
+// THEN it should load the fields correctly without using prefixes
+// WHEN we call LoadFromEnv with a struct that has prefixes
+// THEN it should ignore the prefixes and load the fields correctly
+func TestNestedStructWithoutPrefix(t *testing.T) {
+ type ServerConfig struct {
+ Host string `env:"HOST"`
+ Port int `env:"PORT"`
+ }
+ type AppConfig struct {
+ Server ServerConfig
+ LogLevel string `env:"LOG_LEVEL"`
+ }
+ os.Setenv("HOST", "localhost")
+ os.Setenv("PORT", "8080")
+ os.Setenv("LOG_LEVEL", "debug")
+ defer func() {
+ os.Unsetenv("HOST")
+ os.Unsetenv("PORT")
+ os.Unsetenv("LOG_LEVEL")
+ }()
+
+ var config AppConfig
+ err := LoadFromEnv(&config)
+
+ check.Nil(t, err)
+ check.Equal(t, "localhost", config.Server.Host)
+ check.Equal(t, 8080, config.Server.Port)
+ check.Equal(t, "debug", config.LogLevel)
+
+ os.Setenv("SERVER_HOST", "wrong-host")
+ os.Setenv("SERVER_PORT", "9090")
+ defer func() {
+ os.Unsetenv("SERVER_HOST")
+ os.Unsetenv("SERVER_PORT")
+ }()
+
+ config = AppConfig{} // Reset
+ err = LoadFromEnv(&config)
+
+ check.Nil(t, err)
+ check.Equal(t, "localhost", config.Server.Host)
+ check.Equal(t, 8080, config.Server.Port)
+}
diff --git a/errors.go b/errors.go
new file mode 100644
index 0000000..cb356be
--- /dev/null
+++ b/errors.go
@@ -0,0 +1,96 @@
+package envelope
+
+import (
+ "fmt"
+ "reflect"
+)
+
+// BaseError represents the base error type for the envelope package
+type BaseError struct {
+ // Message is a human-readable error description
+ Message string
+ // Err is the underlying error, if any
+ Err error
+}
+
+func (e *BaseError) Error() string {
+ if e.Err != nil {
+ return fmt.Sprintf("%s: %v", e.Message, e.Err)
+ }
+ return e.Message
+}
+
+func (e *BaseError) Unwrap() error {
+ return e.Err
+}
+
+type NotPointerToStructError struct {
+ BaseError
+ ActualType reflect.Type
+}
+
+func (e *NotPointerToStructError) Error() string {
+ return e.Message
+}
+
+func newNotPointerToStructError(t reflect.Type) *NotPointerToStructError {
+ return &NotPointerToStructError{
+ BaseError: BaseError{
+ Message: "value must be a pointer to a struct",
+ },
+ ActualType: t,
+ }
+}
+
+// UnsupportedTypeError is returned when a field has a type that cannot be parsed
+type UnsupportedTypeError struct {
+ BaseError
+ // FieldName is the name of the field with the unsupported type
+ FieldName string
+ // FieldType is the unsupported type
+ FieldType reflect.Type
+}
+
+func (e *UnsupportedTypeError) Error() string {
+ return e.Message
+}
+
+func newUnsupportedTypeError(fieldName string, fieldType reflect.Type) *UnsupportedTypeError {
+ return &UnsupportedTypeError{
+ BaseError: BaseError{
+ Message: fmt.Sprintf("unsupported field type for field %s", fieldName),
+ },
+ FieldName: fieldName,
+ FieldType: fieldType,
+ }
+}
+
+// ParseError is returned when a value cannot be parsed into the desired type
+type ParseError struct {
+ BaseError
+ // FieldName is the name of the field being parsed
+ FieldName string
+ // EnvName is the name of the environment variable
+ EnvName string
+ // Value is the string value that could not be parsed
+ Value string
+ // TargetType is the type that the value could not be parsed into
+ TargetType reflect.Type
+}
+
+func (e *ParseError) Error() string {
+ return e.Message
+}
+
+func newParseError(fieldName string, envName string, value string, targetType reflect.Type, err error) *ParseError {
+ return &ParseError{
+ BaseError: BaseError{
+ Message: fmt.Sprintf("error parsing value '%s' to '%v' for field '%s' from environment variable '%s'", value, targetType, fieldName, envName),
+ Err: err,
+ },
+ FieldName: fieldName,
+ EnvName: envName,
+ Value: value,
+ TargetType: targetType,
+ }
+}
diff --git a/errors_test.go b/errors_test.go
new file mode 100644
index 0000000..fb739a0
--- /dev/null
+++ b/errors_test.go
@@ -0,0 +1,80 @@
+package envelope
+
+import (
+ "errors"
+ "reflect"
+ "testing"
+
+ "git.sr.ht/~eugenetriguba/checkmate/assert"
+ "git.sr.ht/~eugenetriguba/checkmate/check"
+)
+
+// GIVEN a BaseError
+// WHEN we call Error on it
+// THEN it should return the error message if there's no underlying error
+// or a formatted message including the underlying error when one exists
+func TestBaseError(t *testing.T) {
+ err := BaseError{
+ Message: "test error",
+ Err: nil,
+ }
+ check.Equal(t, err.Error(), err.Message)
+
+ err.Err = errors.New("underlying error")
+ check.Equal(t, err.Error(), "test error: underlying error")
+
+}
+
+// GIVEN a NotPointerToStructError
+// WHEN we create it with a non-pointer type
+// THEN it should:
+// - Return an error message indicating the value must be a pointer to a struct
+// - Be identifiable via errors.As
+// - Contain the actual type that was provided
+func TestNotPointerToStructError(t *testing.T) {
+ var s string
+ err := newNotPointerToStructError(reflect.TypeOf(s))
+ assert.Equal(t, "value must be a pointer to a struct", err.Error())
+
+ var notPtrErr *NotPointerToStructError
+ assert.NotNil(t, notPtrErr)
+ assert.True(t, errors.As(err, &notPtrErr))
+ assert.Equal(t, reflect.TypeOf(s), notPtrErr.ActualType)
+}
+
+// GIVEN an UnsupportedTypeError
+// WHEN we create it with a field name and type
+// THEN it should:
+// - Return an error message indicating the field type is unsupported
+// - Be identifiable via errors.As
+// - Contain the field name and type that caused the error
+func TestUnsupportedTypeError(t *testing.T) {
+ err := newUnsupportedTypeError("TestField", reflect.TypeOf(complex128(0)))
+ assert.Equal(t, "unsupported field type for field TestField", err.Error())
+
+ var typeErr *UnsupportedTypeError
+ assert.True(t, errors.As(err, &typeErr))
+ assert.Equal(t, "TestField", typeErr.FieldName)
+ assert.Equal(t, reflect.TypeOf(complex128(0)), typeErr.FieldType)
+}
+
+// GIVEN a ParseError created with field information and an underlying error
+// WHEN we examine its properties and behavior
+// THEN it should:
+// - Contain the correct error message with field and environment variable context
+// - Wrap the original error properly
+// - Provide access to its field name, environment variable name, value, and target type
+func TestParseError(t *testing.T) {
+ originalErr := errors.New("test error")
+ err := newParseError("TestField", "TEST_ENV", "invalid", reflect.TypeOf(int(0)), originalErr)
+ assert.ErrorContains(t, err, "error parsing value 'invalid' to 'int' for field 'TestField' from environment variable 'TEST_ENV'")
+
+ var parseErr *ParseError
+ assert.True(t, errors.As(err, &parseErr))
+ assert.Equal(t, "TestField", parseErr.FieldName)
+ assert.Equal(t, "TEST_ENV", parseErr.EnvName)
+ assert.Equal(t, "invalid", parseErr.Value)
+ assert.Equal(t, reflect.TypeOf(int(0)), parseErr.TargetType)
+
+ assert.True(t, errors.Is(err, originalErr))
+}
diff --git a/go.mod b/go.mod
index bc33ce0..00d81e6 100644
--- a/go.mod
+++ b/go.mod
@@ -1,7 +1,7 @@
-module github.com/eugenetriguba/envelope
+module git.sr.ht/~eugenetriguba/envelope
go 1.23.0
-require github.com/eugenetriguba/checkmate v0.3.2
+require git.sr.ht/~eugenetriguba/checkmate v0.3.3
require github.com/google/go-cmp v0.6.0 // indirect
diff --git a/go.sum b/go.sum
index 9ccb220..c66aafa 100644
--- a/go.sum
+++ b/go.sum
@@ -1,4 +1,4 @@
-github.com/eugenetriguba/checkmate v0.3.2 h1:vcALwpLLpt0FBxckjuobNFYtBLtlCT2p55Xk4p0SAhk=
-github.com/eugenetriguba/checkmate v0.3.2/go.mod h1:IY38Cl4zlNI1dg+wcDYwrbWZfJ9i2/ouWf8C0N8c/do=
+git.sr.ht/~eugenetriguba/checkmate v0.3.3 h1:5qEwiDLRVcaI4Z5LRpUQYz0CIsSA9OuWxFB9GBDRMrk=
+git.sr.ht/~eugenetriguba/checkmate v0.3.3/go.mod h1:Pxv1PKcBSbOqmoEOZxOBJVv9dHUGU+zcwuwfnGqZEQk=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
diff --git a/parsers.go b/parsers.go
new file mode 100644
index 0000000..eca2ebb
--- /dev/null
+++ b/parsers.go
@@ -0,0 +1,251 @@
+package envelope
+
+import (
+ "fmt"
+ "net"
+ "net/url"
+ "reflect"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// TypeParser defines an interface for custom type parsing of values
+// from environment variables
+type TypeParser interface {
+ // Parse converts a string value from an environment variable to a value
+ // that can be set on a struct field
+ Parse(value string) (any, error)
+}
+
+// TypeParserFunc is a function type that implements TypeParser
+type TypeParserFunc func(value string) (any, error)
+
+func (f TypeParserFunc) Parse(value string) (any, error) {
+ return f(value)
+}
+
+var typeParserRegistry = map[reflect.Type]TypeParser{}
+
+// RegisterTypeParser registers a custom type parser for a specific type.
+//
+// This allows you to extend the LoadFromEnv function to support additional types
+// beyond the built-in ones. The parser will be called when LoadFromEnv encounters
+// a field of the specified type.
+//
+// You can also use this function to override the default parsers for built-in types.
+// For example, you could register a custom time.Time parser that uses a different
+// date format than the default RFC3339.
+//
+// Example:
+//
+// // Register a custom parser for UserID type
+// type UserID int64
+//
+// RegisterTypeParser(reflect.TypeOf(UserID(0)), TypeParserFunc(func(value string) (any, error) {
+// id, err := strconv.ParseInt(value, 10, 64)
+// if err != nil {
+// return nil, err
+// }
+// return UserID(id), nil
+// }))
+//
+// // Override the default time.Time parser to use a custom format
+// RegisterTypeParser(reflect.TypeOf(time.Time{}), TypeParserFunc(func(value string) (any, error) {
+// return time.Parse("2006-01-02", value)
+// }))
+func RegisterTypeParser(t reflect.Type, parser TypeParser) {
+ typeParserRegistry[t] = parser
+}
+
+func init() {
+ // String parser
+ RegisterTypeParser(reflect.TypeOf(""), TypeParserFunc(func(value string) (any, error) {
+ return value, nil
+ }))
+
+ // Int parsers
+ RegisterTypeParser(reflect.TypeOf(int(0)), TypeParserFunc(func(value string) (any, error) {
+ i, err := strconv.ParseInt(value, 10, 0)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as an integer: %w", value, err)
+ }
+ return int(i), nil
+ }))
+
+ RegisterTypeParser(reflect.TypeOf(int8(0)), TypeParserFunc(func(value string) (any, error) {
+ i, err := strconv.ParseInt(value, 10, 8)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as an int8: %w", value, err)
+ }
+ return int8(i), nil
+ }))
+
+ RegisterTypeParser(reflect.TypeOf(int16(0)), TypeParserFunc(func(value string) (any, error) {
+ i, err := strconv.ParseInt(value, 10, 16)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as an int16: %w", value, err)
+ }
+ return int16(i), nil
+ }))
+
+ RegisterTypeParser(reflect.TypeOf(int32(0)), TypeParserFunc(func(value string) (any, error) {
+ i, err := strconv.ParseInt(value, 10, 32)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as an int32: %w", value, err)
+ }
+ return int32(i), nil
+ }))
+
+ RegisterTypeParser(reflect.TypeOf(int64(0)), TypeParserFunc(func(value string) (any, error) {
+ i, err := strconv.ParseInt(value, 10, 64)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as an int64: %w", value, err)
+ }
+ return i, nil
+ }))
+
+ // Uint parsers
+ RegisterTypeParser(reflect.TypeOf(uint(0)), TypeParserFunc(func(value string) (any, error) {
+ i, err := strconv.ParseUint(value, 10, 0)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as a uint: %w", value, err)
+ }
+ return uint(i), nil
+ }))
+
+ RegisterTypeParser(reflect.TypeOf(uint8(0)), TypeParserFunc(func(value string) (any, error) {
+ i, err := strconv.ParseUint(value, 10, 8)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as a uint8: %w", value, err)
+ }
+ return uint8(i), nil
+ }))
+
+ RegisterTypeParser(reflect.TypeOf(uint16(0)), TypeParserFunc(func(value string) (any, error) {
+ i, err := strconv.ParseUint(value, 10, 16)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as a uint16: %w", value, err)
+ }
+ return uint16(i), nil
+ }))
+
+ RegisterTypeParser(reflect.TypeOf(uint32(0)), TypeParserFunc(func(value string) (any, error) {
+ i, err := strconv.ParseUint(value, 10, 32)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as a uint32: %w", value, err)
+ }
+ return uint32(i), nil
+ }))
+
+ RegisterTypeParser(reflect.TypeOf(uint64(0)), TypeParserFunc(func(value string) (any, error) {
+ i, err := strconv.ParseUint(value, 10, 64)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as a uint64: %w", value, err)
+ }
+ return uint64(i), nil
+ }))
+
+ // Bool parser
+ RegisterTypeParser(reflect.TypeOf(bool(false)), TypeParserFunc(func(value string) (any, error) {
+ lower := strings.ToLower(value)
+ if lower == "on" || lower == "yes" || lower == "y" {
+ return true, nil
+ } else if lower == "off" || lower == "no" || lower == "n" {
+ return false, nil
+ }
+ b, err := strconv.ParseBool(value)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as a bool: %w", value, err)
+ }
+ return b, nil
+ }))
+
+ // Float parsers
+ RegisterTypeParser(reflect.TypeOf(float32(0)), TypeParserFunc(func(value string) (any, error) {
+ f, err := strconv.ParseFloat(value, 32)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as a float32: %w", value, err)
+ }
+ return float32(f), nil
+ }))
+
+ RegisterTypeParser(reflect.TypeOf(float64(0)), TypeParserFunc(func(value string) (any, error) {
+ f, err := strconv.ParseFloat(value, 64)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as a float64: %w", value, err)
+ }
+ return f, nil
+ }))
+
+ // Time.Time parser
+ RegisterTypeParser(reflect.TypeOf(time.Time{}), TypeParserFunc(func(value string) (any, error) {
+ t, err := time.Parse(time.RFC3339, value)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as time (RFC3339 format expected): %w", value, err)
+ }
+ return t, nil
+ }))
+
+ // time.Duration parser
+ RegisterTypeParser(reflect.TypeOf(time.Duration(0)), TypeParserFunc(func(value string) (any, error) {
+ d, err := time.ParseDuration(value)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as duration: %w", value, err)
+ }
+ return d, nil
+ }))
+
+ // net.IP parser
+ RegisterTypeParser(reflect.TypeOf(net.IP{}), TypeParserFunc(func(value string) (any, error) {
+ ip := net.ParseIP(value)
+ if ip == nil {
+ return nil, fmt.Errorf("unable to parse %s as IP address", value)
+ }
+ return ip, nil
+ }))
+
+ // net.IPNet parser (CIDR notation)
+ RegisterTypeParser(reflect.TypeOf(net.IPNet{}), TypeParserFunc(func(value string) (any, error) {
+ _, ipNet, err := net.ParseCIDR(value)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as CIDR: %w", value, err)
+ }
+ return *ipNet, nil
+ }))
+
+ // url.URL parser
+ RegisterTypeParser(reflect.TypeOf(url.URL{}), TypeParserFunc(func(value string) (any, error) {
+ u, err := url.Parse(value)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse %s as URL: %w", value, err)
+ }
+ return *u, nil
+ }))
+
+ // []string parser (comma separated)
+ RegisterTypeParser(reflect.TypeOf([]string{}), TypeParserFunc(func(value string) (any, error) {
+ if value == "" {
+ return []string{}, nil
+ }
+ return strings.Split(value, ","), nil
+ }))
+
+ // []int parser (comma separated)
+ RegisterTypeParser(reflect.TypeOf([]int{}), TypeParserFunc(func(value string) (any, error) {
+ if value == "" {
+ return []int{}, nil
+ }
+ parts := strings.Split(value, ",")
+ result := make([]int, 0, len(parts))
+ for _, part := range parts {
+ trimmed := strings.TrimSpace(part)
+ i, err := strconv.Atoi(trimmed)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse '%s' as int in comma-separated list: %w", trimmed, err)
+ }
+ result = append(result, i)
+ }
+ return result, nil
+ }))
+}
diff --git a/parsers_test.go b/parsers_test.go
new file mode 100644
index 0000000..1ea9299
--- /dev/null
+++ b/parsers_test.go
@@ -0,0 +1,436 @@
+package envelope
+
+import (
+ "net"
+ "net/url"
+ "reflect"
+ "testing"
+ "time"
+
+ "git.sr.ht/~eugenetriguba/checkmate/assert"
+)
+
+// GIVEN a string parser
+// WHEN we parse a string value
+// THEN it should return the string value as-is
+func TestStringParser(t *testing.T) {
+ parser := typeParserRegistry[reflect.TypeOf("")]
+
+ result, err := parser.Parse("test string")
+
+ assert.Nil(t, err)
+ assert.Equal(t, "test string", result)
+}
+
+// GIVEN various integer parsers
+// WHEN we parse string representations of integers
+// THEN it should return the correct integer type
+func TestIntParsers(t *testing.T) {
+ tests := []struct {
+ name string
+ typ reflect.Type
+ input string
+ expected any
+ }{
+ {
+ name: "int",
+ typ: reflect.TypeOf(int(0)),
+ input: "42",
+ expected: int(42),
+ },
+ {
+ name: "int8",
+ typ: reflect.TypeOf(int8(0)),
+ input: "42",
+ expected: int8(42),
+ },
+ {
+ name: "int16",
+ typ: reflect.TypeOf(int16(0)),
+ input: "42",
+ expected: int16(42),
+ },
+ {
+ name: "int32",
+ typ: reflect.TypeOf(int32(0)),
+ input: "42",
+ expected: int32(42),
+ },
+ {
+ name: "int64",
+ typ: reflect.TypeOf(int64(0)),
+ input: "42",
+ expected: int64(42),
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ parser := typeParserRegistry[tt.typ]
+
+ result, err := parser.Parse(tt.input)
+
+ assert.Nil(t, err)
+ assert.Equal(t, tt.expected, result)
+ })
+ }
+}
+
+// GIVEN various unsigned integer parsers
+// WHEN we parse string representations of integers
+// THEN it should return the correct unsigned integer type
+func TestUintParsers(t *testing.T) {
+ tests := []struct {
+ name string
+ typ reflect.Type
+ input string
+ expected any
+ }{
+ {
+ name: "uint",
+ typ: reflect.TypeOf(uint(0)),
+ input: "42",
+ expected: uint(42),
+ },
+ {
+ name: "uint8",
+ typ: reflect.TypeOf(uint8(0)),
+ input: "42",
+ expected: uint8(42),
+ },
+ {
+ name: "uint16",
+ typ: reflect.TypeOf(uint16(0)),
+ input: "42",
+ expected: uint16(42),
+ },
+ {
+ name: "uint32",
+ typ: reflect.TypeOf(uint32(0)),
+ input: "42",
+ expected: uint32(42),
+ },
+ {
+ name: "uint64",
+ typ: reflect.TypeOf(uint64(0)),
+ input: "42",
+ expected: uint64(42),
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ parser := typeParserRegistry[tt.typ]
+
+ result, err := parser.Parse(tt.input)
+
+ assert.Nil(t, err)
+ assert.Equal(t, tt.expected, result)
+ })
+ }
+}
+
+// GIVEN a boolean parser
+// WHEN we parse string representations of boolean values
+// THEN it should:
+// - Return true for various true-like values (true, TRUE, 1, on, yes, etc.)
+// - Return false for various false-like values (false, FALSE, 0, off, no, etc.)
+// - Return an error for invalid boolean values
+func TestBoolParser(t *testing.T) {
+ parser := typeParserRegistry[reflect.TypeOf(bool(false))]
+
+ for _, val := range []string{"true", "TRUE", "True", "1", "t", "T", "on", "ON", "yes", "YES", "y", "Y"} {
+ result, err := parser.Parse(val)
+ assert.Nil(t, err)
+ assert.Equal(t, true, result)
+ }
+
+ for _, val := range []string{"false", "FALSE", "False", "0", "f", "F", "off", "OFF", "no", "NO", "n", "N"} {
+ result, err := parser.Parse(val)
+ assert.Nil(t, err)
+ assert.Equal(t, false, result)
+ }
+
+ _, err := parser.Parse("not-a-bool")
+ assert.NotNil(t, err)
+}
+
+// GIVEN float parsers (float32, float64)
+// WHEN we parse string representations of floating point numbers
+// THEN it should return the correct float type with proper precision
+func TestFloatParsers(t *testing.T) {
+ tests := []struct {
+ name string
+ typ reflect.Type
+ input string
+ expected any
+ }{
+ {
+ name: "float32",
+ typ: reflect.TypeOf(float32(0)),
+ input: "3.14159",
+ expected: float32(3.14159),
+ },
+ {
+ name: "float64",
+ typ: reflect.TypeOf(float64(0)),
+ input: "3.14159265359",
+ expected: float64(3.14159265359),
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ parser := typeParserRegistry[tt.typ]
+ result, err := parser.Parse(tt.input)
+
+ assert.Nil(t, err)
+ assert.Equal(t, tt.expected, result)
+ })
+ }
+}
+
+// GIVEN a time.Time parser
+// WHEN we parse:
+// - A valid RFC3339 formatted time string
+// - An invalid time string
+//
+// THEN it should return the correct time.Time value or an error respectively
+func TestTimeParser(t *testing.T) {
+ parser := typeParserRegistry[reflect.TypeOf(time.Time{})]
+
+ result, err := parser.Parse("2023-08-31T12:34:56Z")
+ assert.Nil(t, err)
+ expected, _ := time.Parse(time.RFC3339, "2023-08-31T12:34:56Z")
+ assert.Equal(t, expected, result)
+
+ _, err = parser.Parse("not-a-time")
+ assert.NotNil(t, err)
+}
+
+// GIVEN a time.Duration parser
+// WHEN we parse various duration strings (5s, 1m30s, 1h, 24h)
+// THEN it should:
+// - Convert each string to the correct time.Duration value
+// - Return an error for invalid duration strings
+func TestDurationParser(t *testing.T) {
+ parser := typeParserRegistry[reflect.TypeOf(time.Duration(0))]
+
+ tests := []struct {
+ input string
+ expected time.Duration
+ }{
+ {"5s", 5 * time.Second},
+ {"1m30s", 90 * time.Second},
+ {"1h", time.Hour},
+ {"24h", 24 * time.Hour},
+ }
+ for _, tt := range tests {
+ result, err := parser.Parse(tt.input)
+ assert.Nil(t, err)
+ assert.Equal(t, tt.expected, result)
+ }
+
+ _, err := parser.Parse("not-a-duration")
+ assert.NotNil(t, err)
+}
+
+// GIVEN a net.IP parser
+// WHEN we parse various IP address formats (IPv4 and IPv6)
+// THEN it should:
+// - Correctly convert each string to a net.IP value
+// - Return an error for invalid IP addresses
+func TestIPParser(t *testing.T) {
+ parser := typeParserRegistry[reflect.TypeOf(net.IP{})]
+
+ tests := []string{
+ "192.168.1.1",
+ "127.0.0.1",
+ "::1",
+ "2001:db8::1",
+ }
+ for _, testip := range tests {
+ result, err := parser.Parse(testip)
+ assert.Nil(t, err)
+ ip, ok := result.(net.IP)
+ assert.True(t, ok)
+ assert.Equal(t, testip, ip.String())
+ }
+
+ _, err := parser.Parse("not-an-ip")
+ assert.NotNil(t, err)
+}
+
+// GIVEN a net.IPNet parser
+// WHEN we parse CIDR notation strings
+// THEN it should:
+// - Correctly convert each string to a net.IPNet value
+// - Return an error for invalid CIDR notations
+func TestIPNetParser(t *testing.T) {
+ parser := typeParserRegistry[reflect.TypeOf(net.IPNet{})]
+
+ tests := []string{
+ "192.168.1.0/24",
+ "10.0.0.0/8",
+ "2001:db8::/32",
+ }
+
+ for _, ipnet := range tests {
+ result, err := parser.Parse(ipnet)
+ assert.Nil(t, err)
+ ipNet, ok := result.(net.IPNet)
+ assert.True(t, ok)
+ assert.Equal(t, ipnet, ipNet.String())
+ }
+
+ _, err := parser.Parse("not-a-cidr")
+ assert.NotNil(t, err)
+}
+
+// GIVEN a url.URL parser
+// WHEN we parse URL strings
+// THEN it should:
+// - Correctly convert each string to a url.URL value
+// - Return an error for invalid URL strings
+func TestURLParser(t *testing.T) {
+ parser := typeParserRegistry[reflect.TypeOf(url.URL{})]
+
+ tests := []struct {
+ input string
+ expected string
+ }{
+ {"https://example.com", "https://example.com"},
+ {"http://localhost:8080/path?query=value", "http://localhost:8080/path?query=value"},
+ {"postgres://user:pass@host:5432/dbname", "postgres://user:pass@host:5432/dbname"},
+ }
+
+ for _, tt := range tests {
+ result, err := parser.Parse(tt.input)
+ assert.Nil(t, err)
+ url, ok := result.(url.URL)
+ assert.True(t, ok)
+ assert.Equal(t, tt.expected, url.String())
+ }
+
+ _, err := parser.Parse(":")
+ assert.NotNil(t, err)
+}
+
+// GIVEN a string slice parser
+// WHEN we parse comma-separated string values
+// THEN it should correctly split the input into a string slice
+func TestStringSliceParser(t *testing.T) {
+ parser := typeParserRegistry[reflect.TypeOf([]string{})]
+
+ tests := []struct {
+ input string
+ expected []string
+ }{
+ {"one,two,three", []string{"one", "two", "three"}},
+ {"", []string{}},
+ {"single", []string{"single"}},
+ {"with space, and another", []string{"with space", " and another"}},
+ }
+
+ for _, tt := range tests {
+ result, err := parser.Parse(tt.input)
+ assert.Nil(t, err)
+ slice, ok := result.([]string)
+ assert.True(t, ok)
+ assert.Equal(t, len(tt.expected), len(slice))
+ for i, v := range tt.expected {
+ assert.Equal(t, v, slice[i])
+ }
+ }
+}
+
+// GIVEN an int slice parser
+// WHEN we parse comma-separated integer values
+// THEN it should:
+// - Correctly convert each element to an integer
+// - Return an error if any element cannot be parsed as an integer
+func TestIntSliceParser(t *testing.T) {
+ parser := typeParserRegistry[reflect.TypeOf([]int{})]
+
+ tests := []struct {
+ input string
+ expected []int
+ }{
+ {"1,2,3", []int{1, 2, 3}},
+ {"", []int{}},
+ {"42", []int{42}},
+ {"1, 2, 3", []int{1, 2, 3}},
+ }
+ for _, tt := range tests {
+ result, err := parser.Parse(tt.input)
+ assert.Nil(t, err)
+ slice, ok := result.([]int)
+ assert.True(t, ok)
+ assert.Equal(t, len(tt.expected), len(slice))
+ for i, v := range tt.expected {
+ assert.Equal(t, v, slice[i])
+ }
+ }
+
+ _, err := parser.Parse("1,not-an-int,3")
+ assert.NotNil(t, err)
+}
+
+// GIVEN the RegisterTypeParser function
+// WHEN we register a custom type parser
+// THEN it should:
+// - Successfully add the parser to the registry
+// - Correctly use the parser when parsing values
+func TestRegisterTypeParserSupportsRegisteringCustomTypes(t *testing.T) {
+ type CustomType struct {
+ Value string
+ }
+ defer delete(typeParserRegistry, reflect.TypeOf(CustomType{}))
+
+ RegisterTypeParser(reflect.TypeOf(CustomType{}), TypeParserFunc(func(value string) (any, error) {
+ return CustomType{Value: "prefix-" + value}, nil
+ }))
+
+ parser, exists := typeParserRegistry[reflect.TypeOf(CustomType{})]
+ assert.True(t, exists)
+ result, err := parser.Parse("test")
+ assert.Nil(t, err)
+ customValue, ok := result.(CustomType)
+ assert.True(t, ok)
+ assert.Equal(t, "prefix-test", customValue.Value)
+}
+
+// GIVEN various type parsers
+// WHEN we provide invalid string values
+// THEN each parser should return an appropriate error
+func TestParseInvalidValues(t *testing.T) {
+ tests := []struct {
+ name string
+ typ reflect.Type
+ input string
+ }{
+ {"Invalid int", reflect.TypeOf(int(0)), "not-an-int"},
+ {"Invalid int8", reflect.TypeOf(int8(0)), "not-an-int"},
+ {"Invalid int16", reflect.TypeOf(int16(0)), "not-an-int"},
+ {"Invalid int32", reflect.TypeOf(int32(0)), "not-an-int"},
+ {"Invalid int64", reflect.TypeOf(int64(0)), "not-an-int"},
+ {"Invalid uint", reflect.TypeOf(uint(0)), "not-a-uint"},
+ {"Invalid uint8", reflect.TypeOf(uint8(0)), "not-an-int"},
+ {"Invalid uint16", reflect.TypeOf(uint16(0)), "not-an-int"},
+ {"Invalid uint32", reflect.TypeOf(uint32(0)), "not-an-int"},
+ {"Invalid uint64", reflect.TypeOf(uint64(0)), "not-an-int"},
+ {"Invalid uint negative", reflect.TypeOf(uint(0)), "-5"},
+ {"Invalid float32", reflect.TypeOf(float32(0)), "not-a-float"},
+ {"Invalid float64", reflect.TypeOf(float64(0)), "not-a-float"},
+ {"Invalid bool", reflect.TypeOf(false), "not-a-bool"},
+ {"Invalid time", reflect.TypeOf(time.Time{}), "not-a-time"},
+ {"Invalid duration", reflect.TypeOf(time.Duration(0)), "not-a-duration"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ parser := typeParserRegistry[tt.typ]
+ _, err := parser.Parse(tt.input)
+ assert.NotNil(t, err)
+ })
+ }
+}