aboutsummaryrefslogtreecommitdiffstats
path: root/README.md
blob: eb9d49799d2b3f3fe24b8a9214effb2c569d8438 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# Envelope

<p>
    <a href="https://pkg.go.dev/git.eugenetriguba.com/envelope">
        <img src="https://pkg.go.dev/badge/git.eugenetriguba.com/envelope.svg" alt="Go Reference">
    </a>
    <img alt="Version Badge" src="https://img.shields.io/badge/version-0.2.0-blue" style="max-width:100%;">
</p>

Envelope is a Go library that makes it easy to populate Go structs from environment variables.

## Installation

```bash
go get git.eugenetriguba.com/envelope
```

## Quick Start

```go
package main

import (
    "fmt"
    "log"
    "time"

    "git.eugenetriguba.com/envelope"
)

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 config Config
    if err := envelope.LoadFromEnv(&config); err != nil {
        log.Fatalf("Failed to load configuration: %v", err)
    }
    
    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
```

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"`
}

// LoadFromEnv will look for:
// - URL
// - USERNAME
// - PASSWORD
// - LOG_LEVEL
```

### 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
```

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
```

### 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 [Go reference](https://pkg.go.dev/git.eugenetriguba.com/envelope).