config

package module
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Config

config is a Go package designed for flexible and robust application configuration management. It allows applications to load configuration from various sources, including files, environment variables, and command-line flags, with a clear and predictable precedence order.

Features

  • Multiple Configuration Sources: Load settings from YAML and JSON files, environment variables, and command-line flags (primarily via pflag).
  • Structured Configuration: Map configuration settings directly into Go structs, supporting default values defined via struct tags.
  • Pluggable Storage: Merge values from any backend (database, key-value store, remote service) by implementing the small Storage interface.
  • Configuration Precedence: A well-defined hierarchy ensures that configuration values are applied consistently.
  • Easy Integration: Designed for seamless integration into existing Go applications, with explicit support for cobra and pflag.

Installation

To install the config package, use go get:

go get github.com/zauberhaus/config

Usage

The config package provides a simple API to load configurations. Here's an example using cobra to define command-line flags and load configuration:

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/spf13/cobra"
	"github.com/zauberhaus/config"
	"github.com/zauberhaus/config/pkg/flags"
)

type MyConfig struct {
	Host string `default:"localhost"`
	Port int    `default:"3000"`
}

func main() {
	if err := RootCmd().Execute(); err != nil {
		log.Fatal(err)
	}
}

func RootCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "my-app",
		Short: "My application with config",
		RunE: func(cmd *cobra.Command, args []string) error {
			// Bind Cobra flags to the config struct
			flagList := flags.NewFlagList(nil)
			_ = flagList.BindCmdFlag(cmd, "Host", "host")
			_ = flagList.BindCmdFlag(cmd, "Port", "port")

			// Define config options
			o := []config.Option{
				config.WithName("my-app"), // Prefix for environment variables (e.g., MY_APP_HOST)
				config.WithFlags(flagList),
			}

			// Optionally, specify a config file via flag or environment variable
			configFile := os.Getenv("MY_APP_CONFIG_FILE") // Custom env var for config file
			if cmd.Flags().Changed("config") {
				if cfgFile, err := cmd.Flags().GetString("config"); err == nil && cfgFile != "" {
					configFile = cfgFile
				}
			}

			if configFile != "" {
				o = append(o, config.WithFile(configFile))
			}

			// Load the configuration
			cfg, loadedFile, err := config.Load[*MyConfig](o...)
			if err != nil {
				return fmt.Errorf("failed to load configuration: %w", err)
			}

			if loadedFile != "" {
				fmt.Printf("Configuration loaded from: %s\n", loadedFile)
			} else {
				fmt.Println("No configuration file loaded, using defaults and environment variables.")
			}

			fmt.Printf("Host: %s\n", cfg.Host)
			fmt.Printf("Port: %d\n", cfg.Port)

			return nil
		},
	}

	// Define Cobra flags
	cmd.Flags().StringP("host", "H", "", "Specify the host")
	cmd.Flags().IntP("port", "P", 0, "Specify the port")
	cmd.Flags().StringP("config", "c", "", "Path to the configuration file (e.g., config.yaml)")

	return cmd
}

For more advanced usage, including integration with pflag and cobra, refer to the examples/ directory:

Config File Lookup

Load reads at most one config file:

  1. The file given with config.WithFile, or else
  2. the file named by the CONFIG environment variable, or else
  3. the first file named <name>.json, <name>.yaml or <name>.yml found in these directories, in this order:
    1. the directories given with config.WithPaths,
    2. the current working directory, only with config.WithWorkingDir(true),
    3. the home directory.

<name> is the name given with config.WithName, or config without one. config.WithExtension and config.WithExtensions change the accepted file extensions.

The current working directory isn't searched by default. Otherwise a config file in any directory a tool is run from, such as a freshly cloned repository, would silently change its settings.

File checks
  • Paths with a .. element (e.g. ../app.yaml) are rejected. Dots inside a name (app..v2.yaml) are fine.
  • The config file must be a regular file.
  • A file that is writable by others (e.g. mode 0666) is rejected, unless config.WithWorldWritable(true) is set. This check is skipped on Windows.
  • A file found in a search directory may be a symlink, but only to a file inside that directory. A file given with WithFile or CONFIG may point anywhere.
Values in error messages

Values from environment variables, flags and storage can be secrets, so they are replaced with *** in error messages, e.g. env MY_APP_PORT: strconv.ParseInt: parsing "***": invalid syntax. The original error is still available with errors.As as *errors.Error from github.com/zauberhaus/config/pkg/errors.

Configuration Precedence

When multiple configuration sources are defined, config resolves values based on a strict order of precedence, from lowest to highest:

  1. Default values in the struct: Values specified using the default:"value" struct tag. An invalid default (e.g. default:"abc" on an int) makes Load return an error.
  2. Configuration files: Settings loaded from YAML or JSON files (e.g., config.yaml, app.json).
  3. Storage: Values returned by a custom Storage passed with config.WithStorage.
  4. Environment variables: Values provided via environment variables (e.g., MY_APP_HOST, MY_APP_PORT).
  5. Command-line flags: Values passed as command-line arguments (e.g., --host, -P) and bound one by one with flags.NewFlagList and BindCmdFlag, or all at once by name with flags.FromCommand(cmd, idx): every flag whose name matches a field (--host → Host, --sub-name → Sub.Name) is bound, other flags are skipped. A flag tag overrides the name: with flag:"addr" only --addr sets the field, with flag:"-" no flag is bound to it by name. A custom pflag.Value (e.g. an enum registered with cmd.Flags().Var) whose variable has the type of the field sets the field directly; otherwise its String() is parsed into the field.

This order ensures that command-line flags always override environment variables, which in turn override storage and configuration file settings, and finally, struct defaults provide a baseline.

Environment Variables

Environment variable names are built from the name given with config.WithName and the field names of the config struct:

  • The name is the prefix: my-app → MY_APP_. Without a name, there is no prefix.
  • Field names are converted to SNAKE_CASE and joined with _: Server.ListenAddress → MY_APP_SERVER_LISTEN_ADDRESS.
  • env:"NAME" replaces the field name: Database Database `env:"DB"` → MY_APP_DB_HOST.
  • env:"-" adds no name for the field itself, its fields are added to the parent: MY_APP_HOST instead of MY_APP_COMMON_HOST.
  • env:"--" excludes the field and everything below it.
  • Two fields with the same name (e.g. Host and a Host field of an env:"-" struct) make Load return an error.
  • Slice and map elements use an index or key in brackets: MY_APP_ENDPOINTS[0]_NAME, MY_APP_LABELS[team]. Map keys are lowercased.
Listing environment variables

env.List returns all environment variables a config struct accepts, with the current value of the ones that are set. Slices and maps are listed with a [] placeholder.

import "github.com/zauberhaus/config/pkg/env"

vars, err := env.List(MyConfig{}, env.WithName("my-app"))
if err != nil {
	return err
}

for _, k := range slices.Sorted(maps.Keys(vars)) {
	fmt.Printf("%s=%s\n", k, vars[k])
}

To get only the names, without reading the environment, use the index. idx.String() also shows the config path and type for each name.

import "github.com/zauberhaus/config/pkg/index"

idx, err := index.New[MyConfig](nil)
if err != nil {
	return err
}

prefix := env.Prefix("my-app") // MY_APP_
for _, k := range idx.Keys() {
	fmt.Println(prefix + k)
}

If you use config.WithReplacer, pass the same map to index.New or env.WithReplacer, so the listed names match the ones Load reads. See examples/env-list for a complete example.

Custom Storage

Use config.WithStorage to load values from a source other than a file, such as a database or a key-value store. A storage implements the config.Storage interface:

type Storage interface {
	All() (map[string]any, error)
	Get(key string) (any, error)
	Set(key string, val any) error
}

Load calls All() once and applies every entry to the configuration struct. Keys are lower-case, dot-separated field paths (e.g. host, sub.name, sub2.name) and values must be assignable to the target field. Load returns an error if All() fails, if a key doesn't match a field, or if a value has the wrong type. Get and Set are not used by Load; they are there so the same storage can be used to read and persist individual settings.

type MyConfig struct {
	Host string `default:"localhost"`
	Port int    `default:"3000"`
	Sub  struct {
		Name string
	}
}

// memStorage is a minimal in-memory Storage.
type memStorage map[string]any

func (m memStorage) All() (map[string]any, error) { return m, nil }

func (m memStorage) Get(key string) (any, error) {
	v, ok := m[key]
	if !ok {
		return nil, fmt.Errorf("key not found: %s", key)
	}
	return v, nil
}

func (m memStorage) Set(key string, val any) error {
	m[key] = val
	return nil
}

func main() {
	storage := memStorage{"host": "db.example.com", "sub.name": "from-storage"}

	cfg, _, err := config.Load[*MyConfig](
		config.WithName("my-app"),
		config.WithStorage(storage),
	)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(cfg.Host) // db.example.com (environment variables and flags still take precedence)
}

License

Copyright 2026 Zauberhaus

Licensed to Zauberhaus under one or more agreements. Zauberhaus licenses this file to you under the Apache 2.0 License. See the LICENSE file in the project root for more information.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Load

func Load[P ~*T, T any](options ...Option) (P, string, error)

Types

type ConfigOptions

type ConfigOptions struct {
	File       string
	FileType   FileType
	Storage    Storage
	Name       string
	Paths      []string
	Strict     bool
	Index      index.Index
	Flags      *flags.Flags
	Extensions []Extension
	Replacer   map[string]string
	Hooks      []lookup.ParserHook

	WorkingDir    bool
	WorldWritable bool
	// contains filtered or unexported fields
}

type Extension

type Extension struct {
	Name     string
	FileType FileType
}

type FileType

type FileType int
const (
	UnknownFileType FileType = iota
	JSON
	YAML
)

func GetFileType

func GetFileType(name string, ext ...Extension) FileType

type MockStorage added in v1.2.0

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

MockStorage is a mock of Storage interface.

func NewMockStorage added in v1.2.0

func NewMockStorage(ctrl *gomock.Controller) *MockStorage

NewMockStorage creates a new mock instance.

func (*MockStorage) All added in v1.2.0

func (m *MockStorage) All(ctx context.Context) (map[string]any, error)

All mocks base method.

func (*MockStorage) Delete added in v1.3.0

func (m *MockStorage) Delete(ctx context.Context, key string) error

Delete mocks base method.

func (*MockStorage) EXPECT added in v1.2.0

func (m *MockStorage) EXPECT() *MockStorageMockRecorder

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockStorage) Get added in v1.2.0

func (m *MockStorage) Get(ctx context.Context, key string) (any, error)

Get mocks base method.

func (*MockStorage) Set added in v1.2.0

func (m *MockStorage) Set(ctx context.Context, key string, val any) error

Set mocks base method.

type MockStorageAllCall added in v1.2.0

type MockStorageAllCall struct {
	*gomock.Call
}

MockStorageAllCall wrap *gomock.Call

func (*MockStorageAllCall) Do added in v1.2.0

Do rewrite *gomock.Call.Do

func (*MockStorageAllCall) DoAndReturn added in v1.2.0

func (c *MockStorageAllCall) DoAndReturn(f func(context.Context) (map[string]any, error)) *MockStorageAllCall

DoAndReturn rewrite *gomock.Call.DoAndReturn

func (*MockStorageAllCall) Return added in v1.2.0

func (c *MockStorageAllCall) Return(arg0 map[string]any, arg1 error) *MockStorageAllCall

Return rewrite *gomock.Call.Return

type MockStorageDeleteCall added in v1.3.0

type MockStorageDeleteCall struct {
	*gomock.Call
}

MockStorageDeleteCall wrap *gomock.Call

func (*MockStorageDeleteCall) Do added in v1.3.0

Do rewrite *gomock.Call.Do

func (*MockStorageDeleteCall) DoAndReturn added in v1.3.0

DoAndReturn rewrite *gomock.Call.DoAndReturn

func (*MockStorageDeleteCall) Return added in v1.3.0

Return rewrite *gomock.Call.Return

type MockStorageGetCall added in v1.2.0

type MockStorageGetCall struct {
	*gomock.Call
}

MockStorageGetCall wrap *gomock.Call

func (*MockStorageGetCall) Do added in v1.2.0

Do rewrite *gomock.Call.Do

func (*MockStorageGetCall) DoAndReturn added in v1.2.0

func (c *MockStorageGetCall) DoAndReturn(f func(context.Context, string) (any, error)) *MockStorageGetCall

DoAndReturn rewrite *gomock.Call.DoAndReturn

func (*MockStorageGetCall) Return added in v1.2.0

func (c *MockStorageGetCall) Return(arg0 any, arg1 error) *MockStorageGetCall

Return rewrite *gomock.Call.Return

type MockStorageMockRecorder added in v1.2.0

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

MockStorageMockRecorder is the mock recorder for MockStorage.

func (*MockStorageMockRecorder) All added in v1.2.0

All indicates an expected call of All.

func (*MockStorageMockRecorder) Delete added in v1.3.0

func (mr *MockStorageMockRecorder) Delete(ctx, key any) *MockStorageDeleteCall

Delete indicates an expected call of Delete.

func (*MockStorageMockRecorder) Get added in v1.2.0

func (mr *MockStorageMockRecorder) Get(ctx, key any) *MockStorageGetCall

Get indicates an expected call of Get.

func (*MockStorageMockRecorder) Set added in v1.2.0

func (mr *MockStorageMockRecorder) Set(ctx, key, val any) *MockStorageSetCall

Set indicates an expected call of Set.

type MockStorageSetCall added in v1.2.0

type MockStorageSetCall struct {
	*gomock.Call
}

MockStorageSetCall wrap *gomock.Call

func (*MockStorageSetCall) Do added in v1.2.0

Do rewrite *gomock.Call.Do

func (*MockStorageSetCall) DoAndReturn added in v1.2.0

DoAndReturn rewrite *gomock.Call.DoAndReturn

func (*MockStorageSetCall) Return added in v1.2.0

func (c *MockStorageSetCall) Return(arg0 error) *MockStorageSetCall

Return rewrite *gomock.Call.Return

type Option

type Option interface {
	Set(*ConfigOptions)
}
var Strict Option = optionFunc(func(o *ConfigOptions) {
	o.Strict = true
})

Strict makes Load fail on environment variables with the name prefix (see WithName) that don't match a field, instead of ignoring them.

func WithContext added in v1.3.0

func WithContext(val context.Context) Option

func WithExtension

func WithExtension(ext string, fileType FileType) Option

WithExtension restricts the config file search, including $CONFIG, to a single extension and file type. It replaces any earlier extension options but doesn't affect a file given with WithFile.

func WithExtensions

func WithExtensions(val []Extension) Option

WithExtensions sets the extensions and file types accepted by the config file search, including $CONFIG. It replaces any earlier extension options but doesn't affect a file given with WithFile.

func WithFile

func WithFile(val string) Option

WithFile sets the config file to load and disables the search for one, including $CONFIG. The type is taken from the extension (.json, .yaml or .yml) and a path with a ".." element is rejected.

func WithFlags

func WithFlags(val *flags.Flags) Option

WithFlags applies the bound command-line flags that were set by the user. They are applied last, so they override all other sources.

func WithIndex

func WithIndex(val index.Index) Option

WithIndex sets the index that maps environment variable names to field paths. Without it, the index is built from the config struct, so this is only needed for custom mappings.

func WithName

func WithName(val string) Option

WithName sets the base name of the config file (default "config") and the prefix of environment variables, e.g. "my-app" reads MY_APP_HOST. Environment variables are only read when a name is set.

func WithParserHooks added in v1.5.0

func WithParserHooks(hooks ...lookup.ParserHook) Option

WithParserHooks parses the values of the storage, the environment and the flags into types the parser doesn't know, such as an interface type. It adds to the hooks of an earlier WithParserHooks.

func WithPaths

func WithPaths(val ...string) Option

WithPaths sets the directories searched for a config file before the working directory (see WithWorkingDir) and the home directory. It replaces the paths of an earlier WithPaths.

func WithReplacer

func WithReplacer(m map[string]string) Option

WithReplacer replaces parts of field names when the environment variable names are built, e.g. {"Sub": "Section"} maps Sub.Name to SECTION_NAME. It has no effect together with WithIndex.

func WithStorage added in v1.2.0

func WithStorage(val Storage) Option

WithStorage merges all values from val after the config file and before environment variables. Load calls only val.All(); keys are lower-case, dot-separated field paths such as "sub.name".

func WithWorkingDir added in v1.2.0

func WithWorkingDir(val bool) Option

WithWorkingDir adds the working directory to the config file search, between the WithPaths directories and the home directory. It is off by default, because a file in an untrusted directory would change the settings.

func WithWorldWritable added in v1.2.0

func WithWorldWritable(val bool) Option

WithWorldWritable allows config files that are writable by others. They are rejected by default, because anybody could change them. It has no effect on Windows.

type Storage added in v1.2.0

type Storage interface {
	All(ctx context.Context) (map[string]any, error)
	Get(ctx context.Context, key string) (any, error)
	Set(ctx context.Context, key string, val any) error
	Delete(ctx context.Context, key string) error
}

Directories

Path Synopsis
examples
basic command
cobra command
env-list command
pflags command
pkg
env
errors
Package errors keeps configuration values out of error messages, because values can be secrets that would otherwise end up in logs.
Package errors keeps configuration values out of error messages, because values can be secrets that would otherwise end up in logs.

Jump to

Keyboard shortcuts

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