goconfig

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2025 License: MIT Imports: 9 Imported by: 0

README

goconfig

A flexible and powerful Go configuration utility that loads environment variables into structs with support for various data types and customization options.

Features

  • Load environment variables into struct fields automatically
  • Support for nested structs and pointers
  • Customizable field name transformation
  • Support for various data types:
    • Basic types (string, bool, int, uint, float)
    • Duration
    • Slices (with custom separator)
    • Maps (via JSON)
    • Custom types implementing encoding.TextUnmarshaler
  • Configurable prefix and separators
  • Tag-based field mapping with env and alias tags
  • Anonymous struct embedding support
  • Panic recovery for safe error handling

Installation

go get github.com/jkaveri/goconfig

Usage

Basic Example
import "github.com/jkaveri/goconfig"

type Config struct {
    Host     string `env:"HOST"`
    Port     int    `env:"PORT"`
    Timeout  time.Duration
    Debug    bool
    Numbers  []int
    Settings map[string]string
}

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

ConfigType Package

The configtype package provides additional functionality for loading configuration from various file formats and handling special data types:

  • Support for multiple configuration formats:
    • JSON files
    • YAML files
    • TOML files
  • Base64 encoding support for sensitive data
  • Environment variable expansion in both file paths and configuration content
  • Hot reloading capability for configuration files
  • Generic type support for type-safe configuration loading

Example usage with configtype:

import (
    "github.com/jkaveri/goconfig"
    "github.com/jkaveri/goconfig/configtype"
)

type DBConfig struct {
    Host     string `json:"host"`
    Port     int    `json:"port"`
    Database string `json:"database"`
}

type AppConfig struct {
    DB     configtype.JSONFile[DBConfig] `env:"DB_CONFIG"`
    Secret configtype.Base64             `env:"API_SECRET"`
}

func main() {
    var cfg AppConfig
    if err := goconfig.Load(&cfg); err != nil {
        log.Fatal(err)
    }

    // Access configuration
    fmt.Printf("Database: %s:%d/%s\n",
        cfg.DB.Data.Host,
        cfg.DB.Data.Port,
        cfg.DB.Data.Database)
    fmt.Printf("Secret: %s\n", cfg.Secret)
}
With Options
import "github.com/jkaveri/goconfig"

type Config struct {
    Host string `env:"HOST"`
    Port int    `env:"PORT"`
}

func main() {
    var cfg Config
    loader := goconfig.New(
        goconfig.WithPrefix("APP"),
        goconfig.WithSeparator("."),
        goconfig.WithArraySeparator(";"),
    )
    if err := loader.LoadToStruct(&cfg); err != nil {
        log.Fatal(err)
    }
}
Field Tags
  • env: Exact environment variable name
  • alias: Alternative name for the field (will be combined with prefix)
type Config struct {
    Host     string `env:"SERVER_HOST"`     // Uses exact name
    Port     int    `alias:"server_port"`   // Uses prefix + name
    Timeout  time.Duration                  // Uses field name transformed
}

Environment Variables

Given the following struct:

type Config struct {
    Host     string        `env:"HOST"`
    Port     int
    Timeout  time.Duration
    Debug    bool
    Numbers  []int
    Settings map[string]string
}

The following environment variables would be loaded:

HOST=localhost
PORT=8080
TIMEOUT=5s
DEBUG=true
NUMBERS=1,2,3,4
SETTINGS={"key":"value"}

Options

  • WithPrefix(prefix string): Set prefix for all environment variables
  • WithSeparator(sep string): Set separator for nested fields (default: "_")
  • WithArraySeparator(sep string): Set separator for array values (default: ",")
  • WithFieldNameTransformer(fn func(string) string): Set custom field name transformation

License

MIT License

Documentation

Overview

Package goconfig provides a flexible and powerful configuration utility for Go applications. It allows loading environment variables into structs with support for various data types and customization options.

Key features:

  • Load environment variables into struct fields automatically
  • Support for nested structs and pointers
  • Customizable field name transformation
  • Support for various data types (string, bool, int, uint, float, duration, slices, maps)
  • Configurable prefix and separators
  • Tag-based field mapping with env and alias tags
  • Anonymous struct embedding support
  • Panic recovery for safe error handling

Example usage:

type Config struct {
    Host     string        `env:"HOST"`
    Port     int
    Timeout  time.Duration
    Debug    bool
    Numbers  []int
    Settings map[string]string
}

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

Index

Constants

View Source
const (
	// DefaultSep is the default separator used for environment variable names
	DefaultSep string = "_"
	// DefaultArrSep is the default separator used for array values
	DefaultArrSep string = ","
)

Variables

This section is empty.

Functions

func Load

func Load(s interface{}, options ...Option) error

Load loads configuration from environment variables into the provided struct. It uses default options and is a convenience wrapper around New().Load(). The struct should be a pointer to a struct with fields tagged with "env" or "alias" tags.

func UperCaseTransformer

func UperCaseTransformer(key string) string

UperCaseTransformer transforms PascalCase field names into MACRO_CASE environment variable names. It handles various cases including:

  • DBConnection => DB_CONNECTION
  • AKey => A_KEY
  • KeyA => KEY_A
  • ThisISMyKey => THIS_IS_MY_KEY

This transformer is useful when you want to maintain a consistent uppercase naming convention for environment variables while using PascalCase in your Go code.

func VoidTransformer

func VoidTransformer(key string) string

VoidTransformer is the default field name transformer that returns the key unchanged. It can be used with WithKeyTransformer to maintain the original field names.

Types

type Loader

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

Loader handles the loading of configuration from environment variables into structs. It provides customization options for prefix, separators, and field name transformation.

func New

func New(options ...Option) *Loader

New creates a new configuration loader with the provided options. If no options are provided, default values will be used.

func (*Loader) Load

func (c *Loader) Load(s interface{}) error

Load loads environment variables into the provided struct. The struct should be a pointer to a struct with fields tagged with "env" or "alias" tags. Returns an error if the loading process fails.

type Option

type Option func(*Loader)

Option is a function type that modifies a Loader's configuration.

func WithArraySeparator

func WithArraySeparator(sep string) Option

WithArraySeparator sets the separator used for array values in environment variables. The default separator is ",". For example, with separator ";" and array field "Numbers", the environment variable would be "1;2;3;4".

func WithKeyTransformer

func WithKeyTransformer(transformer func(key string) string) Option

WithKeyTransformer sets a custom function to transform field names into environment variable names. This allows for custom naming conventions beyond the default behavior. The transformer function receives the field name and returns the transformed name.

func WithPrefix

func WithPrefix(prefix string) Option

WithPrefix sets a prefix for all environment variables. The name of the environment variable will be prefix_fieldName. For example, with prefix "APP" and field "Host", the environment variable would be "APP_HOST".

func WithSeparator

func WithSeparator(sep string) Option

WithSeparator sets the separator used for nested field names in environment variables. The default separator is "_". For example, with separator "." and nested field "DB.Host", the environment variable would be "DB.HOST".

Directories

Path Synopsis
Package configtype provides a flexible and type-safe way to load and manage configuration from various sources.
Package configtype provides a flexible and type-safe way to load and manage configuration from various sources.

Jump to

Keyboard shortcuts

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