config

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2025 License: MIT Imports: 5 Imported by: 0

README

Config

A Go package that provides functionality for loading application configuration from environment variables with support for .env files.

This module is a wrapper around godotenv and envconfig (see Dependencies section below)

Features

  • Load environment variables from multiple .env files
  • Process environment variables into Go structs
  • Support for required fields and default values
  • Prefix support for environment variables
  • Helpful error messages for missing required variables
  • Functional options pattern for flexible configuration

Installation

go get github.com/twlvprscs/config

Usage

Basic Usage
package main

import (
    "log"
    
    "github.com/twlvprscs/config"
)

// Define your configuration struct with appropriate tags
type AppConfig struct {
    DatabaseURL string `envconfig:"DATABASE_URL" required:"true"`
    Port        int    `envconfig:"PORT" default:"8080"`
    Debug       bool   `envconfig:"DEBUG" default:"false"`
}

func main() {
    // Create an instance of your config struct
    var cfg AppConfig
    
    // Load configuration
    err := config.Load(
        config.WithPrefix("APP"),
        config.WithEnvFiles(".env", ".env.local"),
        config.WithConfigs(&cfg),
    )
    if err != nil {
        log.Fatalf("Failed to load config: %v", err)
    }
    
    // Use your configuration
    log.Printf("Database URL: %s", cfg.DatabaseURL)
    log.Printf("Port: %d", cfg.Port)
    log.Printf("Debug mode: %v", cfg.Debug)
}
Environment Variables

With the above example, the package will look for the following environment variables:

  • APP_DATABASE_URL (required)
  • APP_PORT (defaults to 8080 if not set)
  • APP_DEBUG (defaults to false if not set)
.env File Example
APP_DATABASE_URL=postgres://user:pass@localhost:5432/db
APP_DEBUG=true

Options

WithPrefix

Sets a prefix for environment variables. This is useful for namespacing configuration for different parts of an application.

config.WithPrefix("APP")
WithEnvFiles

Specifies one or more .env files to load environment variables from. Files are loaded in the order specified, with later files taking precedence over earlier ones.

config.WithEnvFiles(".env", ".env.local")
WithConfigs

Specifies one or more configuration structs to populate with values from environment variables.

config.WithConfigs(&cfg1, &cfg2)

Error Handling

The package provides helpful error messages for missing required variables:

err := config.Load(...)
if errors.Is(err, config.ErrMissingEnvVar) {
    // Handle missing environment variable
    log.Fatalf("Missing environment variable: %v", err)
}

Dependencies

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package config provides functionality for loading application configuration from environment variables. It supports loading environment variables from .env files and processing them into Go structs.

This package uses the functional options pattern to configure the loading process. It leverages godotenv for loading environment variables from files and envconfig for processing environment variables into Go structs.

Example usage:

type AppConfig struct {
	DatabaseURL string `envconfig:"DATABASE_URL" required:"true"`
	Port        int    `envconfig:"PORT" default:"8080"`
}

func main() {
	var cfg AppConfig
	err := config.Load(
		config.WithPrefix("APP"),
		config.WithEnvFiles(".env", ".env.local"),
		config.WithConfigs(&cfg),
	)
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}
	// Use cfg...
}

Index

Constants

This section is empty.

Variables

View Source
var (

	// ErrMissingEnvVar is returned by the Load function when a required environment variable is missing.
	// This error is wrapped with the name of the missing variable to provide more context.
	// Applications can use errors.Is to check for this specific error type.
	ErrMissingEnvVar = errors.New("config: a required environment variable is missing")
)

Functions

func Load

func Load(opts ...Option) error

Load loads configuration from environment variables into the provided configuration structs. It applies the provided options to customize the loading process.

The function performs the following steps: 1. Loads environment variables from any .env files specified with WithEnvFiles 2. Processes each configuration struct specified with WithConfigs using the envconfig package

If a required environment variable is missing, Load returns an ErrMissingEnvVar error wrapped with the name of the missing variable.

Example:

type Config struct {
	DatabaseURL string `envconfig:"DATABASE_URL" required:"true"`
	Port        int    `envconfig:"PORT" default:"8080"`
}

var cfg Config
err := config.Load(
	config.WithPrefix("APP"),
	config.WithEnvFiles(".env"),
	config.WithConfigs(&cfg),
)

Parameters:

  • opts: Zero or more Option functions to configure the loading process

Returns:

  • error: nil if successful, or an error if configuration loading failed

Types

type Option

type Option func(*option)

Option is a function type that modifies the internal option struct. It implements the functional options pattern for configuring the Load function.

func WithConfigs

func WithConfigs(configs ...any) Option

WithConfigs returns an Option that adds one or more configuration structs to be populated. Each config parameter should be a pointer to a struct that envconfig will populate with values from environment variables.

The struct fields should be tagged with `envconfig:"ENV_VAR_NAME"` to specify which environment variable to use for each field. Additional tags like `required:"true"` and `default:"value"` can be used to configure the behavior.

See the envconfig package documentation for more details on available tags and behavior.

func WithEnvFiles

func WithEnvFiles(paths ...string) Option

WithEnvFiles returns an Option that adds one or more .env files to load environment variables from. The files are loaded in the order they are specified, with later files taking precedence over earlier ones.

This is useful for loading default configuration from a checked-in .env file and then overriding it with a local .env file that is not checked into version control.

If a specified file doesn't exist, it is silently ignored.

func WithPrefix

func WithPrefix(prefix string) Option

WithPrefix returns an Option that sets the environment variable prefix for envconfig. The prefix is used to filter environment variables and can be used to namespace configuration for different parts of an application.

For example, with a prefix of "APP", envconfig will look for environment variables like "APP_DATABASE_URL" instead of just "DATABASE_URL".

If not specified, no prefix is used.

Jump to

Keyboard shortcuts

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