enve

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 15, 2024 License: BSD-3-Clause Imports: 13 Imported by: 3

README

enve v1.1.0

GoDoc

Parsing and configuration via environment variables.

  • Handy logs & error messages so you can easily discover your configuration by just running the program.
  • Lets you know by default what knobs are required or missing... at most once per environment variable.
  • As simple an API as I could make.

the big idea

Mandatory Environment Variables

If you have a required configuration value, use the Must family of functions:

Or specify custom parsing functions with Must itself.

Optional Environment Variables

If you have an optional configuration value, use the Or family of functions:

Or specify custom parsing functions with Or itself.

Customizing Enve's Logging Output

Enve outputs logs using the log package by default, using it's default (global) logger. You can customize this behavior using environment variables:

See more examples in the GoDoc.

Documentation

Overview

Package enve retrieves & parses environment variables with optional logging.

  • Handy logs & error messages so you can easily discover your configuration by just running the program.
  • Lets you know by default what knobs are required or missing... at most once per environment variable.
  • As simple an API as I could make.
Example (Must)

Use the Must family of functions for required environment variables.

package main

import (
	"fmt"
	"os"

	"gitlab.com/efronlicht/enve"
)

func main() {
	os.Setenv("THE_ANSWER", "42")
	fmt.Println(enve.MustInt("THE_ANSWER"))
}
Output:

42
Example (MustPanicOnMissing)
package main

import (
	"fmt"
	"log"
	"os"

	"gitlab.com/efronlicht/enve"
)

func main() {
	defer replaceStderr()()
	defer func() { recover() }()

	fmt.Println(enve.MustString("THE_QUESTION"))
	// enve: enve/example_test.go:48 enve_test.Example_mustPanicOnMissing FATAL ERR: missing required envvar THE_QUESTION
}

func replaceStderr() func() {
	log.SetFlags(0)

	oldstderr := *os.Stderr
	*os.Stderr = *os.Stdout
	return func() { *os.Stderr = oldstderr }
}
Output:

Example (Or)

Use the Or family of functions for optional environment variables.

package main

import (
	"fmt"

	"gitlab.com/efronlicht/enve"
)

func main() {
	port := fmt.Sprintf(":%d", enve.IntOr("PORT", 8080)) // default to 8080 if not set
	fmt.Printf("server listening at %s\n", port)
}
Output:

server listening at :8080
Example (OrCustom)

You can use your own parser functions with Or or Must for custom types.

package main

import (
	"fmt"
	"net"
	"os"

	"gitlab.com/efronlicht/enve"
)

func main() {
	parseIP := func(s string) (net.IP, error) {
		if ip := net.ParseIP(s); ip != nil {
			return ip, nil
		}
		return nil, fmt.Errorf("invalid IP address %q", s)
	}

	os.Setenv("DNS", "8.8.8.8")                                // google's public DNS
	fmt.Println(enve.Or(parseIP, "DNS", net.IPv4(1, 1, 1, 1))) // default to Cloudflare's public DNS if not set
}
Output:

8.8.8.8

Index

Examples

Constants

View Source
const (
	// environment variables to control logging behavior.
	ENVE_LOG_SUCCESS  = "ENVE_LOG_SUCCESS"  // if false, don't log successes (found/parsed key for the first time)
	ENVE_LOG_ERROR    = "ENVE_LOG_ERROR"    // if false, don't log errors (missing keys, bad values)
	ENVE_LOG_SLOG     = "ENVE_LOG_SLOG"     // environment variable to enable "log/slog" logging mode; if false, use "log" instead.
	ENVE_LOG_DISABLED = "ENVE_LOG_DISABLED" // environment variable to disable logging entirely; overrides all other logging settings.
)

Variables

This section is empty.

Functions

func BoolOr

func BoolOr(key string, backup bool) bool

BoolOr returns the boolean value represented by the environment variable. It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. Any other value will return backup.

func DurationOr

func DurationOr(key string, backup time.Duration) time.Duration

DurationOr looks up and parses the envvar as a duration.

func FloatOr

func FloatOr(key string, backup float64) float64

FloatOr wraps Or(parse.Float, key, backup)

func FromTextOr

func FromTextOr[T any, PT interface {
	*T
	encoding.TextUnmarshaler
}](key string, backup T,
) T

FromTextOr looks up and parses the envvar as a TextUnmarshaler.

func IntOr

func IntOr(key string, backup int) int

IntOr wraps Or(strconv.ParseInt(key, 0, 0), key, backup)

func Lookup

func Lookup[T any](parse func(s string) (T, error), key string) (T, error)

Lookup and parse the specified environment variable key, returning ErrorMissingKey if it's missing, and the result of parse(os.Getenv(key)) otherwise. The error message will include the key.

func Must

func Must[T any](parse func(string) (T, error), key string) T

Must looks up & parses the specified environment variable key, panicking on a missing value or parse error. Successful output will be logged exactly once if ENVE_LOG_SUCCESS is true.

func MustBool

func MustBool(key string) bool

MustBool wraps Must(strconv.ParseBool, key)v

func MustDuration

func MustDuration(key string) time.Duration

MustDuration wraps Must(time.ParseDuration, key)

func MustFloat

func MustFloat(key string) float64

MustFloat wraps Must(strconv.ParseFloat(key, 64), key)

func MustInt

func MustInt(key string) int

MustInt wraps Must(strconv.ParseInt(key, 0, 0), key)

func MustString

func MustString(key string) string

MustString looks up the envvar, panicking on a missing value. Unlike "Or", the empty string is OK.

func MustTimeRFC3339

func MustTimeRFC3339(key string) time.Time

MustTimeRFC3339 wraps Must(parse.TimeRFC3339, key)

func MustUint64

func MustUint64(key string) uint64

MustUint64 wraps Must(strconv.ParseUint(key, 0, 64), key)

func Or

func Or[T any](parse func(string) (T, error), key string, backup T) T

Or looks up & parses the specified environment variable key. A missing or unparsable value will return the backup value, logging the error (if any) and the fallback valuue. Successful output will be logged exactly once if ENVE_LOG_SUCCESS is true.

func StringOr

func StringOr(key, backup string) string

StringOr returns os.Getenv(key) if it's not the empty string, Or backup otherwise.

func TimeRFC3339Or

func TimeRFC3339Or(key string, backup time.Time) time.Time

TimeRFC3339Or wraps Or(parse.TimeRFC3339, key, backup)

func Uint64Or added in v1.1.0

func Uint64Or(key string, backup uint64) uint64

Uint64Or wraps Or(parse.Uint, key, backup)

Types

This section is empty.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL