zoobzio January 23, 2026 Edit this page

API Reference

Functions

Load

func Load[T any](cfg *T, provider ...SecretProvider) error

Populates a struct from environment variables, secrets, and defaults.

Type Parameters:

  • T — any struct type

Parameters:

  • cfg — pointer to the struct to populate
  • provider — optional secret provider (only the first is used)

Returns: error — nil on success, or:

  • ErrNotStruct if T is not a struct type
  • *FieldError wrapping ErrRequired for missing required fields
  • *FieldError wrapping ErrInvalidType for type conversion failures
  • *FieldError wrapping provider errors
  • Validation error if the struct implements Validator

Resolution Order: secret → env → default → zero value

Example:

type Config struct {
    Host string `env:"APP_HOST" default:"localhost"`
    Port int    `env:"APP_PORT" default:"8080"`
}

var cfg Config
if err := fig.Load(&cfg); err != nil {
    log.Fatal(err)
}

With secret provider:

provider, _ := vault.New()

var cfg Config
if err := fig.Load(&cfg, provider); err != nil {
    log.Fatal(err)
}

LoadContext

func LoadContext[T any](ctx context.Context, cfg *T, provider ...SecretProvider) error

Populates a struct with context support for secret provider timeouts.

Type Parameters:

  • T — any struct type

Parameters:

  • ctx — context for secret provider calls
  • cfg — pointer to the struct to populate
  • provider — optional secret provider

Returns: Same as Load, plus context errors (context.Canceled, context.DeadlineExceeded)

Example:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

var cfg Config
if err := fig.LoadContext(ctx, &cfg, provider); err != nil {
    log.Fatal(err)
}

Interfaces

SecretProvider

type SecretProvider interface {
    Get(ctx context.Context, key string) (string, error)
}

Defines the interface for secret backends.

Methods:

Get

Retrieves a secret by key.

Parameters:

  • ctx — context for cancellation and timeouts
  • key — the secret key (format is provider-specific)

Returns:

  • (string, nil) — the secret value on success
  • ("", ErrSecretNotFound) — if the secret doesn't exist (fig continues to next source)
  • ("", error) — for other errors (fig fails immediately)

Implementation Notes:

  • Return ErrSecretNotFound only for missing secrets
  • Return other errors for network issues, permission denied, etc.
  • Respect context cancellation

Example Implementation:

type MyProvider struct {
    client *MySecretClient
}

func (p *MyProvider) Get(ctx context.Context, key string) (string, error) {
    val, err := p.client.Fetch(ctx, key)
    if errors.Is(err, client.ErrNotFound) {
        return "", fig.ErrSecretNotFound
    }
    return val, err
}

Validator

type Validator interface {
    Validate() error
}

Optional interface for config validation after loading.

Methods:

Validate

Validates the configuration after all fields are populated.

Returns:

  • nil — validation passed
  • error — validation failed (returned from Load)

Implementation Notes:

  • Called after all fields are set, before Load returns
  • Errors are not wrapped in FieldError
  • Use for cross-field validation, range checks, business logic

Example:

type Config struct {
    MinConns int `env:"MIN_CONNS" default:"5"`
    MaxConns int `env:"MAX_CONNS" default:"25"`
}

func (c *Config) Validate() error {
    if c.MinConns > c.MaxConns {
        return fmt.Errorf("min connections (%d) exceeds max (%d)",
            c.MinConns, c.MaxConns)
    }
    return nil
}

Struct Tags

env

Maps a field to an environment variable.

Host string `env:"DATABASE_HOST"`
  • Value is read via os.Getenv
  • Empty strings are treated as unset

secret

Maps a field to a secret provider key.

Password string `secret:"database/credentials:password"`
  • Only queried if a provider is passed to Load
  • Key format is provider-specific

default

Provides a fallback value.

Port int `default:"5432"`
  • Parsed using the same type conversion as environment variables
  • Used when secret and env both return no value

required

Marks a field as mandatory.

APIKey string `env:"API_KEY" required:"true"`
  • Only "true" is recognised; any other value is ignored
  • Returns ErrRequired if no value found from any source

Tag Combinations

Tags can be combined for flexible resolution:

type Config struct {
    // Try secret, then env, then default
    Password string `secret:"db/pass" env:"DB_PASSWORD" default:"changeme"`

    // Env with default
    Port int `env:"PORT" default:"8080"`

    // Required with env
    APIKey string `env:"API_KEY" required:"true"`

    // Secret only (fails if no provider or secret not found)
    Token string `secret:"auth/token" required:"true"`
}

Next Steps