ferrite

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2024 License: MIT Imports: 23 Imported by: 5

README

Ferrite

A type-safe, declarative environment variable validation system for Go.

Documentation Latest Version Build Status Code Coverage

Getting Started

This example demonstrates how to declare an environment variable that produces a time.Duration value, but Ferrite supports many different variable types, as described in the examples.

First, describe the application's environment variables using Ferrite's "builder" interfaces. This is typically done at the package-scope of the main package.

var httpTimeout = ferrite.
    Duration("HTTP_TIMEOUT", "the maximum duration of each HTTP request").
    WithDefault(10 * time.Second).
    Required()

Next, initialize Ferrite in the application's main() function before any other code is executed so that it may halt execution when the environment is invalid.

func main() {
    ferrite.Init()

    // existing application logic ...
}

Finally, read the environment variable's value by calling the Value() method.

timeout := httpTimeout.Value()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()

// do HTTP request ...

Modes of Operation

By default, calling Init() operates in "validation" mode. There are several other modes that can be used to gain insight into the application's use of environment variables.

Modes are selected by setting the FERRITE_MODE environment variable.

validate mode

This is the default mode. If one or more environment variables are invalid, this mode renders a description of all declared environment variables and their associated values and validation failures to STDERR, then exits the process with a non-zero exit code.

It also shows warnings if deprecated environment variables are used.

usage/markdown mode

This mode renders Markdown documentation about the environment variables to STDOUT. The output is designed to be included in the application's README.md file or a similar file.

export/dotenv mode

This mode renders environment variables to STDOUT in a format suitable for use with tools like dotenv and the env_file directive in Docker compose files.

Other Implementations

Austenite is a TypeScript library with similar features to Ferrite.

Documentation

Overview

Package ferrite is a type-safe, declarative environment variable validation system.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Init added in v0.2.0

func Init(options ...InitOption)

Init initializes Ferrite.

Different modes can be selected by setting the `FERRITE_MODE` environment variable.

"validate" mode: This is the default mode. If one or more environment variables are invalid, this mode renders a description of all declared environment variables and their associated values and validation failures to `STDERR`, then exits the process with a non-zero exit code.

It also shows warnings if deprecated environment variables are used.

"usage/markdown" mode: This mode renders Markdown documentation about the environment variables to `STDOUT`. The output is designed to be included in the application's `README.md` file or a similar file.

"export/dotenv" mode: This mode renders environment variables to `STDOUT` in a format suitable for use as a `.env` file.

Example (ExportDotEnvFile)
defer example()()

os.Setenv("FERRITE_BINARY", "PHZhbHVlPg==")
ferrite.
	Binary("FERRITE_BINARY", "example binary").
	Required()

os.Setenv("FERRITE_BINARY_SENSITIVE", "aHVudGVyMg==")
ferrite.
	Binary("FERRITE_BINARY_SENSITIVE", "example sensitive binary").
	WithDefault([]byte("password")).
	WithSensitiveContent().
	Required()

os.Setenv("FERRITE_BOOL", "true")
ferrite.
	Bool("FERRITE_BOOL", "example bool").
	Required()

os.Setenv("FERRITE_DURATION", "620s")
ferrite.
	Duration("FERRITE_DURATION", "example duration").
	WithDefault(1 * time.Hour).
	Required()

ferrite.
	Enum("FERRITE_ENUM", "example enum").
	WithMembers("foo", "bar", "baz").
	WithDefault("bar").
	Required()

os.Setenv("FERRITE_NETWORK_PORT", "8080")
ferrite.
	NetworkPort("FERRITE_NETWORK_PORT", "example network port").
	Optional()

ferrite.
	Float[float32]("FERRITE_NUM_FLOAT", "example floating-point").
	Required()

ferrite.
	Signed[int16]("FERRITE_NUM_SIGNED", "example signed integer").
	Required()

ferrite.
	Unsigned[uint16]("FERRITE_NUM_UNSIGNED", "example unsigned integer").
	Required()

os.Setenv("FERRITE_STRING", "hello, world!")
ferrite.
	String("FERRITE_STRING", "example string").
	Required()

os.Setenv("FERRITE_STRING_SENSITIVE", "hunter2")
ferrite.
	String("FERRITE_STRING_SENSITIVE", "example sensitive string").
	WithDefault("password").
	WithSensitiveContent().
	Required()

os.Setenv("FERRITE_SVC_SERVICE_HOST", "host.example.org")
os.Setenv("FERRITE_SVC_SERVICE_PORT", "443")
ferrite.
	KubernetesService("ferrite-svc").
	Deprecated()

os.Setenv("FERRITE_URL", "https//example.org")
ferrite.
	URL("FERRITE_URL", "example URL").
	Required()

// Tell ferrite to export an env file containing the environment variables.
os.Setenv("FERRITE_MODE", "export/dotenv")

ferrite.Init()
Output:

# example binary (required)
export FERRITE_BINARY=PHZhbHVlPg==

# example sensitive binary (default: {12 bytes}, sensitive)
export FERRITE_BINARY_SENSITIVE=aHVudGVyMg==

# example bool (required)
export FERRITE_BOOL=true

# example duration (default: 1h)
export FERRITE_DURATION=620s # equivalent to 10m20s

# example enum (default: bar)
export FERRITE_ENUM=

# example network port (optional)
export FERRITE_NETWORK_PORT=8080

# example floating-point (required)
export FERRITE_NUM_FLOAT=

# example signed integer (required)
export FERRITE_NUM_SIGNED=

# example unsigned integer (required)
export FERRITE_NUM_UNSIGNED=

# example string (required)
export FERRITE_STRING='hello, world!'

# example sensitive string (default: ********, sensitive)
export FERRITE_STRING_SENSITIVE=hunter2

# kubernetes "ferrite-svc" service host (deprecated)
export FERRITE_SVC_SERVICE_HOST=host.example.org

# kubernetes "ferrite-svc" service port (deprecated)
export FERRITE_SVC_SERVICE_PORT=443

# example URL (required)
export FERRITE_URL= # https//example.org is invalid: URL must have a scheme
<process exited successfully>
Example (MarkdownUsage)
defer example()()

// Tell ferrite to generate markdown documentation for the environment
// variables.
os.Setenv("FERRITE_MODE", "usage/markdown")

ferrite.Init()

// In the interest of simplicity this example doesn't have any defined
// environment variables, which is explained in the markdown output.
Output:

# Environment Variables

This document describes the environment variables used by `ferrite.test`.

**There do not appear to be any environment variables.**

⚠️ `ferrite.test` may consume other undocumented environment variables. This
document only shows variables declared using [Ferrite].

<!-- references -->

[ferrite]: https://github.com/dogmatiq/ferrite
<process exited successfully>
Example (Validation)
defer example()()

os.Setenv("FERRITE_BINARY", "PHZhbHVlPg==")
ferrite.
	Binary("FERRITE_BINARY", "example binary").
	Required()

os.Setenv("FERRITE_BINARY_SENSITIVE", "aHVudGVyMg==")
ferrite.
	Binary("FERRITE_BINARY_SENSITIVE", "example sensitive binary").
	WithSensitiveContent().
	Required()

os.Setenv("FERRITE_BOOL", "true")
ferrite.
	Bool("FERRITE_BOOL", "example bool").
	Required()

os.Setenv("FERRITE_DURATION", "3h20m")
ferrite.
	Duration("FERRITE_DURATION", "example duration").
	Required()

os.Setenv("FERRITE_ENUM", "foo")
ferrite.
	Enum("FERRITE_ENUM", "example enum").
	WithMembers("foo", "bar", "baz").
	Required()

os.Setenv("FERRITE_NETWORK_PORT", "8080")
ferrite.
	NetworkPort("FERRITE_NETWORK_PORT", "example network port").
	Required()

os.Setenv("FERRITE_NUM_FLOAT", "-123.45")
ferrite.
	Float[float32]("FERRITE_NUM_FLOAT", "example float-point").
	Required()

os.Setenv("FERRITE_NUM_SIGNED", "-123")
ferrite.
	Signed[int16]("FERRITE_NUM_SIGNED", "example signed integer").
	Required()

os.Setenv("FERRITE_NUM_UNSIGNED", "456")
ferrite.
	Unsigned[uint16]("FERRITE_NUM_UNSIGNED", "example unsigned integer").
	Required()

os.Setenv("FERRITE_STRING", "hello, world!")
ferrite.
	String("FERRITE_STRING", "example string").
	Required()

os.Setenv("FERRITE_STRING_SENSITIVE", "hunter2")
ferrite.
	String("FERRITE_STRING_SENSITIVE", "example sensitive string").
	WithSensitiveContent().
	Required()

os.Setenv("FERRITE_SVC_SERVICE_HOST", "host.example.org")
os.Setenv("FERRITE_SVC_SERVICE_PORT", "443")
ferrite.
	KubernetesService("ferrite-svc").
	Required()

os.Setenv("FERRITE_URL", "https://example.org")
ferrite.
	URL("FERRITE_URL", "example URL").
	Required()

ferrite.
	String("FERRITE_XTRIGGER", "trigger failure for example").
	Required()

ferrite.Init()
Output:

Environment Variables:

   FERRITE_BINARY            example binary                           <base64>           ✓ set to {12 bytes}
   FERRITE_BINARY_SENSITIVE  example sensitive binary                 <base64>           ✓ set to {12 bytes}
   FERRITE_BOOL              example bool                             true | false       ✓ set to true
   FERRITE_DURATION          example duration                         1ns ...            ✓ set to 3h20m
   FERRITE_ENUM              example enum                             foo | bar | baz    ✓ set to foo
   FERRITE_NETWORK_PORT      example network port                     <string>           ✓ set to 8080
   FERRITE_NUM_FLOAT         example float-point                      <float32>          ✓ set to -123.45
   FERRITE_NUM_SIGNED        example signed integer                   <int16>            ✓ set to -123
   FERRITE_NUM_UNSIGNED      example unsigned integer                 <uint16>           ✓ set to 456
   FERRITE_STRING            example string                           <string>           ✓ set to 'hello, world!'
   FERRITE_STRING_SENSITIVE  example sensitive string                 <string>           ✓ set to *******
   FERRITE_SVC_SERVICE_HOST  kubernetes "ferrite-svc" service host    <string>           ✓ set to host.example.org
   FERRITE_SVC_SERVICE_PORT  kubernetes "ferrite-svc" service port    <string>           ✓ set to 443
   FERRITE_URL               example URL                              <string>           ✓ set to https://example.org
 ❯ FERRITE_XTRIGGER          trigger failure for example              <string>           ✗ undefined

<process exited with error code 1>
Example (ValidationWithDefaultValues)
defer example()()

ferrite.
	Binary("FERRITE_BINARY", "example binary").
	WithEncodedDefault("PHZhbHVlPg==").
	Required()

ferrite.
	Binary("FERRITE_BINARY_SENSITIVE", "example sensitive binary").
	WithEncodedDefault("aHVudGVyMg==").
	WithSensitiveContent().
	Required()

ferrite.
	Bool("FERRITE_BOOL", "example bool").
	WithDefault(true).
	Required()

ferrite.
	Duration("FERRITE_DURATION", "example duration").
	WithDefault(10 * time.Second).
	Required()

ferrite.
	Enum("FERRITE_ENUM", "example enum").
	WithMembers("foo", "bar", "baz").
	WithDefault("bar").
	Required()

ferrite.
	NetworkPort("FERRITE_NETWORK_PORT", "example network port").
	WithDefault("8080").
	Required()

ferrite.
	Float[float32]("FERRITE_NUM_FLOAT", "example float-point").
	WithDefault(-123.45).
	Required()

ferrite.
	Signed[int16]("FERRITE_NUM_SIGNED", "example signed integer").
	WithDefault(-123).
	Required()

ferrite.
	Unsigned[uint16]("FERRITE_NUM_UNSIGNED", "example unsigned integer").
	WithDefault(123).
	Required()

ferrite.
	String("FERRITE_STRING", "example string").
	WithDefault("hello, world!").
	Required()

ferrite.
	String("FERRITE_STRING_SENSITIVE", "example sensitive string").
	WithDefault("hunter2").
	WithSensitiveContent().
	Required()

ferrite.
	KubernetesService("ferrite-svc").
	WithDefault("host.example.org", "443").
	Required()

ferrite.
	URL("FERRITE_URL", "example URL").
	WithDefault("https://example.org").
	Required()

ferrite.
	String("FERRITE_XTRIGGER", "trigger failure for example").
	Required()

ferrite.Init()
Output:

Environment Variables:

   FERRITE_BINARY            example binary                         [ <base64> ] = {12 bytes}           ✓ using default value
   FERRITE_BINARY_SENSITIVE  example sensitive binary               [ <base64> ] = {12 bytes}           ✓ using default value
   FERRITE_BOOL              example bool                           [ true | false ] = true             ✓ using default value
   FERRITE_DURATION          example duration                       [ 1ns ... ] = 10s                   ✓ using default value
   FERRITE_ENUM              example enum                           [ foo | bar | baz ] = bar           ✓ using default value
   FERRITE_NETWORK_PORT      example network port                   [ <string> ] = 8080                 ✓ using default value
   FERRITE_NUM_FLOAT         example float-point                    [ <float32> ] = -123.45             ✓ using default value
   FERRITE_NUM_SIGNED        example signed integer                 [ <int16> ] = -123                  ✓ using default value
   FERRITE_NUM_UNSIGNED      example unsigned integer               [ <uint16> ] = 123                  ✓ using default value
   FERRITE_STRING            example string                         [ <string> ] = 'hello, world!'      ✓ using default value
   FERRITE_STRING_SENSITIVE  example sensitive string               [ <string> ] = *******              ✓ using default value
   FERRITE_SVC_SERVICE_HOST  kubernetes "ferrite-svc" service host  [ <string> ] = host.example.org     ✓ using default value
   FERRITE_SVC_SERVICE_PORT  kubernetes "ferrite-svc" service port  [ <string> ] = 443                  ✓ using default value
   FERRITE_URL               example URL                            [ <string> ] = https://example.org  ✓ using default value
 ❯ FERRITE_XTRIGGER          trigger failure for example              <string>                          ✗ undefined

<process exited with error code 1>
Example (ValidationWithInvalidValues)
defer example()()

os.Setenv("FERRITE_BINARY", "<invalid base64>")
ferrite.
	Binary("FERRITE_BINARY", "example binary").
	Required()

os.Setenv("FERRITE_BINARY_SENSITIVE", "<invalid base64>")
ferrite.
	Binary("FERRITE_BINARY_SENSITIVE", "example sensitive binary").
	WithSensitiveContent().
	Required()

os.Setenv("FERRITE_BOOL", "yes")
ferrite.
	Bool("FERRITE_BOOL", "example bool").
	Required()

os.Setenv("FERRITE_DURATION", "-+10s")
ferrite.
	Duration("FERRITE_DURATION", "example duration").
	Required()

os.Setenv("FERRITE_ENUM", "qux")
ferrite.
	Enum("FERRITE_ENUM", "example enum").
	WithMembers("foo", "bar", "baz").
	Required()

os.Setenv("FERRITE_NETWORK_PORT", "<invalid port>")
ferrite.
	NetworkPort("FERRITE_NETWORK_PORT", "example network port").
	Required()

os.Setenv("FERRITE_NUM_FLOAT", "-123w45")
ferrite.
	Float[float32]("FERRITE_NUM_FLOAT", "example float-point").
	Required()

os.Setenv("FERRITE_NUM_SIGNED", "123.3")
ferrite.
	Signed[int16]("FERRITE_NUM_SIGNED", "example signed integer").
	Required()

os.Setenv("FERRITE_NUM_UNSIGNED", "-123")
ferrite.
	Unsigned[uint16]("FERRITE_NUM_UNSIGNED", "example unsigned integer").
	Required()

os.Setenv("FERRITE_STRING", "foo bar")
ferrite.
	String("FERRITE_STRING", "example string").
	WithConstraint(
		"must not contain whitespace",
		func(s string) bool {
			return !strings.ContainsRune(s, ' ')
		},
	).
	Required()

os.Setenv("FERRITE_STRING_SENSITIVE", "foo bar")
ferrite.
	String("FERRITE_STRING_SENSITIVE", "example sensitive string").
	WithConstraint(
		"must not contain whitespace",
		func(s string) bool {
			return !strings.ContainsRune(s, ' ')
		},
	).
	WithSensitiveContent().
	Required()

os.Setenv("FERRITE_SVC_SERVICE_HOST", ".local")
os.Setenv("FERRITE_SVC_SERVICE_PORT", "https-")
ferrite.
	KubernetesService("ferrite-svc").
	Required()

os.Setenv("FERRITE_URL", "/relative/path")
ferrite.
	URL("FERRITE_URL", "example URL").
	Required()

ferrite.Init()
Output:

Environment Variables:

 ❯ FERRITE_BINARY            example binary                           <base64>           ✗ set to {16 bytes}, illegal base64 data at input byte 0
 ❯ FERRITE_BINARY_SENSITIVE  example sensitive binary                 <base64>           ✗ set to {16 bytes}, illegal base64 data at input byte 0
 ❯ FERRITE_BOOL              example bool                             true | false       ✗ set to yes, expected either true or false
 ❯ FERRITE_DURATION          example duration                         1ns ...            ✗ set to -+10s, expected duration
 ❯ FERRITE_ENUM              example enum                             foo | bar | baz    ✗ set to qux, expected foo, bar or baz
 ❯ FERRITE_NETWORK_PORT      example network port                     <string>           ✗ set to '<invalid port>', IANA service name must contain only ASCII letters, digits and hyphen
 ❯ FERRITE_NUM_FLOAT         example float-point                      <float32>          ✗ set to -123w45, expected float32
 ❯ FERRITE_NUM_SIGNED        example signed integer                   <int16>            ✗ set to 123.3, expected integer between -32768 and +32767
 ❯ FERRITE_NUM_UNSIGNED      example unsigned integer                 <uint16>           ✗ set to -123, expected integer between 0 and 65535
 ❯ FERRITE_STRING            example string                           <string>           ✗ set to 'foo bar', must not contain whitespace
 ❯ FERRITE_STRING_SENSITIVE  example sensitive string                 <string>           ✗ set to *******, must not contain whitespace
 ❯ FERRITE_SVC_SERVICE_HOST  kubernetes "ferrite-svc" service host    <string>           ✗ set to .local, host must not begin or end with a dot
 ❯ FERRITE_SVC_SERVICE_PORT  kubernetes "ferrite-svc" service port    <string>           ✗ set to https-, IANA service name must not begin or end with a hyphen
 ❯ FERRITE_URL               example URL                              <string>           ✗ set to /relative/path, URL must have a scheme

<process exited with error code 1>
Example (ValidationWithNonCanonicalValues)
defer example()()

os.Setenv("FERRITE_DURATION", "3h 10m 0s")
ferrite.
	Duration("FERRITE_DURATION", "example duration").
	Required()

ferrite.
	String("FERRITE_XTRIGGER", "trigger failure for example").
	Required()

ferrite.Init()
Output:

Environment Variables:

   FERRITE_DURATION  example duration               1ns ...     ✓ set to '3h 10m 0s', equivalent to 3h10m
 ❯ FERRITE_XTRIGGER  trigger failure for example    <string>    ✗ undefined

<process exited with error code 1>
Example (ValidationWithOptionalValues)
defer example()()

ferrite.
	Binary("FERRITE_BINARY", "example binary").
	Optional()

ferrite.
	Binary("FERRITE_BINARY_SENSITIVE", "example sensitive binary").
	WithSensitiveContent().
	Optional()

ferrite.
	Bool("FERRITE_BOOL", "example bool").
	Optional()

ferrite.
	Duration("FERRITE_DURATION", "example duration").
	Optional()

ferrite.
	Enum("FERRITE_ENUM", "example enum").
	WithMembers("foo", "bar", "baz").
	Optional()

ferrite.
	NetworkPort("FERRITE_NETWORK_PORT", "example network port").
	Optional()

ferrite.
	Float[float32]("FERRITE_NUM_FLOAT", "example float-point").
	Optional()

ferrite.
	Signed[int16]("FERRITE_NUM_SIGNED", "example signed integer").
	Optional()

ferrite.
	Unsigned[uint16]("FERRITE_NUM_UNSIGNED", "example unsigned integer").
	Optional()

ferrite.
	String("FERRITE_STRING", "example string").
	Optional()

ferrite.
	String("FERRITE_STRING_SENSITIVE", "example sensitive string").
	WithSensitiveContent().
	Optional()

ferrite.
	KubernetesService("ferrite-svc").
	Optional()

ferrite.
	URL("FERRITE_URL", "example URL").
	Optional()

ferrite.
	String("FERRITE_XTRIGGER", "trigger failure for example").
	Required()

ferrite.Init()
Output:

Environment Variables:

   FERRITE_BINARY            example binary                         [ <base64> ]         • undefined
   FERRITE_BINARY_SENSITIVE  example sensitive binary               [ <base64> ]         • undefined
   FERRITE_BOOL              example bool                           [ true | false ]     • undefined
   FERRITE_DURATION          example duration                       [ 1ns ... ]          • undefined
   FERRITE_ENUM              example enum                           [ foo | bar | baz ]  • undefined
   FERRITE_NETWORK_PORT      example network port                   [ <string> ]         • undefined
   FERRITE_NUM_FLOAT         example float-point                    [ <float32> ]        • undefined
   FERRITE_NUM_SIGNED        example signed integer                 [ <int16> ]          • undefined
   FERRITE_NUM_UNSIGNED      example unsigned integer               [ <uint16> ]         • undefined
   FERRITE_STRING            example string                         [ <string> ]         • undefined
   FERRITE_STRING_SENSITIVE  example sensitive string               [ <string> ]         • undefined
   FERRITE_SVC_SERVICE_HOST  kubernetes "ferrite-svc" service host  [ <string> ]         • undefined
   FERRITE_SVC_SERVICE_PORT  kubernetes "ferrite-svc" service port  [ <string> ]         • undefined
   FERRITE_URL               example URL                            [ <string> ]         • undefined
 ❯ FERRITE_XTRIGGER          trigger failure for example              <string>           ✗ undefined

<process exited with error code 1>

func RelevantIf added in v0.6.0

RelevantIf is an option that enables a variable set only if the value obtained from another set, s, is "truthy" (not the zero-value).

A "irrelevant" variable set behaves as though its environment variables are undefined, irrespective of the actual values of the variables and any default values.

Example (WhenNotRelevant)
defer example()()

widgetEnabled := ferrite.
	Bool("FERRITE_WIDGET_ENABLED", "enable the widget").
	Required()

ferrite.
	Unsigned[uint]("FERRITE_WIDGET_SPEED", "set the speed of the widget").
	Required(ferrite.RelevantIf(widgetEnabled))

// FERRITE_WIDGET_SPEED is "required" but we can leave it undefined when
// FERRITE_WIDGET_ENABLED is "false" without causing a validation failure.
os.Setenv("FERRITE_WIDGET_ENABLED", "false")
ferrite.Init()
Output:

Example (WhenNotRelevantBuInvalid)
defer example()()

widgetEnabled := ferrite.
	Bool("FERRITE_WIDGET_ENABLED", "enable the widget").
	Required()

ferrite.
	Unsigned[uint]("FERRITE_WIDGET_SPEED", "set the speed of the widget").
	Required(ferrite.RelevantIf(widgetEnabled))

// FERRITE_WIDGET_SPEED is not required because FERRITE_WIDGET_ENABLED is
// "false". We want to see the error message but not terminate execution.
os.Setenv("FERRITE_WIDGET_SPEED", "-100")
os.Setenv("FERRITE_WIDGET_ENABLED", "false")
ferrite.Init()
Output:

Environment Variables:

   FERRITE_WIDGET_ENABLED  enable the widget              true | false    ✓ set to false
 ❯ FERRITE_WIDGET_SPEED    set the speed of the widget    <uint>          ✗ set to -100, expected integer
Example (WhenRelevant)
defer example()()

widgetEnabled := ferrite.
	Bool("FERRITE_WIDGET_ENABLED", "enable the widget").
	Required()

widgetSpeed := ferrite.
	Unsigned[uint]("FERRITE_WIDGET_SPEED", "set the speed of the widget").
	Optional(ferrite.RelevantIf(widgetEnabled))

os.Setenv("FERRITE_WIDGET_SPEED", "100")
os.Setenv("FERRITE_WIDGET_ENABLED", "true")
ferrite.Init()

if x, ok := widgetSpeed.Value(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is not relevant")
}
Output:

value is 100

func SeeAlso added in v0.6.0

SeeAlso is an option for a variable set that adds the variables in another set, s, to the "see also" section of the generated documentation.

Example
defer example()()

verbose := ferrite.
	Bool("FERRITE_VERBOSE", "enable verbose logging").
	Optional()

ferrite.
	Bool("FERRITE_DEBUG", "enable or disable debugging features").
	Optional(ferrite.SeeAlso(verbose))

ferrite.Init()
Output:

func WithRegistry added in v0.5.0

func WithRegistry(reg Registry) interface {
	InitOption
	RequiredOption
	OptionalOption
	DeprecatedOption
}

WithRegistry is an option that sets the variable registries to use.

Types

type BinaryBuilder added in v1.1.0

type BinaryBuilder[T ~[]B, B ~byte] struct {
	// contains filtered or unexported fields
}

BinaryBuilder builds a specification for a binary variable.

func Binary added in v1.1.0

func Binary(name, desc string) *BinaryBuilder[[]byte, byte]

Binary configures an environment variable as a raw binary value, represented as a byte-slice.

Binary values are represented in environment variables using a suitable encoding schema. The default encoding is the standard "base64" encoding described by RFC 4648.

name is the name of the environment variable to read. desc is a human-readable description of the environment variable.

Example (Base64url)
defer example()()

v := ferrite.
	Binary("FERRITE_BINARY", "example binary variable").
	WithBase64Encoding(base64.RawURLEncoding).
	Required()

os.Setenv("FERRITE_BINARY", "_w") // would be "/w==" with standard base64 encoding
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is [255]
Example (Default)
defer example()()

v := ferrite.
	Binary("FERRITE_BINARY", "example binary variable").
	WithDefault([]byte("<default>")).
	Required()

ferrite.Init()

fmt.Println("value is", string(v.Value()))
Output:

value is <default>
Example (Deprecated)
defer example()()

v := ferrite.
	Binary("FERRITE_BINARY", "example binary variable").
	Deprecated()

os.Setenv("FERRITE_BINARY", "PHZhbHVlPg==")
ferrite.Init()

if x, ok := v.DeprecatedValue(); ok {
	fmt.Println("value is", string(x))
} else {
	fmt.Println("value is undefined")
}
Output:

Environment Variables:

 ❯ FERRITE_BINARY  example binary variable  [ <base64> ]  ⚠ deprecated variable set to {12 bytes}

value is <value>
Example (EncodedDefault)
defer example()()

v := ferrite.
	Binary("FERRITE_BINARY", "example binary variable").
	WithEncodedDefault("PGRlZmF1bHQ+").
	Required()

ferrite.Init()

fmt.Println("value is", string(v.Value()))
Output:

value is <default>
Example (Encoding)
defer example()()

ferrite.
	Binary("FERRITE_BINARY_BASE64", "base64 encoding").
	Required()

ferrite.
	Binary("FERRITE_BINARY_BASE64_RAW", "base64 encoding, no padding").
	WithBase64Encoding(base64.RawStdEncoding).
	Required()

ferrite.
	Binary("FERRITE_BINARY_BASE64_URL", "base64 encoding, url safe").
	WithBase64Encoding(base64.URLEncoding).
	Required()

ferrite.
	Binary("FERRITE_BINARY_BASE64_URL_RAW", "base64 encoding, url safe, no padding").
	WithBase64Encoding(base64.RawURLEncoding).
	Required()

custom := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz)!@#$%^&*(-_")

ferrite.
	Binary("FERRITE_BINARY_BASE64_CUSTOM", "base64 encoding, custom alphabet").
	WithBase64Encoding(custom).
	Required()

ferrite.
	Binary("FERRITE_BINARY_BASE64_CUSTOM_RAW", "base64 encoding, custom alphabet, no padding").
	WithBase64Encoding(custom.WithPadding(base64.NoPadding)).
	Required()

ferrite.
	Binary("FERRITE_BINARY_HEX", "hexadecimal encoding").
	WithHexEncoding().
	Required()

ferrite.Init()
Output:

Environment Variables:

 ❯ FERRITE_BINARY_BASE64             base64 encoding                                 <base64>                  ✗ undefined
 ❯ FERRITE_BINARY_BASE64_CUSTOM      base64 encoding, custom alphabet                <non-canonical base64>    ✗ undefined
 ❯ FERRITE_BINARY_BASE64_CUSTOM_RAW  base64 encoding, custom alphabet, no padding    <non-canonical base64>    ✗ undefined
 ❯ FERRITE_BINARY_BASE64_RAW         base64 encoding, no padding                     <unpadded base64>         ✗ undefined
 ❯ FERRITE_BINARY_BASE64_URL         base64 encoding, url safe                       <padded base64url>        ✗ undefined
 ❯ FERRITE_BINARY_BASE64_URL_RAW     base64 encoding, url safe, no padding           <base64url>               ✗ undefined
 ❯ FERRITE_BINARY_HEX                hexadecimal encoding                            <hex>                     ✗ undefined

<process exited with error code 1>
Example (Hex)
defer example()()

v := ferrite.
	Binary("FERRITE_BINARY", "example binary variable").
	WithHexEncoding().
	Required()

os.Setenv("FERRITE_BINARY", "3c76616c75653e")
ferrite.Init()

fmt.Println("value is", string(v.Value()))
Output:

value is <value>
Example (Limits)
defer example()()

v := ferrite.
	Binary("FERRITE_BINARY", "example binary variable").
	WithMinimumLength(5).
	WithMaximumLength(10).
	Required()

os.Setenv("FERRITE_BINARY", "PHZhbHVlPg==")
ferrite.Init()

fmt.Println("value is", string(v.Value()))
Output:

value is <value>
Example (Optional)
defer example()()

v := ferrite.
	Binary("FERRITE_BINARY", "example binary variable").
	Optional()

ferrite.Init()

if x, ok := v.Value(); ok {
	fmt.Println("value is", string(x))
} else {
	fmt.Println("value is undefined")
}
Output:

value is undefined
Example (Required)
defer example()()

v := ferrite.
	Binary("FERRITE_BINARY", "example binary variable").
	Required()

os.Setenv("FERRITE_BINARY", "PHZhbHVlPg==")
ferrite.Init()

fmt.Println("value is", string(v.Value()))
Output:

value is <value>
Example (Sensitive)
defer example()()

ferrite.
	Binary("FERRITE_BINARY", "example sensitive binary variable").
	WithConstraint(
		"always fail",
		func(v []byte) bool {
			// Force the variable to be considered invalid so that the
			// variable table is rendered to the console.
			return false
		},
	).
	WithSensitiveContent().
	Required()

os.Setenv("FERRITE_BINARY", "aHVudGVyMg==")
ferrite.Init()

// Note that the variable's value is obscured in the console output.
Output:

Environment Variables:

 ❯ FERRITE_BINARY  example sensitive binary variable    <base64>    ✗ set to {12 bytes}, always fail

<process exited with error code 1>

func BinaryAs added in v1.1.0

func BinaryAs[T ~[]B, B ~byte](name, desc string) *BinaryBuilder[T, B]

BinaryAs configures an environment variable as a raw binary value, represented as a user-defined byte-slice type.

Binary values are represented in environment variables using a suitable encoding schema. The default encoding is the standard "base64" encoding described by RFC 4648.

name is the name of the environment variable to read. desc is a human-readable description of the environment variable.

func (*BinaryBuilder[T, B]) Deprecated added in v1.1.0

func (b *BinaryBuilder[T, B]) Deprecated(options ...DeprecatedOption) Deprecated[T]

Deprecated completes the build process and registers a deprecated variable with Ferrite's validation system.

func (*BinaryBuilder[T, B]) Optional added in v1.1.0

func (b *BinaryBuilder[T, B]) Optional(options ...OptionalOption) Optional[T]

Optional completes the build process and registers an optional variable with Ferrite's validation system.

func (*BinaryBuilder[T, B]) Required added in v1.1.0

func (b *BinaryBuilder[T, B]) Required(options ...RequiredOption) Required[T]

Required completes the build process and registers a required variable with Ferrite's validation system.

func (*BinaryBuilder[T, B]) WithBase64Encoding added in v1.1.0

func (b *BinaryBuilder[T, B]) WithBase64Encoding(enc *base64.Encoding) *BinaryBuilder[T, B]

WithBase64Encoding configures the variable to use base64 encoding to represent the binary value within the environment.

func (*BinaryBuilder[T, B]) WithConstraint added in v1.1.0

func (b *BinaryBuilder[T, B]) WithConstraint(
	desc string,
	fn func(T) bool,
) *BinaryBuilder[T, B]

WithConstraint adds a constraint to the variable.

fn is called with the environment variable value after it is parsed. If fn returns false the value is considered invalid.

func (*BinaryBuilder[T, B]) WithDefault added in v1.1.0

func (b *BinaryBuilder[T, B]) WithDefault(v T) *BinaryBuilder[T, B]

WithDefault sets a default value of the variable.

v is the raw binary value, not the encoded representation used within the environment variable.

It is used when the environment variable is undefined or empty.

func (*BinaryBuilder[T, B]) WithEncodedDefault added in v1.1.0

func (b *BinaryBuilder[T, B]) WithEncodedDefault(v string) *BinaryBuilder[T, B]

WithEncodedDefault sets a default value of the variable from its encoded string representation.

v is the encoded binary value as used in the environment variable. For example, it may be a base64 string.

It is used when the environment variable is undefined or empty.

func (*BinaryBuilder[T, B]) WithHexEncoding added in v1.1.0

func (b *BinaryBuilder[T, B]) WithHexEncoding() *BinaryBuilder[T, B]

WithHexEncoding configures the variable to use hexadecimal encoding to represent the binary value within the environment.

func (*BinaryBuilder[T, B]) WithLength added in v1.3.0

func (b *BinaryBuilder[T, B]) WithLength(n int) *BinaryBuilder[T, B]

WithLength sets the exact permitted length of the raw binary value, in bytes.

func (*BinaryBuilder[T, B]) WithMaximumLength added in v1.3.0

func (b *BinaryBuilder[T, B]) WithMaximumLength(max int) *BinaryBuilder[T, B]

WithMaximumLength sets the maximum permitted length of the raw binary value, in bytes.

func (*BinaryBuilder[T, B]) WithMinimumLength added in v1.3.0

func (b *BinaryBuilder[T, B]) WithMinimumLength(min int) *BinaryBuilder[T, B]

WithMinimumLength sets the minimum permitted length of the raw binary value, in bytes.

func (*BinaryBuilder[T, B]) WithSensitiveContent added in v1.1.0

func (b *BinaryBuilder[T, B]) WithSensitiveContent() *BinaryBuilder[T, B]

WithSensitiveContent marks the variable as containing sensitive content.

Values of sensitive variables are not printed to the console or included in generated documentation.

type BoolBuilder added in v0.2.0

type BoolBuilder[T ~bool] struct {
	// contains filtered or unexported fields
}

BoolBuilder builds a specification for a boolean value.

func Bool

func Bool(name, desc string) *BoolBuilder[bool]

Bool configures an environment variable as a boolean.

name is the name of the environment variable to read. desc is a human-readable description of the environment variable.

Example (CustomLiterals)
defer example()()

v := ferrite.
	Bool("FERRITE_BOOL", "example boolean variable").
	WithLiterals("yes", "no").
	Required()

os.Setenv("FERRITE_BOOL", "yes")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is true
Example (Default)
defer example()()

v := ferrite.
	Bool("FERRITE_BOOL", "example boolean variable").
	WithDefault(true).
	Required()

ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is true
Example (Deprecated)
defer example()()

v := ferrite.
	Bool("FERRITE_BOOL", "example boolean variable").
	Deprecated()

os.Setenv("FERRITE_BOOL", "true")
ferrite.Init()

if x, ok := v.DeprecatedValue(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

Environment Variables:

 ❯ FERRITE_BOOL  example boolean variable  [ true | false ]  ⚠ deprecated variable set to true

value is true
Example (Optional)
defer example()()

v := ferrite.
	Bool("FERRITE_BOOL", "example boolean variable").
	Optional()

ferrite.Init()

if x, ok := v.Value(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

value is undefined
Example (Required)
defer example()()

v := ferrite.
	Bool("FERRITE_BOOL", "example boolean variable").
	Required()

os.Setenv("FERRITE_BOOL", "true")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is true

func BoolAs

func BoolAs[T ~bool](name, desc string) *BoolBuilder[T]

BoolAs configures an environment variable as a boolean using a user-defined type.

name is the name of the environment variable to read. desc is a human-readable description of the environment variable.

func (*BoolBuilder[T]) Deprecated added in v0.4.0

func (b *BoolBuilder[T]) Deprecated(options ...DeprecatedOption) Deprecated[T]

Deprecated completes the build process and registers a deprecated variable with Ferrite's validation system.

func (*BoolBuilder[T]) Optional added in v0.2.0

func (b *BoolBuilder[T]) Optional(options ...OptionalOption) Optional[T]

Optional completes the build process and registers an optional variable with Ferrite's validation system.

func (*BoolBuilder[T]) Required added in v0.2.0

func (b *BoolBuilder[T]) Required(options ...RequiredOption) Required[T]

Required completes the build process and registers a required variable with Ferrite's validation system.

func (*BoolBuilder[T]) WithDefault added in v0.2.0

func (b *BoolBuilder[T]) WithDefault(v T) *BoolBuilder[T]

WithDefault sets a default value of the variable.

It is used when the environment variable is undefined or empty.

func (*BoolBuilder[T]) WithLiterals added in v0.2.0

func (b *BoolBuilder[T]) WithLiterals(t, f string) *BoolBuilder[T]

WithLiterals overrides the default literals used to represent true and false.

The default literals "true" and "false" are no longer valid values when using custom literals.

type Deprecated added in v0.4.0

type Deprecated[T any] interface {
	VariableSet

	// DeprecatedValue returns the parsed and validated value built from the
	// environment variable(s).
	//
	// If the constituent environment variable(s) are not defined and there is
	// no default value, ok is false; otherwise, ok is true and v is the value.
	//
	// It panics if any of one of the constituent environment variable(s) has an
	// invalid value.
	DeprecatedValue() (T, bool)
}

Deprecated is a VariableSet used to obtain a value that may be unavailable, due to the environment variables not being defined.

type DeprecatedOption added in v0.4.0

type DeprecatedOption interface {
	// contains filtered or unexported methods
}

DeprecatedOption is an option that configures a "deprecated" variable set. It may be passed to the Deprecated() method on each of the "builder" types.

func SupersededBy added in v0.5.0

func SupersededBy(s VariableSet, _ ...SupersededByOption) DeprecatedOption

SupersededBy is a option for a deprecated variable set that indicates the variables in another set, s, should be used instead.

Example
defer example()()

verbose := ferrite.
	Bool("FERRITE_VERBOSE", "enable verbose logging").
	Optional()

ferrite.
	Bool("FERRITE_DEBUG", "enable debug logging").
	Deprecated(ferrite.SupersededBy(verbose))

ferrite.Init()
Output:

type DurationBuilder added in v0.2.0

type DurationBuilder struct {
	// contains filtered or unexported fields
}

DurationBuilder builds a specification for a duration variable.

func Duration

func Duration(name, desc string) *DurationBuilder

Duration configures an environment variable as a duration.

name is the name of the environment variable to read. desc is a human-readable description of the environment variable.

Durations have a minimum value of 1 nanosecond by default.

Example (Default)
defer example()()

v := ferrite.
	Duration("FERRITE_DURATION", "example duration variable").
	WithDefault(630 * time.Second).
	Required()

ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is 10m30s
Example (Deprecated)
defer example()()

v := ferrite.
	Duration("FERRITE_DURATION", "example duration variable").
	Deprecated()

os.Setenv("FERRITE_DURATION", "630s")
ferrite.Init()

if x, ok := v.DeprecatedValue(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

Environment Variables:

 ❯ FERRITE_DURATION  example duration variable  [ 1ns ... ]  ⚠ deprecated variable set to 630s, equivalent to 10m30s

value is 10m30s
Example (Limits)
defer example()()

v := ferrite.
	Duration("FERRITE_DURATION", "example duration variable").
	WithMinimum(-1 * time.Hour).
	WithMaximum(+1 * time.Hour).
	Required()

os.Setenv("FERRITE_DURATION", "0h")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is 0s
Example (Optional)
defer example()()

v := ferrite.
	Duration("FERRITE_DURATION", "example duration variable").
	Optional()

ferrite.Init()

if x, ok := v.Value(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

value is undefined
Example (Required)
defer example()()

v := ferrite.
	Duration("FERRITE_DURATION", "example duration variable").
	Required()

os.Setenv("FERRITE_DURATION", "630s")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is 10m30s

func (*DurationBuilder) Deprecated added in v0.4.0

func (b *DurationBuilder) Deprecated(options ...DeprecatedOption) Deprecated[time.Duration]

Deprecated completes the build process and registers a deprecated variable with Ferrite's validation system.

func (*DurationBuilder) Optional added in v0.2.0

func (b *DurationBuilder) Optional(options ...OptionalOption) Optional[time.Duration]

Optional completes the build process and registers an optional variable with Ferrite's validation system.

func (*DurationBuilder) Required added in v0.2.0

func (b *DurationBuilder) Required(options ...RequiredOption) Required[time.Duration]

Required completes the build process and registers a required variable with Ferrite's validation system.

func (*DurationBuilder) WithDefault added in v0.2.0

func (b *DurationBuilder) WithDefault(v time.Duration) *DurationBuilder

WithDefault sets a default value of the variable.

It is used when the environment variable is undefined or empty.

func (*DurationBuilder) WithMaximum added in v0.3.2

func (b *DurationBuilder) WithMaximum(v time.Duration) *DurationBuilder

WithMaximum sets the maximum acceptable value of the variable.

func (*DurationBuilder) WithMinimum added in v0.3.2

func (b *DurationBuilder) WithMinimum(v time.Duration) *DurationBuilder

WithMinimum sets the minimum acceptable value of the variable.

type EnumBuilder added in v0.2.0

type EnumBuilder[T any] struct {
	// contains filtered or unexported fields
}

EnumBuilder is the specification for an enumeration.

func Enum

func Enum(name, desc string) *EnumBuilder[string]

Enum configures an environment variable as an enumeration.

name is the name of the environment variable to read. desc is a human-readable description of the environment variable.

Example (Default)
defer example()()

v := ferrite.
	Enum("FERRITE_ENUM", "example enum variable").
	WithMembers("red", "green", "blue").
	WithDefault("green").
	Required()

ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is green
Example (Deprecated)
defer example()()

v := ferrite.
	Enum("FERRITE_ENUM", "example enum variable").
	WithMember("red", "the color red").
	WithMember("green", "the color green").
	WithMember("blue", "the color blue").
	Deprecated()

os.Setenv("FERRITE_ENUM", "red")
ferrite.Init()

if x, ok := v.DeprecatedValue(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

Environment Variables:

 ❯ FERRITE_ENUM  example enum variable  [ red | green | blue ]  ⚠ deprecated variable set to red

value is red
Example (Descriptions)
defer example()()

v := ferrite.
	Enum("FERRITE_ENUM", "example enum variable").
	WithMember("red", "the color red").
	WithMember("green", "the color green").
	WithMember("blue", "the color blue").
	Required()

os.Setenv("FERRITE_ENUM", "red")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is red
Example (Optional)
defer example()()

v := ferrite.
	Enum("FERRITE_ENUM", "example enum variable").
	WithMembers("red", "green", "blue").
	Optional()

ferrite.Init()
if x, ok := v.Value(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

value is undefined
Example (Required)
defer example()()

v := ferrite.
	Enum("FERRITE_ENUM", "example enum variable").
	WithMembers("red", "green", "blue").
	Required()

os.Setenv("FERRITE_ENUM", "red")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is red

func EnumAs added in v0.2.0

func EnumAs[T any](name, desc string) *EnumBuilder[T]

EnumAs configures an environment variable as an enumeration with members of type T.

name is the name of the environment variable to read. desc is a human-readable description of the environment variable.

func (*EnumBuilder[T]) Deprecated added in v0.4.0

func (b *EnumBuilder[T]) Deprecated(options ...DeprecatedOption) Deprecated[T]

Deprecated completes the build process and registers a deprecated variable with Ferrite's validation system.

func (*EnumBuilder[T]) Optional added in v0.2.0

func (b *EnumBuilder[T]) Optional(options ...OptionalOption) Optional[T]

Optional completes the build process and registers an optional variable with Ferrite's validation system.

func (*EnumBuilder[T]) Required added in v0.2.0

func (b *EnumBuilder[T]) Required(options ...RequiredOption) Required[T]

Required completes the build process and registers a required variable with Ferrite's validation system.

func (*EnumBuilder[T]) WithDefault added in v0.2.0

func (b *EnumBuilder[T]) WithDefault(v T) *EnumBuilder[T]

WithDefault sets a default value of the variable.

It is used when the environment variable is undefined or empty.

func (*EnumBuilder[T]) WithMember added in v0.3.0

func (b *EnumBuilder[T]) WithMember(v T, desc string) *EnumBuilder[T]

WithMember adds a member to the enum.

The environment variable must be set to the string representation of one of the member values. v must not have an empty string representation.

func (*EnumBuilder[T]) WithMembers added in v0.2.0

func (b *EnumBuilder[T]) WithMembers(values ...T) *EnumBuilder[T]

WithMembers adds members to the enum.

The environment variable must be set to the string representation of one of the member values. The values must not have an empty string representation.

func (*EnumBuilder[T]) WithRenderer added in v0.2.0

func (b *EnumBuilder[T]) WithRenderer(fn func(T) variable.Literal) *EnumBuilder[T]

WithRenderer sets the function used to generate the literal string representation of the enum's member values.

type FileBuilder added in v0.3.2

type FileBuilder struct {
	// contains filtered or unexported fields
}

FileBuilder builds a specification for a boolean value.

func File added in v0.3.2

func File(name, desc string) *FileBuilder

File configures an environment variable as a filename.

name is the name of the environment variable to read. desc is a human-readable description of the environment variable.

Example (ContentAsBytes)
defer example()()

v := ferrite.
	File("FERRITE_FILE", "example file variable").
	Required()

os.Setenv("FERRITE_FILE", "testdata/hello.txt")
ferrite.Init()

data, err := v.Value().ReadBytes()
if err != nil {
	panic(err)
}

fmt.Printf("file content is %#v\n", string(data))
Output:

file content is "Hello, world!\n"
Example (ContentAsReader)
defer example()()

v := ferrite.
	File("FERRITE_FILE", "example file variable").
	Required()

os.Setenv("FERRITE_FILE", "testdata/hello.txt")
ferrite.Init()

r, err := v.Value().Reader()
if err != nil {
	panic(err)
}
defer r.Close()

data, err := io.ReadAll(r)
if err != nil {
	panic(err)
}

fmt.Printf("file content is %#v\n", string(data))
Output:

file content is "Hello, world!\n"
Example (ContentAsString)
defer example()()

v := ferrite.
	File("FERRITE_FILE", "example file variable").
	Required()

os.Setenv("FERRITE_FILE", "testdata/hello.txt")
ferrite.Init()

data, err := v.Value().ReadString()
if err != nil {
	panic(err)
}

fmt.Printf("file content is %#v\n", data)
Output:

file content is "Hello, world!\n"
Example (Default)
defer example()()

v := ferrite.
	File("FERRITE_FILE", "example file variable").
	WithDefault("testdata/hello.txt").
	Required()

ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is testdata/hello.txt
Example (Deprecated)
defer example()()

v := ferrite.
	File("FERRITE_FILE", "example file variable").
	Deprecated()

os.Setenv("FERRITE_FILE", "testdata/hello.txt")
ferrite.Init()

if x, ok := v.DeprecatedValue(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

Environment Variables:

 ❯ FERRITE_FILE  example file variable  [ <string> ]  ⚠ deprecated variable set to testdata/hello.txt

value is testdata/hello.txt
Example (Optional)
defer example()()

v := ferrite.
	File("FERRITE_FILE", "example file variable").
	Optional()

ferrite.Init()

if x, ok := v.Value(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

value is undefined
Example (Required)
defer example()()

v := ferrite.
	File("FERRITE_FILE", "example file variable").
	Required()

os.Setenv("FERRITE_FILE", "testdata/hello.txt")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is testdata/hello.txt

func (*FileBuilder) Deprecated added in v0.4.0

func (b *FileBuilder) Deprecated(options ...DeprecatedOption) Deprecated[FileName]

Deprecated completes the build process and registers a deprecated variable with Ferrite's validation system.

func (*FileBuilder) Optional added in v0.3.2

func (b *FileBuilder) Optional(options ...OptionalOption) Optional[FileName]

Optional completes the build process and registers an optional variable with Ferrite's validation system.

func (*FileBuilder) Required added in v0.3.2

func (b *FileBuilder) Required(options ...RequiredOption) Required[FileName]

Required completes the build process and registers a required variable with Ferrite's validation system.

func (*FileBuilder) WithDefault added in v0.3.2

func (b *FileBuilder) WithDefault(v string) *FileBuilder

WithDefault sets a default value of the variable.

It is used when the environment variable is undefined or empty.

type FileName added in v0.3.2

type FileName string

FileName is the name of a file.

func (FileName) ReadBytes added in v0.3.2

func (n FileName) ReadBytes() ([]byte, error)

ReadBytes returns the contents of the file as a byte slice.

func (FileName) ReadString added in v0.3.2

func (n FileName) ReadString() (string, error)

ReadString returns the contents of the file as a string.

func (FileName) Reader added in v0.3.2

func (n FileName) Reader() (io.ReadCloser, error)

Reader returns a reader that produces the contents of the file.

type FloatBuilder added in v0.3.2

type FloatBuilder[T constraints.Float] struct {
	// contains filtered or unexported fields
}

FloatBuilder builds a specification for a floating-point number.

func Float added in v0.3.2

func Float[T constraints.Float](name, desc string) *FloatBuilder[T]

Float configures an environment variable as a floating-point number.

name is the name of the environment variable to read. desc is a human-readable description of the environment variable.

Example (Default)
defer example()()

v := ferrite.
	Float[float64]("FERRITE_FLOAT", "example floating-point variable").
	WithDefault(-123.45).
	Required()

ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is -123.45
Example (Deprecated)
defer example()()

v := ferrite.
	Float[float64]("FERRITE_FLOAT", "example floating-point variable").
	Deprecated()

os.Setenv("FERRITE_FLOAT", "-123.45")
ferrite.Init()

if x, ok := v.DeprecatedValue(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

Environment Variables:

 ❯ FERRITE_FLOAT  example floating-point variable  [ <float64> ]  ⚠ deprecated variable set to -123.45

value is -123.45
Example (Limits)
defer example()()

v := ferrite.
	Float[float64]("FERRITE_FLOAT", "example floating-point variable").
	WithMinimum(-5).
	WithMaximum(10).
	Required()

os.Setenv("FERRITE_FLOAT", "-2")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is -2
Example (Optional)
defer example()()

v := ferrite.
	Float[float64]("FERRITE_FLOAT", "example floating-point variable").
	Optional()

ferrite.Init()

if x, ok := v.Value(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

value is undefined
Example (Required)
defer example()()

v := ferrite.
	Float[float64]("FERRITE_FLOAT", "example floating-point variable").
	Required()

os.Setenv("FERRITE_FLOAT", "-123.45")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is -123.45

func (*FloatBuilder[T]) Deprecated added in v0.4.0

func (b *FloatBuilder[T]) Deprecated(options ...DeprecatedOption) Deprecated[T]

Deprecated completes the build process and registers a deprecated variable with Ferrite's validation system.

func (*FloatBuilder[T]) Optional added in v0.3.2

func (b *FloatBuilder[T]) Optional(options ...OptionalOption) Optional[T]

Optional completes the build process and registers an optional variable with Ferrite's validation system.

func (*FloatBuilder[T]) Required added in v0.3.2

func (b *FloatBuilder[T]) Required(options ...RequiredOption) Required[T]

Required completes the build process and registers a required variable with Ferrite's validation system.

func (*FloatBuilder[T]) WithDefault added in v0.3.2

func (b *FloatBuilder[T]) WithDefault(v T) *FloatBuilder[T]

WithDefault sets a default value of the variable.

It is used when the environment variable is undefined or empty.

func (*FloatBuilder[T]) WithMaximum added in v0.3.2

func (b *FloatBuilder[T]) WithMaximum(v T) *FloatBuilder[T]

WithMaximum sets the maximum acceptable value of the variable.

func (*FloatBuilder[T]) WithMinimum added in v0.3.2

func (b *FloatBuilder[T]) WithMinimum(v T) *FloatBuilder[T]

WithMinimum sets the minimum acceptable value of the variable.

type InitOption added in v0.4.0

type InitOption interface {
	// contains filtered or unexported methods
}

An InitOption changes the behavior of the Init() function.

type KubernetesAddress added in v0.2.0

type KubernetesAddress struct {
	Host string
	Port string
}

KubernetesAddress is the address of a Kubernetes service.

func (KubernetesAddress) String added in v0.2.0

func (a KubernetesAddress) String() string

type KubernetesServiceBuilder added in v0.2.0

type KubernetesServiceBuilder struct {
	// contains filtered or unexported fields
}

KubernetesServiceBuilder is the specification for a Kubernetes service.

func KubernetesService added in v0.2.0

func KubernetesService(svc string) *KubernetesServiceBuilder

KubernetesService configures environment variables used to obtain the network address of a specific Kubernetes service.

svc is the name of the Kubernetes service, NOT the environment variable.

The environment variables "<svc>_SERVICE_HOST" and "<svc>_SERVICE_PORT" are used to construct an address for the service.

Example (Default)
defer example()()

v := ferrite.
	KubernetesService("ferrite-svc").
	WithDefault("host.example.org", "12345").
	Required()

ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is host.example.org:12345
Example (Deprecated)
defer example()()

v := ferrite.
	KubernetesService("ferrite-svc").
	Deprecated()

os.Setenv("FERRITE_SVC_SERVICE_HOST", "host.example.org")
os.Setenv("FERRITE_SVC_SERVICE_PORT", "12345")
ferrite.Init()

if x, ok := v.DeprecatedValue(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

Environment Variables:

 ❯ FERRITE_SVC_SERVICE_HOST  kubernetes "ferrite-svc" service host  [ <string> ]  ⚠ deprecated variable set to host.example.org
 ❯ FERRITE_SVC_SERVICE_PORT  kubernetes "ferrite-svc" service port  [ <string> ]  ⚠ deprecated variable set to 12345

value is host.example.org:12345
Example (NamedPort)
defer example()()

v := ferrite.
	KubernetesService("ferrite-svc").
	WithNamedPort("api").
	Required()

os.Setenv("FERRITE_SVC_SERVICE_HOST", "host.example.org")
os.Setenv("FERRITE_SVC_SERVICE_PORT_API", "12345") // note _API suffix
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is host.example.org:12345
Example (Optional)
defer example()()

v := ferrite.
	KubernetesService("ferrite-svc").
	Optional()

ferrite.Init()

if x, ok := v.Value(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

value is undefined
Example (Required)
defer example()()

v := ferrite.
	KubernetesService("ferrite-svc").
	Required()

os.Setenv("FERRITE_SVC_SERVICE_HOST", "host.example.org")
os.Setenv("FERRITE_SVC_SERVICE_PORT", "12345")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is host.example.org:12345

func (*KubernetesServiceBuilder) Deprecated added in v0.4.0

Deprecated completes the build process and registers deprecated variables with Ferrite's validation system.

func (*KubernetesServiceBuilder) Optional added in v0.2.0

Optional completes the build process and registers optional variables with Ferrite's validation system.

func (*KubernetesServiceBuilder) Required added in v0.2.0

Required completes the build process and registers required variables with Ferrite's validation system.

func (*KubernetesServiceBuilder) WithDefault added in v0.2.0

func (b *KubernetesServiceBuilder) WithDefault(host, port string) *KubernetesServiceBuilder

WithDefault sets a default value to use when the environment variables are undefined.

The port may be a numeric value between 1 and 65535, or an IANA registered service name (such as "https"). The IANA name is not to be confused with the Kubernetes servcice name or port name.

func (*KubernetesServiceBuilder) WithNamedPort added in v0.2.0

WithNamedPort uses a Kubernetes named port instead of the default service port.

The "<service>_SERVICE_PORT_<port>" environment variable is used instead of "<service>_SERVICE_PORT".

The Kubernetes port name is the name configured in the service manifest. It is not to be confused with an IANA registered service name (e.g. "https"), although the two may use the same names.

See https://kubernetes.io/docs/concepts/services-networking/service/#multi-port-services

type NetworkPortBuilder added in v0.4.0

type NetworkPortBuilder struct {
	// contains filtered or unexported fields
}

NetworkPortBuilder builds a specification for a network port variable.

func NetworkPort added in v0.3.1

func NetworkPort(name, desc string) *NetworkPortBuilder

NetworkPort configures an environment variable as a network port.

name is the name of the environment variable to read. desc is a human-readable description of the environment variable.

Example (Default)
defer example()()

v := ferrite.
	NetworkPort("FERRITE_NETWORK_PORT", "example network port variable").
	WithDefault("12345").
	Required()

ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is 12345
Example (Deprecated)
defer example()()

v := ferrite.
	NetworkPort("FERRITE_NETWORK_PORT", "example network port variable").
	Deprecated()

os.Setenv("FERRITE_NETWORK_PORT", "https")
ferrite.Init()

if x, ok := v.DeprecatedValue(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

Environment Variables:

 ❯ FERRITE_NETWORK_PORT  example network port variable  [ <string> ]  ⚠ deprecated variable set to https

value is https
Example (Optional)
defer example()()

v := ferrite.
	NetworkPort("FERRITE_NETWORK_PORT", "example network port variable").
	Optional()

ferrite.Init()

if x, ok := v.Value(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

value is undefined
Example (Required)
defer example()()

v := ferrite.
	NetworkPort("FERRITE_NETWORK_PORT", "example network port variable").
	Required()

os.Setenv("FERRITE_NETWORK_PORT", "https")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is https

func (*NetworkPortBuilder) Deprecated added in v0.4.0

func (b *NetworkPortBuilder) Deprecated(options ...DeprecatedOption) Deprecated[string]

Deprecated completes the build process and registers a deprecated variable with Ferrite's validation system.

func (*NetworkPortBuilder) Optional added in v0.4.0

func (b *NetworkPortBuilder) Optional(options ...OptionalOption) Optional[string]

Optional completes the build process and registers an optional variable with Ferrite's validation system.

func (*NetworkPortBuilder) Required added in v0.4.0

func (b *NetworkPortBuilder) Required(options ...RequiredOption) Required[string]

Required completes the build process and registers a required variable with Ferrite's validation system.

func (*NetworkPortBuilder) WithDefault added in v0.4.0

func (b *NetworkPortBuilder) WithDefault(v string) *NetworkPortBuilder

WithDefault sets a default value of the variable.

It is used when the environment variable is undefined or empty.

type Optional added in v0.2.0

type Optional[T any] interface {
	VariableSet

	// Value returns the parsed and validated value.
	//
	// It returns a non-nil error if any of one of the environment variables in
	// the set has an invalid value.
	//
	// If the environment variable(s) are not defined and there is no default
	// value, ok is false; otherwise, ok is true and v is the value.
	Value() (T, bool)
}

Optional is a VariableSet used to obtain a value that may be unavailable, due to the environment variables not being defined.

type OptionalOption added in v0.4.0

type OptionalOption interface {
	// contains filtered or unexported methods
}

OptionalOption is an option that configures an "optional" variable set. It may be passed to the Optional() method on each of the "builder" types.

type Registry added in v1.2.0

type Registry interface {
	variable.ProtectedRegistry
}

A Registry is a collection of environment variable specifications.

Example
defer example()()

// Create a custom registry.
reg := ferrite.NewRegistry(
	"my-registry",
	"My Registry",
	ferrite.WithDocumentationURL("https://example.com/registry.html"),
)

// Define an environment variable specification within that registry.
ferrite.
	String("FERRITE_STRING", "example string variable").
	Required(
		ferrite.WithRegistry(reg),
	)

// Import the custom registry when initializing Ferrite. Multiple custom
// registries can be imported. The default global registry is always used.
ferrite.Init(
	ferrite.WithRegistry(reg),
)
Output:

Environment Variables:

 ❯ FERRITE_STRING  example string variable    <string>    ✗ undefined

<process exited with error code 1>

func NewRegistry added in v1.2.0

func NewRegistry(
	key, name string,
	options ...RegistryOption,
) Registry

NewRegistry returns a new environment variable registry.

Use the WithRegistry option to configure an environment variable definition or Init call to use a specific registry.

type RegistryOption added in v1.2.0

type RegistryOption interface {
	// contains filtered or unexported methods
}

RegistryOption is an option that configures the behavior of a registry.

func WithDocumentationURL added in v1.2.0

func WithDocumentationURL(u string) RegistryOption

WithDocumentationURL is a RegistryOption that adds a link to some supplementary documentation.

type RelevantIfOption added in v0.6.0

type RelevantIfOption interface {
	// contains filtered or unexported methods
}

RelevantIfOption changes the behavior of the RelevantIf() option.

type Required added in v0.2.0

type Required[T any] interface {
	VariableSet

	// Value returns the parsed and validated value.
	//
	// It panics if any of one of the environment variables in the set is
	// undefined or has an invalid value.
	Value() T
}

Required is a VariableSet used to obtain a value that must always be available, either from explicit environment variable values or by falling back to defaults.

type RequiredOption added in v0.4.0

type RequiredOption interface {
	// contains filtered or unexported methods
}

RequiredOption is an option that configures a "required" variable set. It may be passed to the Optional() method on each of the "builder" types.

type SeeAlsoOption added in v0.5.0

type SeeAlsoOption interface {
	// contains filtered or unexported methods
}

SeeAlsoOption configures the behavior of the SeeAlso() variable set option.

type SignedBuilder added in v0.2.0

type SignedBuilder[T constraints.Signed] struct {
	// contains filtered or unexported fields
}

SignedBuilder builds a specification for a signed integer value.

func Signed

func Signed[T constraints.Signed](name, desc string) *SignedBuilder[T]

Signed configures an environment variable as a signed integer.

name is the name of the environment variable to read. desc is a human-readable description of the environment variable.

Example (Default)
defer example()()

v := ferrite.
	Signed[int]("FERRITE_SIGNED", "example signed integer variable").
	WithDefault(-123).
	Required()

ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is -123
Example (Deprecated)
defer example()()

v := ferrite.
	Signed[int]("FERRITE_SIGNED", "example signed integer variable").
	Deprecated()

os.Setenv("FERRITE_SIGNED", "-123")
ferrite.Init()

if x, ok := v.DeprecatedValue(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

Environment Variables:

 ❯ FERRITE_SIGNED  example signed integer variable  [ <int> ]  ⚠ deprecated variable set to -123

value is -123
Example (Limits)
defer example()()

v := ferrite.
	Signed[int]("FERRITE_SIGNED", "example signed integer variable").
	WithMinimum(-5).
	WithMaximum(10).
	Required()

os.Setenv("FERRITE_SIGNED", "-2")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is -2
Example (Optional)
defer example()()

v := ferrite.
	Signed[int]("FERRITE_SIGNED", "example signed integer variable").
	Optional()

ferrite.Init()

if x, ok := v.Value(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

value is undefined
Example (Required)
defer example()()

v := ferrite.
	Signed[int]("FERRITE_SIGNED", "example signed integer variable").
	Required()

os.Setenv("FERRITE_SIGNED", "-123")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is -123

func (*SignedBuilder[T]) Deprecated added in v0.4.0

func (b *SignedBuilder[T]) Deprecated(options ...DeprecatedOption) Deprecated[T]

Deprecated completes the build process and registers a deprecated variable with Ferrite's validation system.

func (*SignedBuilder[T]) Optional added in v0.2.0

func (b *SignedBuilder[T]) Optional(options ...OptionalOption) Optional[T]

Optional completes the build process and registers an optional variable with Ferrite's validation system.

func (*SignedBuilder[T]) Required added in v0.2.0

func (b *SignedBuilder[T]) Required(options ...RequiredOption) Required[T]

Required completes the build process and registers a required variable with Ferrite's validation system.

func (*SignedBuilder[T]) WithDefault added in v0.2.0

func (b *SignedBuilder[T]) WithDefault(v T) *SignedBuilder[T]

WithDefault sets a default value of the variable.

It is used when the environment variable is undefined or empty.

func (*SignedBuilder[T]) WithMaximum added in v0.3.2

func (b *SignedBuilder[T]) WithMaximum(v T) *SignedBuilder[T]

WithMaximum sets the maximum acceptable value of the variable.

func (*SignedBuilder[T]) WithMinimum added in v0.3.2

func (b *SignedBuilder[T]) WithMinimum(v T) *SignedBuilder[T]

WithMinimum sets the minimum acceptable value of the variable.

type StringBuilder added in v0.2.0

type StringBuilder[T ~string] struct {
	// contains filtered or unexported fields
}

StringBuilder builds a specification for a string variable.

func String

func String(name, desc string) *StringBuilder[string]

String configures an environment variable as a string.

name is the name of the environment variable to read. desc is a human-readable description of the environment variable.

Example (Default)
defer example()()

v := ferrite.
	String("FERRITE_STRING", "example string variable").
	WithDefault("<default>").
	Required()

ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is <default>
Example (Deprecated)
defer example()()

v := ferrite.
	String("FERRITE_STRING", "example string variable").
	Deprecated()

os.Setenv("FERRITE_STRING", "<value>")
ferrite.Init()

if x, ok := v.DeprecatedValue(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

Environment Variables:

 ❯ FERRITE_STRING  example string variable  [ <string> ]  ⚠ deprecated variable set to '<value>'

value is <value>
Example (Limits)
defer example()()

v := ferrite.
	String("FERRITE_STRING", "example string variable").
	WithMinimumLength(5).
	WithMaximumLength(10).
	Required()

os.Setenv("FERRITE_STRING", "<value>")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is <value>
Example (Optional)
defer example()()

v := ferrite.
	String("FERRITE_STRING", "example string variable").
	Optional()

ferrite.Init()

if x, ok := v.Value(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

value is undefined
Example (Required)
defer example()()

v := ferrite.
	String("FERRITE_STRING", "example string variable").
	Required()

os.Setenv("FERRITE_STRING", "<value>")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is <value>
Example (Sensitive)
defer example()()

ferrite.
	String("FERRITE_STRING", "example sensitive string variable").
	WithConstraint(
		"always fail",
		func(v string) bool {
			// Force the variable to be considered invalid so that the
			// variable table is rendered to the console.
			return false
		},
	).
	WithSensitiveContent().
	Required()

os.Setenv("FERRITE_STRING", "hunter2")
ferrite.Init()

// Note that the variable's value is obscured in the console output.
Output:

Environment Variables:

 ❯ FERRITE_STRING  example sensitive string variable    <string>    ✗ set to *******, always fail

<process exited with error code 1>

func StringAs

func StringAs[T ~string](name, desc string) *StringBuilder[T]

StringAs configures an environment variable as a string using a user-defined type.

name is the name of the environment variable to read. desc is a human-readable description of the environment variable.

func (*StringBuilder[T]) Deprecated added in v0.4.0

func (b *StringBuilder[T]) Deprecated(options ...DeprecatedOption) Deprecated[T]

Deprecated completes the build process and registers a deprecated variable with Ferrite's validation system.

func (*StringBuilder[T]) Optional added in v0.2.0

func (b *StringBuilder[T]) Optional(options ...OptionalOption) Optional[T]

Optional completes the build process and registers an optional variable with Ferrite's validation system.

func (*StringBuilder[T]) Required added in v0.2.0

func (b *StringBuilder[T]) Required(options ...RequiredOption) Required[T]

Required completes the build process and registers a required variable with Ferrite's validation system.

func (*StringBuilder[T]) WithConstraint added in v0.5.0

func (b *StringBuilder[T]) WithConstraint(
	desc string,
	fn func(T) bool,
) *StringBuilder[T]

WithConstraint adds a constraint to the variable.

fn is called with the environment variable value after it is parsed. If fn returns false the value is considered invalid.

func (*StringBuilder[T]) WithDefault added in v0.2.0

func (b *StringBuilder[T]) WithDefault(v T) *StringBuilder[T]

WithDefault sets a default value of the variable.

It is used when the environment variable is undefined or empty.

func (*StringBuilder[T]) WithLength added in v1.3.0

func (b *StringBuilder[T]) WithLength(n int) *StringBuilder[T]

WithLength sets the exact permitted length of the variable, in bytes (not runes).

func (*StringBuilder[T]) WithMaximumLength added in v1.3.0

func (b *StringBuilder[T]) WithMaximumLength(max int) *StringBuilder[T]

WithMaximumLength sets the maximum permitted length of the variable, in bytes (not runes).

func (*StringBuilder[T]) WithMinimumLength added in v1.3.0

func (b *StringBuilder[T]) WithMinimumLength(min int) *StringBuilder[T]

WithMinimumLength sets the minimum permitted length of the variable, in bytes (not runes).

func (*StringBuilder[T]) WithSensitiveContent added in v0.4.0

func (b *StringBuilder[T]) WithSensitiveContent() *StringBuilder[T]

WithSensitiveContent marks the variable as containing sensitive content.

Values of sensitive variables are not printed to the console or included in generated documentation.

type SupersededByOption added in v0.6.0

type SupersededByOption interface {
	// contains filtered or unexported methods
}

SupersededByOption changes the behavior of the SupersededBy() option.

type URLBuilder added in v0.3.3

type URLBuilder struct {
	// contains filtered or unexported fields
}

URLBuilder builds a specification for a URL variable.

func URL added in v0.3.3

func URL(name, desc string) *URLBuilder

URL configures an environment variable as a URL.

The URL must be fully-qualified (i.e. it must have a scheme and hostname).

name is the name of the environment variable to read. desc is a human-readable description of the environment variable.

Example (Default)
defer example()()

v := ferrite.
	URL("FERRITE_URL", "example URL variable").
	WithDefault("https://example.org/default").
	Required()

ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is https://example.org/default
Example (Deprecated)
defer example()()

v := ferrite.
	URL("FERRITE_URL", "example URL variable").
	Deprecated()

os.Setenv("FERRITE_URL", "https://example.org/path")
ferrite.Init()

if x, ok := v.DeprecatedValue(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

Environment Variables:

 ❯ FERRITE_URL  example URL variable  [ <string> ]  ⚠ deprecated variable set to https://example.org/path

value is https://example.org/path
Example (Optional)
defer example()()

v := ferrite.
	URL("FERRITE_URL", "example URL variable").
	Optional()

ferrite.Init()

if x, ok := v.Value(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

value is undefined
Example (Required)
defer example()()

v := ferrite.
	URL("FERRITE_URL", "example URL variable").
	Required()

os.Setenv("FERRITE_URL", "https://example.org/path")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is https://example.org/path

func (*URLBuilder) Deprecated added in v0.4.0

func (b *URLBuilder) Deprecated(options ...DeprecatedOption) Deprecated[*url.URL]

Deprecated completes the build process and registers a deprecated variable with Ferrite's validation system.

func (*URLBuilder) Optional added in v0.3.3

func (b *URLBuilder) Optional(options ...OptionalOption) Optional[*url.URL]

Optional completes the build process and registers an optional variable with Ferrite's validation system.

func (*URLBuilder) Required added in v0.3.3

func (b *URLBuilder) Required(options ...RequiredOption) Required[*url.URL]

Required completes the build process and registers a required variable with Ferrite's validation system.

func (*URLBuilder) WithDefault added in v0.3.3

func (b *URLBuilder) WithDefault(v string) *URLBuilder

WithDefault sets a default value of the variable.

It is used when the environment variable is undefined or empty.

type UnsignedBuilder added in v0.2.0

type UnsignedBuilder[T constraints.Unsigned] struct {
	// contains filtered or unexported fields
}

UnsignedBuilder builds a specification for an unsigned integer value.

func Unsigned

func Unsigned[T constraints.Unsigned](name, desc string) *UnsignedBuilder[T]

Unsigned configures an environment variable as a unsigned integer.

name is the name of the environment variable to read. desc is a human-readable description of the environment variable.

Example (Default)
defer example()()

v := ferrite.
	Unsigned[uint]("FERRITE_UNSIGNED", "example unsigned integer variable").
	WithDefault(123).
	Required()

ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is 123
Example (Deprecated)
defer example()()

v := ferrite.
	Unsigned[uint]("FERRITE_UNSIGNED", "example unsigned integer variable").
	Deprecated()

os.Setenv("FERRITE_UNSIGNED", "123")
ferrite.Init()

if x, ok := v.DeprecatedValue(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

Environment Variables:

 ❯ FERRITE_UNSIGNED  example unsigned integer variable  [ <uint> ]  ⚠ deprecated variable set to 123

value is 123
Example (Limits)
defer example()()

v := ferrite.
	Unsigned[uint]("FERRITE_UNSIGNED", "example unsigned integer variable").
	WithMinimum(5).
	WithMaximum(10).
	Required()

os.Setenv("FERRITE_UNSIGNED", "7")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is 7
Example (Optional)
defer example()()

v := ferrite.
	Unsigned[uint]("FERRITE_UNSIGNED", "example unsigned integer variable").
	Optional()

ferrite.Init()

if x, ok := v.Value(); ok {
	fmt.Println("value is", x)
} else {
	fmt.Println("value is undefined")
}
Output:

value is undefined
Example (Required)
defer example()()

v := ferrite.
	Unsigned[uint]("FERRITE_UNSIGNED", "example unsigned integer variable").
	Required()

os.Setenv("FERRITE_UNSIGNED", "123")
ferrite.Init()

fmt.Println("value is", v.Value())
Output:

value is 123

func (*UnsignedBuilder[T]) Deprecated added in v0.4.0

func (b *UnsignedBuilder[T]) Deprecated(options ...DeprecatedOption) Deprecated[T]

Deprecated completes the build process and registers a deprecated variable with Ferrite's validation system.

func (*UnsignedBuilder[T]) Optional added in v0.2.0

func (b *UnsignedBuilder[T]) Optional(options ...OptionalOption) Optional[T]

Optional completes the build process and registers an optional variable with Ferrite's validation system.

func (*UnsignedBuilder[T]) Required added in v0.2.0

func (b *UnsignedBuilder[T]) Required(options ...RequiredOption) Required[T]

Required completes the build process and registers a required variable with Ferrite's validation system.

func (*UnsignedBuilder[T]) WithDefault added in v0.2.0

func (b *UnsignedBuilder[T]) WithDefault(v T) *UnsignedBuilder[T]

WithDefault sets a default value of the variable.

It is used when the environment variable is undefined or empty.

func (*UnsignedBuilder[T]) WithMaximum added in v0.3.2

func (b *UnsignedBuilder[T]) WithMaximum(v T) *UnsignedBuilder[T]

WithMaximum sets the maximum acceptable value of the variable.

func (*UnsignedBuilder[T]) WithMinimum added in v0.3.2

func (b *UnsignedBuilder[T]) WithMinimum(v T) *UnsignedBuilder[T]

WithMinimum sets the minimum acceptable value of the variable.

type VariableSet added in v0.6.0

type VariableSet interface {
	// contains filtered or unexported methods
}

VariableSet is the application-facing interface for obtaining a value constructed from one or more environment variables.

A variable set is obtained using one of the many "builder" types returned by functions such as Bool(), String(), etc.

It is common for a variable set to contain a single variable. However, some builders produce sets containing multiple variables.

Directories

Path Synopsis
internal
diff
Package diff implements a basic diff algorithm equivalent to patience diff.
Package diff implements a basic diff algorithm equivalent to patience diff.
environment
Package environment is an abstraction that Ferrite uses to interact with the environment.
Package environment is an abstraction that Ferrite uses to interact with the environment.
inflect
Package inflect provides utilities for inflecting English words.
Package inflect provides utilities for inflecting English words.
limits
Package limits allows finding the limits of arbitrary numeric types.
Package limits allows finding the limits of arbitrary numeric types.
maybe
Package maybe implements a maybe type, also known as an option(al) type.
Package maybe implements a maybe type, also known as an option(al) type.
mode
Package mode is an abstraction for executing the various "modes" supported by Ferrite.
Package mode is an abstraction for executing the various "modes" supported by Ferrite.
mode/export/dotenv
Package dotenv is a Ferrite mode that exports the environment variables to a file suitable use as a .env file.
Package dotenv is a Ferrite mode that exports the environment variables to a file suitable use as a .env file.
mode/internal/render
Package render contains utilities for rendering variable values and schema descriptions in a consistent way across various modes.
Package render contains utilities for rendering variable values and schema descriptions in a consistent way across various modes.
mode/usage/markdown
Package markdown is a Ferrite mode that generates usage documentation in markdown format.
Package markdown is a Ferrite mode that generates usage documentation in markdown format.
mode/validate
Package validate is a Ferrite mode that validates environment variable values against a set of specifications and exits the process if any are invalid.
Package validate is a Ferrite mode that validates environment variable values against a set of specifications and exits the process if any are invalid.
reflectx
Package reflectx contains reflection-related utilities.
Package reflectx contains reflection-related utilities.
variable
Package variable contains utilities for describing and representing environment variables.
Package variable contains utilities for describing and representing environment variables.
wordwrap
Package wordwrap provides a unicode-aware line-wrapping implementation.
Package wordwrap provides a unicode-aware line-wrapping implementation.

Jump to

Keyboard shortcuts

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