bconf

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2026 License: Apache-2.0 Imports: 16 Imported by: 3

README

bconf: builder configuration for go

License GoDoc Go Report Card Build Status codecov.io

bconf is a configuration framework that makes it easy to define, load, and validate application configuration values.

go get github.com/xavi-group/bconf
Philosophy

Most configuration libraries assume centralized configuration—you define everything in one place. bconf inverts this: configuration lives with the code that needs it.

This makes bconf particularly well-suited for:

  • Self-documenting applications that benefit from auto-generated help text showing all configuration options, types, defaults, and valid values
  • Service-oriented applications where internal packages define their own configuration requirements
  • Package authors building reusable components for bconf-based applications
  • Applications that should fail fast on misconfiguration rather than encountering errors at runtime
Why bconf

bconf provides tooling to write your configuration package by package. With bconf, configuration lives right alongside the code that needs it. This also makes it so that configuration is more easily re-used and composible by multiple applications (just like your packages should be).

bconf accomplishes this with FieldSets, which provide a namespace and logical grouping for related configuration. Independent packages define their FieldSets, and then application executables can attach them to an AppConfig, which provides a unified structure for loading and retrieving configuration values.

Within FieldSets, you define Fields, with each field defining the expected format and behavior of a configuration value.

Accessing configuration values can be done by calling lookup methods on a AppConfig with field-set and field keys, but it is often easier to define a configuration value structure alongside a FieldSet. A AppConfig can fill these configuration value structs at load time, providing easy access to precisely the values you need, where you need them.

Check out the documentation and introductory examples below, and see if bconf is right for your project!

Supported Configuration Sources
  • Environment (bconf.EnvironmentLoader)
  • Flags (bconf.FlagLoader)
  • JSON files (bconf.JSONFileLoader)
  • YAML files (bconf.YAMLFileLoader)
  • Overrides (setter functions)
Getting Values from bconf.AppConfig
  • AttachConfigStructs(configStructs ...any) (use prior to Load(...))
  • FillStruct(configStruct any) error
  • GetField(fieldSetKey, fieldKey string) (*bconf.Field, error)
  • GetString(fieldSetKey, fieldKey string) (string, error)
  • GetStrings(fieldSetKey, fieldKey string) ([]string, error)
  • GetInt(fieldSetKey, fieldKey string) (int, error)
  • GetInts(fieldSetKey, fieldKey string) ([]int, error)
  • GetBool(fieldSetKey, fieldKey string) (bool, error)
  • GetBools(fieldSetKey, fieldKey string) ([]bool, error)
  • GetTime(fieldSetKey, fieldKey string) (time.Time, error)
  • GetTimes(fieldSetKey, fieldKey string) ([]time.Time, error)
  • GetDuration(fieldSetKey, fieldKey string) (time.Duration, error)
  • GetDurations(fieldSetKey, fieldKey string) ([]time.Duration, error)
  • GetMapStringAny(fieldSetKey, fieldKey string) (map[string]any, error)
  • GetMapStringString(fieldSetKey, fieldKey string) (map[string]string, error)
Features
  • Ability to generate default configuration values with the bconf.Field DefaultGenerator parameter
  • Ability to define custom configuration value validation with the bconf.Field Validator parameter
  • Common field validators included: ValidateNonEmptyString, ValidateStringMinLength, ValidateURL, ValidatePort, ValidateIntRange, ValidateFileExists, ValidateDirExists, and more
  • Ability to conditionally load a bconf.FieldSet by defining bconf.LoadConditions
  • Ability to conditionally load a bconf.Field by defining bconf.LoadConditions
  • Ability to get a safe map of configuration values from the bconf.AppConfig ConfigMap() function
    • (the configuration map will obfuscate values from fields with Sensitive parameter set to true)
  • Ability to reload field-sets and individual fields via the bconf.AppConfig
  • Ability to fill configuration structures with values from a bconf.AppConfig using the FillStruct(...) method
Limitations
  • No support for watching / automatically updating configuration values
Example

Below is an example of a bconf.AppConfig defined with the builder pattern. Below this code block the behavior of the example is discussed.

package main

import (
    "fmt"
    "os"
    "time"

    "github.com/segmentio/ksuid"
    "github.com/xavi-group/bconf"
    "github.com/xavi-group/bobotel"
    "github.com/xavi-group/bobzap"
    "go.uber.org/zap"
)

const (
    APIFieldSetKey   = "api"
    SessionSecretKey = "session_secret"
    ReadTimeoutKey   = "read_timeout"
    WriteTimeoutKey  = "write_timeout"
)

func APIFieldSets() bconf.FieldSets {
    checkValidSessionSecret := func(fieldValue any) error {
        secret, _ := fieldValue.(string)

        minLength := 20
        if len(secret) < minLength {
            return fmt.Errorf(
                "expected string of minimum %d characters (len=%d)",
                minLength,
                len(secret),
            )
        }

        return nil
    }

    // FSB() is a shorthand function for NewFieldSetBuilder()
    // FB() is a shorthand function for NewFieldBuilder()
    // C is a shorthand method for Create()
    return bconf.FieldSets{
        bconf.FSB(APIFieldSetKey).
            Fields(
                bconf.FB(SessionSecretKey, bconf.String).Sensitive().Required().
                    Description("API secret for session management").
                    Validator(checkValidSessionSecret).C(),
                bconf.FB(ReadTimeoutKey, bconf.Duration).Default(5*time.Second).
                    Description("API read timeout").C(),
                bconf.FB(WriteTimeoutKey, bconf.Duration).Default(5*time.Second).
                    Description("API write timeout").C(),
            ).C(),
    }
}

type APIConfig struct {
    bconf.ConfigStruct `bconf:"api"`
    LogConfig          *bobzap.Config
    AppID              string        `bconf:"app.id"`
    SessionSecret      string        `bconf:"session_secret"`
    ReadTimeout        time.Duration `bconf:"read_timeout"`
    WriteTimeout       time.Duration `bconf:"write_timeout"`
}

func main() {
    config := bconf.NewAppConfig(
        "auth_service_example",
        "HTTP API for user authentication and authorization",
        bconf.WithAppIDFunc(func() string { return ksuid.New().String() }),
        bconf.WithAppVersion("1.0.0"),
        bconf.WithEnvironmentLoader("auth_svc"),
        bconf.WithFlagLoader(),
    )

    config.AddFieldSetGroup("bobzap", bobzap.FieldSets())
    config.AddFieldSetGroup("bobotel", bobotel.FieldSets())
    config.AddFieldSetGroup("api", APIFieldSets())

    apiConfig := &APIConfig{}

    config.AttachConfigStructs(
        bobzap.NewConfig(),
        bobotel.NewConfig(),
        apiConfig,
    )

    // Load when called without any options will also handle the help flag (--help or -h)
    if errs := config.Load(); len(errs) > 0 {
        fmt.Printf("problem(s) loading application configuration: %v\n", errs)
        os.Exit(1)
    }

    // -- Initialize application observability --
    if err := bobotel.InitializeTraceProvider(); err != nil {
        fmt.Printf("problem initializing application tracer: %s\n", err)
        os.Exit(1)
    }

    if err := bobzap.InitializeGlobalLogger(); err != nil {
        fmt.Printf("problem initializing application logger: %s\n", err)
        os.Exit(1)
    }

    log := bobzap.NewLogger("main")

    log.Info(
        fmt.Sprintf("%s initialized successfully", config.AppName()),
        zap.Any("app_config", config.ConfigMap()),
        zap.Strings("warnings", config.Warnings()),
    )

    // -- Configuration access examples --
}

In the code block above, a bconf.AppConfig is defined with three field-set groups (which group configuration related to the logging, tracing, and api in this case). Two field-set groups are from separate packages (bobzap and bobotel). One is defined right above the main function (api). The api field-set group is defined above to showcase how a field-set and configuration value struct are implemented, but in practice it would likely be defined within an HTTP routing package.

The APIConfig value struct is written to showcase the flexibility that exists when filling a configuration value struct. In this case, it nests the values for the logging configuration as defined by the bobzap package, opts to acquire the app.id configuration value from the app field-set, and sets a default field-set of api, which is used to locate the session_secret, read_timeout, and write_timeout fields. Although this example is contrived, it is useful when defining more complex service-like packages.

The easiest way to see your application configuration is to execute your applicaiton with the -h or --help flag. The help output will take into account which loaders you have configured, and highlights which configuration values are required, conditionally required, or optional. Additional help options are in progress.

Usage of 'auth_service_example':
HTTP API for user authentication and authorization

Required Configuration:
        api.session_secret string
                API secret for session management.
                Environment key: 'AUTH_SVC_API_SESSION_SECRET'
                Flag argument: '--api_session_secret'
Conditionally Required Configuration:
        otlp.host string
                Otlp host defines the host location of the trace collector.
                Environment key: 'AUTH_SVC_OTLP_HOST'
                Flag argument: '--otlp_host'
                Loading depends on field(s): 'otel.exporters'
Optional Configuration:
        api.read_timeout time.Duration
                Timeout for HTTP read operations.
                Default value: '5s'
                Environment key: 'AUTH_SVC_API_READ_TIMEOUT'
                Flag argument: '--api_read_timeout'
        api.write_timeout time.Duration
                Timeout for HTTP write operations.
                Default value: '5s'
                Environment key: 'AUTH_SVC_API_WRITE_TIMEOUT'
                Flag argument: '--api_write_timeout'
        app.id string
                Default value: <generated-at-run-time>
                Environment key: 'AUTH_SVC_APP_ID'
                Flag argument: '--app_id'
        app.version string
                Default value: '1.0.0'
                Environment key: 'AUTH_SVC_APP_VERSION'
                Flag argument: '--app_version'
        log.color bool
                Log color defines whether console formatted logs are rendered in color.
                Default value: 'true'
                Environment key: 'AUTH_SVC_LOG_COLOR'
                Flag argument: '--log_color'
        log.config string
                Log config defines whether the Zap will be configured with development or production defaults. 
                Note: `development` defaults to debug log level and console format, `production` defaults to info log 
                level and json format. 
                Accepted values: ['production', 'development']
                Default value: 'production'
                Environment key: 'AUTH_SVC_LOG_CONFIG'
                Flag argument: '--log_config'
        log.format string
                Log format defines the format logs will be emitted in (overrides log config defaults).
                Accepted values: ['console', 'json']
                Environment key: 'AUTH_SVC_LOG_FORMAT'
                Flag argument: '--log_format'
        log.level string
                Log level defines the level at which logs will be emitted (overrides log config defaults).
                Accepted values: ['debug', 'info', 'warn', 'error', 'dpanic', 'panic', 'fatal']
                Environment key: 'AUTH_SVC_LOG_LEVEL'
                Flag argument: '--log_level'
        otel.console_format string
                Otel console format defines the format of traces output to the console where 'pretty' is more 
                human readable (adds whitespace). 
                Accepted values: ['production', 'pretty']
                Default value: 'production'
                Environment key: 'AUTH_SVC_OTEL_CONSOLE_FORMAT'
                Flag argument: '--otel_console_format'
        otel.exporters []string
                Otel exporters defines where traces will be sent (accepted values are 'console' and 'otlp'). 
                Exporters accepts a list and can be configured to export traces to multiple destinations. 
                Default value: '[console]'
                Environment key: 'AUTH_SVC_OTEL_EXPORTERS'
                Flag argument: '--otel_exporters'
        otlp.endpoint_kind string
                Otlp endpoint kind defines the protocol used by the trace collector.
                Accepted values: ['http', 'grpc']
                Default value: 'http'
                Environment key: 'AUTH_SVC_OTLP_ENDPOINT_KIND'
                Flag argument: '--otlp_endpoint_kind'
                Loading depends on field(s): 'otel.exporters'
        otlp.port int
                Otlp port defines the port of the trace collector process. For a GRPC endpoint the default is 
                4317. 
                Default value: '4318'
                Environment key: 'AUTH_SVC_OTLP_PORT'
                Flag argument: '--otlp_port'
                Loading depends on field(s): 'otel.exporters'

To view more examples, including a real-world example showcasing how configuration can live alongside package code, please visit github.com/xavi-group/bapp-template.

If you are interested in quickly configuring your application with tracing and logging as showcased in the example above, consider checking out github.com/xavi-group/bobzap and github.com/xavi-group/bobotel.

For Package Authors

bconf is designed to help package authors expose configurable behavior that integrates seamlessly into any bconf-based application. The pattern is simple:

  1. Export a FieldSets() function that returns your package's configuration fields
  2. Export a NewConfig() function that returns a configuration struct for easy access
  3. Provide an initialization function that uses the loaded configuration

Packages built with this pattern can be composed together—applications simply attach each package's FieldSets to their AppConfig, and all configuration is loaded, validated, and documented uniformly.

Examples

Two packages that demonstrate this pattern:

  • bobzap - Structured logging with Zap, exposing log.level, log.format, log.color, and other settings
  • bobotel - OpenTelemetry tracing, exposing otel.exporters, otlp.host, otlp.port, and related settings

Both packages define their configuration alongside their code, making them instantly usable in any bconf application:

config.AddFieldSetGroup("bobzap", bobzap.FieldSets())
config.AddFieldSetGroup("bobotel", bobotel.FieldSets())
config.AttachConfigStructs(bobzap.NewConfig(), bobotel.NewConfig())

Roadmap / Future Improvements

Documentation & Code Generation

bconf captures rich metadata about configuration—types, defaults, descriptions, enumerations, and conditions. Future tooling will leverage this metadata to generate:

  • Markdown documentation - Auto-generated docs for all configuration options
  • .env.example files - Template environment files with descriptions and defaults
  • JSON Schema - For editor validation of JSON/YAML config files
  • Go structs - Generate ConfigStruct definitions from FieldSet definitions
Additional Features
  • File watching and notifications for configuration value updates
  • TOML files (bconf.TOMLFileLoader)
  • Additional -h / --help options
  • Implement Transformers on bconf.Field

Documentation

Overview

Package bconf provides a package-scoped configuration management system for Go applications. It supports multiple configuration sources including environment variables, command-line flags, JSON files, and YAML files, with type-safe access to configuration values.

Index

Constants

View Source
const (
	Bool            = "bool"
	Bools           = "[]bool"
	String          = "string"
	Strings         = "[]string"
	Int             = "int"
	Ints            = "[]int"
	Float           = "float64"
	Floats          = "[]float64"
	Time            = "time.Time"
	Times           = "[]time.Time"
	Duration        = "time.Duration"
	Durations       = "[]time.Duration"
	MapStringAny    = "map[string]any"
	MapStringString = "map[string]string"
)

Field type constants for configuration field definitions.

View Source
const FieldNotFoundError = "field not found"

FieldNotFoundError is the error message returned when a field is not found.

Variables

This section is empty.

Functions

func FieldTypes

func FieldTypes() []string

FieldTypes returns all supported field type constants.

Types

type AppConfig

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

AppConfig manages application configuration field-sets and provides access to configuration values. It should be initialized with the NewAppConfig function.

func NewAppConfig

func NewAppConfig(appName, appDescription string, options ...ConfigOption) *AppConfig

NewAppConfig creates a new application configuration struct with configuration options that allow for the specification of configuration sources (environment, flags, json files, etc).

func (*AppConfig) AddFieldSet

func (c *AppConfig) AddFieldSet(fieldSet *FieldSet)

AddFieldSet adds a single field set to the configuration.

func (*AppConfig) AddFieldSetGroup

func (c *AppConfig) AddFieldSetGroup(groupName string, fieldSets FieldSets)

AddFieldSetGroup adds a named group of field sets to the configuration.

func (*AppConfig) AppDescription

func (c *AppConfig) AppDescription() string

AppDescription returns the configured application description.

func (*AppConfig) AppID

func (c *AppConfig) AppID() string

AppID returns the configured application ID.

func (*AppConfig) AppName

func (c *AppConfig) AppName() string

AppName returns the configured application name.

func (*AppConfig) AppVersion

func (c *AppConfig) AppVersion() string

AppVersion returns the configured application version.

func (*AppConfig) AttachConfigStructs

func (c *AppConfig) AttachConfigStructs(configStructs ...any)

AttachConfigStructs attaches struct pointers that will be filled with configuration values during Load.

func (*AppConfig) ConfigMap

func (c *AppConfig) ConfigMap() map[string]map[string]any

ConfigMap returns a nested map of all configuration values organized by field set and field key.

func (*AppConfig) FillStruct

func (c *AppConfig) FillStruct(configStruct any) (err error)

FillStruct populates a struct's fields with configuration values based on bconf tags.

func (*AppConfig) GetBool

func (c *AppConfig) GetBool(fieldSetKey, fieldKey string) (bool, error)

GetBool retrieves a boolean field value.

func (*AppConfig) GetBools

func (c *AppConfig) GetBools(fieldSetKey, fieldKey string) ([]bool, error)

GetBools retrieves a boolean slice field value.

func (*AppConfig) GetDuration

func (c *AppConfig) GetDuration(fieldSetKey, fieldKey string) (time.Duration, error)

GetDuration retrieves a time.Duration field value.

func (*AppConfig) GetDurations

func (c *AppConfig) GetDurations(fieldSetKey, fieldKey string) ([]time.Duration, error)

GetDurations retrieves a time.Duration slice field value.

func (*AppConfig) GetField

func (c *AppConfig) GetField(fieldSetKey, fieldKey string) (*Field, error)

GetField retrieves a field by its field set key and field key.

func (*AppConfig) GetInt

func (c *AppConfig) GetInt(fieldSetKey, fieldKey string) (int, error)

GetInt retrieves an integer field value.

func (*AppConfig) GetInts

func (c *AppConfig) GetInts(fieldSetKey, fieldKey string) ([]int, error)

GetInts retrieves an integer slice field value.

func (*AppConfig) GetMapStringAny added in v0.7.0

func (c *AppConfig) GetMapStringAny(fieldSetKey, fieldKey string) (map[string]any, error)

GetMapStringAny retrieves a map[string]any field value.

func (*AppConfig) GetMapStringString added in v0.7.0

func (c *AppConfig) GetMapStringString(fieldSetKey, fieldKey string) (map[string]string, error)

GetMapStringString retrieves a map[string]string field value.

func (*AppConfig) GetString

func (c *AppConfig) GetString(fieldSetKey, fieldKey string) (string, error)

GetString retrieves a string field value.

func (*AppConfig) GetStrings

func (c *AppConfig) GetStrings(fieldSetKey, fieldKey string) ([]string, error)

GetStrings retrieves a string slice field value.

func (*AppConfig) GetTime

func (c *AppConfig) GetTime(fieldSetKey, fieldKey string) (time.Time, error)

GetTime retrieves a time.Time field value.

func (*AppConfig) GetTimes

func (c *AppConfig) GetTimes(fieldSetKey, fieldKey string) ([]time.Time, error)

GetTimes retrieves a time.Time slice field value.

func (*AppConfig) HelpString

func (c *AppConfig) HelpString() string

HelpString returns a formatted help string describing all configuration options.

func (*AppConfig) Load

func (c *AppConfig) Load(options ...LoadOption) []error

Load loads configuration values from all configured loaders and validates fields.

func (*AppConfig) SetField

func (c *AppConfig) SetField(fieldSetKey, fieldKey string, fieldValue any) error

SetField sets a field value by its field set key and field key, overriding any loaded value.

func (*AppConfig) Warnings

func (c *AppConfig) Warnings() []string

Warnings returns any warnings generated during configuration loading.

type ConfigOption

type ConfigOption interface {
	ConfigOptionType() string
}

ConfigOption is the interface for application configuration options passed to NewAppConfig.

func WithAppID

func WithAppID(appID string) ConfigOption

WithAppID sets a static application ID.

func WithAppIDFunc

func WithAppIDFunc(appIDFunc func() string) ConfigOption

WithAppIDFunc sets a function to generate the application ID dynamically.

func WithAppVersion

func WithAppVersion(appVersion string) ConfigOption

WithAppVersion sets a static application version.

func WithAppVersionFunc

func WithAppVersionFunc(appVersionFunc func() string) ConfigOption

WithAppVersionFunc sets a function to generate the application version dynamically.

func WithEnvironmentLoader

func WithEnvironmentLoader(keyPrefix ...string) ConfigOption

WithEnvironmentLoader enables the Environment loader. Only the first value in the keyPrefix parameter will be accepted as a key prefix.

func WithFlagLoader

func WithFlagLoader(keyPrefix ...string) ConfigOption

WithFlagLoader enables the Flag loader. Only the first value in the keyPrefix parameter will be accepted as a key prefix.

type ConfigStruct

type ConfigStruct struct {
	FieldSet string
}

ConfigStruct is embedded in structs that will be filled with configuration values.

type EnvironmentLoader

type EnvironmentLoader struct {
	KeyPrefix string
}

EnvironmentLoader loads configuration values from environment variables.

func NewEnvironmentLoader

func NewEnvironmentLoader() *EnvironmentLoader

NewEnvironmentLoader creates a new environment loader without a key prefix.

func NewEnvironmentLoaderWithKeyPrefix

func NewEnvironmentLoaderWithKeyPrefix(keyPrefix string) *EnvironmentLoader

NewEnvironmentLoaderWithKeyPrefix creates a new environment loader with the specified key prefix.

func (*EnvironmentLoader) Clone

Clone creates a copy of the EnvironmentLoader.

func (*EnvironmentLoader) CloneLoader

func (l *EnvironmentLoader) CloneLoader() Loader

CloneLoader creates a copy of the loader as a Loader interface.

func (*EnvironmentLoader) Get

func (l *EnvironmentLoader) Get(fieldSetKey, fieldKey string) (any, bool)

Get retrieves a single field value from environment variables.

func (*EnvironmentLoader) GetMap

func (l *EnvironmentLoader) GetMap(fieldSetKey string, fieldKeys []string) map[string]any

GetMap retrieves multiple field values from environment variables.

func (*EnvironmentLoader) HelpString

func (l *EnvironmentLoader) HelpString(fieldSetKey, fieldKey string) string

HelpString returns a help string describing where this field can be configured.

func (*EnvironmentLoader) Name

func (l *EnvironmentLoader) Name() string

Name returns the name of this loader.

type Field

type Field struct {

	// Validator defines a function that runs during validation to check a value against validity constraints
	Validator func(value any) error
	// DefaultGenerator defines a function that creates a base value for a field
	DefaultGenerator func() (any, error)
	// Default defines a base value for a field
	Default any

	// Key is a required field that defines the field lookup value
	Key string
	// Type is a required field that defines the type of value the field contains
	Type string
	// Description defines a summary of the field contents
	Description string
	// Enumeration defines a list of acceptable inputs for the field value
	Enumeration []any
	// LoadConditions defines the conditions required for a field to load values
	LoadConditions LoadConditions

	// Required defines whether a field value must be set in order for the field to be valid
	Required bool
	// Sensitive identifies the field value as sensitive
	Sensitive bool
	// contains filtered or unexported fields
}

Field is a data structure that provides context for a configuration value

func (*Field) Clone

func (f *Field) Clone() *Field

Clone creates a deep copy of the Field.

type FieldBuilder

type FieldBuilder interface {
	Default(value any) FieldBuilder
	Validator(validationFunc func(fieldValue any) error) FieldBuilder
	DefaultGenerator(defaultGeneratorFunc func() (any, error)) FieldBuilder
	LoadConditions(conditions ...LoadCondition) FieldBuilder
	Description(description string, concat ...string) FieldBuilder
	Enumeration(acceptedValues ...any) FieldBuilder
	Required() FieldBuilder
	Sensitive() FieldBuilder
	Create() *Field
	C() *Field
}

FieldBuilder provides a fluent interface for constructing Field instances.

func FB

func FB(fieldKey, fieldType string) FieldBuilder

FB is a shorthand alias for NewFieldBuilder.

func NewFieldBuilder

func NewFieldBuilder(fieldKey, fieldType string) FieldBuilder

NewFieldBuilder creates a new field builder with the specified key and type.

type FieldLocation

type FieldLocation struct {
	FieldSetKey string
	FieldKey    string
}

FieldLocation identifies a specific field by its field set key and field key.

func FD

func FD(fieldSetKey, fieldKey string) FieldLocation

FD creates a FieldLocation with the specified field set key and field key.

type FieldLocations

type FieldLocations []FieldLocation

FieldLocations is a slice of FieldLocation.

type FieldSet

type FieldSet struct {
	Key            string
	LoadConditions LoadConditions
	Fields         Fields
	// contains filtered or unexported fields
}

FieldSet represents a group of related configuration fields.

func (*FieldSet) Clone

func (f *FieldSet) Clone() *FieldSet

Clone creates a deep copy of the FieldSet.

type FieldSetBuilder

type FieldSetBuilder interface {
	Fields(fields ...*Field) FieldSetBuilder
	LoadConditions(conditions ...LoadCondition) FieldSetBuilder
	Create() *FieldSet
	C() *FieldSet
}

FieldSetBuilder provides a fluent interface for constructing FieldSet instances.

func FSB

func FSB(fieldSetKey string) FieldSetBuilder

FSB is a shorthand alias for NewFieldSetBuilder.

func NewFieldSetBuilder

func NewFieldSetBuilder(fieldSetKey string) FieldSetBuilder

NewFieldSetBuilder creates a new field set builder with the specified key.

type FieldSetStruct

type FieldSetStruct interface {
	FieldSet() string
}

FieldSetStruct is implemented by structs that provide their field set key.

type FieldSets

type FieldSets []*FieldSet

FieldSets is a slice of FieldSet pointers.

type FieldValidator added in v0.7.0

type FieldValidator func(value any) error

FieldValidator is the function signature for field validation.

func ValidateAll added in v0.7.0

func ValidateAll(validators ...FieldValidator) FieldValidator

ValidateAll returns a validator that passes only if all provided validators pass.

func ValidateAny added in v0.7.0

func ValidateAny(validators ...FieldValidator) FieldValidator

ValidateAny returns a validator that passes if at least one validator passes. If all validators fail, returns the error from the last validator.

func ValidateDirExists added in v0.7.0

func ValidateDirExists() FieldValidator

ValidateDirExists returns a validator that ensures a directory exists at the given path.

func ValidateEachInt added in v0.7.0

func ValidateEachInt(validator FieldValidator) FieldValidator

ValidateEachInt returns a validator that applies the given validator to each element in a []int.

func ValidateEachString added in v0.7.0

func ValidateEachString(validator FieldValidator) FieldValidator

ValidateEachString returns a validator that applies the given validator to each element in a []string.

func ValidateFileExists added in v0.7.0

func ValidateFileExists() FieldValidator

ValidateFileExists returns a validator that ensures a file exists at the given path.

func ValidateIntMax added in v0.7.0

func ValidateIntMax(maxVal int) FieldValidator

ValidateIntMax returns a validator that ensures an int is at most maxVal.

func ValidateIntMin added in v0.7.0

func ValidateIntMin(minVal int) FieldValidator

ValidateIntMin returns a validator that ensures an int is at least minVal.

func ValidateIntRange added in v0.7.0

func ValidateIntRange(minVal, maxVal int) FieldValidator

ValidateIntRange returns a validator that ensures an int is within [minVal, maxVal].

func ValidateNonEmptySlice added in v0.7.0

func ValidateNonEmptySlice() FieldValidator

ValidateNonEmptySlice returns a validator that ensures a slice is not empty. Works with []string, []int, []bool, and other slice types.

func ValidateNonEmptyString added in v0.7.0

func ValidateNonEmptyString() FieldValidator

ValidateNonEmptyString returns a validator that ensures a string is not empty.

func ValidatePathExists added in v0.7.0

func ValidatePathExists() FieldValidator

ValidatePathExists returns a validator that ensures a file or directory exists at the given path.

func ValidatePort added in v0.7.0

func ValidatePort() FieldValidator

ValidatePort returns a validator that ensures an int is a valid port number (1-65535).

func ValidateSliceMaxLength added in v0.7.0

func ValidateSliceMaxLength(maxLen int) FieldValidator

ValidateSliceMaxLength returns a validator that ensures a slice has at most maxLen elements.

func ValidateSliceMinLength added in v0.7.0

func ValidateSliceMinLength(minLen int) FieldValidator

ValidateSliceMinLength returns a validator that ensures a slice has at least minLen elements.

func ValidateStringMaxLength added in v0.7.0

func ValidateStringMaxLength(maxLen int) FieldValidator

ValidateStringMaxLength returns a validator that ensures a string has at most maxLen characters.

func ValidateStringMinLength added in v0.7.0

func ValidateStringMinLength(minLen int) FieldValidator

ValidateStringMinLength returns a validator that ensures a string has at least minLen characters.

func ValidateStringRegex added in v0.7.0

func ValidateStringRegex(pattern string) FieldValidator

ValidateStringRegex returns a validator that ensures a string matches the given regex pattern.

func ValidateURL added in v0.7.0

func ValidateURL() FieldValidator

ValidateURL returns a validator that ensures a string is a valid URL.

func ValidateURLWithSchemes added in v0.7.0

func ValidateURLWithSchemes(schemes ...string) FieldValidator

ValidateURLWithSchemes returns a validator that ensures a string is a valid URL with one of the allowed schemes.

type FieldValue

type FieldValue struct {
	FieldValue  any
	FieldSetKey string
	FieldKey    string
}

FieldValue represents a configuration field value with its location.

type FieldValueFinder

type FieldValueFinder interface {
	GetFieldDependencies() map[FieldLocation]any
	GetFieldValue(fieldSetKey, fieldKey string) (value any, found bool)
	GetString(fieldSetKey, fieldKey string) (val string, found bool, err error)
	GetStrings(fieldSetKey, fieldKey string) (val []string, found bool, err error)
	GetInt(fieldSetKey, fieldKey string) (val int, found bool, err error)
	GetInts(fieldSetKey, fieldKey string) (val []int, found bool, err error)
	GetBool(fieldSetKey, fieldKey string) (val bool, found bool, err error)
	GetBools(fieldSetKey, fieldKey string) (val []bool, found bool, err error)
	GetTime(fieldSetKey, fieldKey string) (val time.Time, found bool, err error)
	GetTimes(fieldSetKey, fieldKey string) (val []time.Time, found bool, err error)
	GetDuration(fieldSetKey, fieldKey string) (val time.Duration, found bool, err error)
	GetDurations(fieldSetKey, fieldKey string) (val []time.Duration, found bool, err error)
}

FieldValueFinder provides type-safe access to field values during load condition evaluation.

type FieldValues

type FieldValues []FieldValue

FieldValues is a slice of FieldValue.

type Fields

type Fields []*Field

Fields is a slice of Field elements providing context for configuration values

type FlagLoader

type FlagLoader struct {
	KeyPrefix      string
	OverrideLookup []string
}

FlagLoader loads configuration values from command-line flags.

func NewFlagLoader

func NewFlagLoader() *FlagLoader

NewFlagLoader creates a new flag loader without a key prefix.

func NewFlagLoaderWithKeyPrefix

func NewFlagLoaderWithKeyPrefix(keyPrefix string) *FlagLoader

NewFlagLoaderWithKeyPrefix creates a new flag loader with the specified key prefix.

func (*FlagLoader) Clone

func (l *FlagLoader) Clone() *FlagLoader

Clone creates a copy of the FlagLoader.

func (*FlagLoader) CloneLoader

func (l *FlagLoader) CloneLoader() Loader

CloneLoader creates a copy of the loader as a Loader interface.

func (*FlagLoader) Get

func (l *FlagLoader) Get(fieldSetKey, fieldKey string) (any, bool)

Get retrieves a single field value from command-line flags.

func (*FlagLoader) GetMap

func (l *FlagLoader) GetMap(fieldSetKey string, fieldKeys []string) map[string]any

GetMap retrieves multiple field values from command-line flags.

func (*FlagLoader) HelpString

func (l *FlagLoader) HelpString(fieldSetKey, fieldKey string) string

HelpString returns a help string describing where this field can be configured.

func (*FlagLoader) Name

func (l *FlagLoader) Name() string

Name returns the name of this loader.

type JSONFileLoader

type JSONFileLoader struct {
	Decoder   JSONUnmarshal
	FilePaths []string
	// contains filtered or unexported fields
}

JSONFileLoader loads configuration values from JSON files.

func NewJSONFileLoader

func NewJSONFileLoader() *JSONFileLoader

NewJSONFileLoader creates a new JSON file loader with default settings.

func NewJSONFileLoaderWithAttributes

func NewJSONFileLoaderWithAttributes(decoder JSONUnmarshal, filePaths ...string) *JSONFileLoader

NewJSONFileLoaderWithAttributes creates a new JSON file loader with the specified decoder and file paths.

func (*JSONFileLoader) Clone

func (l *JSONFileLoader) Clone() *JSONFileLoader

Clone creates a copy of the JSONFileLoader.

func (*JSONFileLoader) CloneLoader

func (l *JSONFileLoader) CloneLoader() Loader

CloneLoader creates a copy of the loader as a Loader interface.

func (*JSONFileLoader) Get

func (l *JSONFileLoader) Get(fieldSetKey, fieldKey string) (any, bool)

Get retrieves a single field value from the loaded JSON files.

func (*JSONFileLoader) GetMap

func (l *JSONFileLoader) GetMap(fieldSetKey string, fieldKeys []string) map[string]any

GetMap retrieves multiple field values from the loaded JSON files.

func (*JSONFileLoader) HelpString

func (l *JSONFileLoader) HelpString(fieldSetKey, fieldKey string) string

HelpString returns a help string describing where this field can be configured.

func (*JSONFileLoader) Name

func (l *JSONFileLoader) Name() string

Name returns the name of this loader.

type JSONLoaderConfigOption added in v0.6.1

type JSONLoaderConfigOption interface {
	ConfigOption
	WithDecoder(decoder JSONUnmarshal)
}

JSONLoaderConfigOption is a configuration option for JSON file loaders that supports custom decoders.

func WithJSONFileLoader

func WithJSONFileLoader(filePaths ...string) JSONLoaderConfigOption

WithJSONFileLoader enables the JSON file loader with the specified file paths.

type JSONUnmarshal

type JSONUnmarshal func(data []byte, v any) error

JSONUnmarshal defines the function signature for JSON unmarshaling.

type LoadCondition

type LoadCondition interface {
	FieldValueFinder
	Clone() LoadCondition
	FieldDependencies() FieldLocations
	SetFieldValues(fieldValues ...FieldValue)
	Load(c FieldValueFinder) (bool, error)
}

LoadCondition defines conditions that control when a field should be loaded.

type LoadConditionBuilder

type LoadConditionBuilder interface {
	AddFieldDependencies(dependencies ...FieldLocation) LoadConditionBuilder
	AddFieldSetDependencies(fieldSetKey string, fieldKeys ...string) LoadConditionBuilder
	Create() LoadCondition
	C() LoadCondition
}

LoadConditionBuilder provides a fluent interface for constructing LoadCondition instances.

func LCB

func LCB(loadFunc func(c FieldValueFinder) (bool, error)) LoadConditionBuilder

LCB is a shorthand alias for NewLoadConditionBuilder.

func NewLoadConditionBuilder

func NewLoadConditionBuilder(loadFunc func(c FieldValueFinder) (bool, error)) LoadConditionBuilder

NewLoadConditionBuilder creates a new load condition builder with the specified load function.

type LoadConditions

type LoadConditions []LoadCondition

LoadConditions is a slice of LoadCondition interfaces.

type LoadOption

type LoadOption interface {
	LoadOptionType() string
}

LoadOption is the interface for options passed to the Load method.

func DisableGenerateFlagHandler

func DisableGenerateFlagHandler() LoadOption

DisableGenerateFlagHandler returns a LoadOption that disables the built-in generate flag handler.

func DisableHelpFlagHandler

func DisableHelpFlagHandler() LoadOption

DisableHelpFlagHandler returns a LoadOption that disables the built-in help flag handler.

type Loader

type Loader interface {
	CloneLoader() Loader
	Name() string
	Get(fieldSetKey, fieldKey string) (value any, found bool)
	GetMap(fieldSetKey string, fieldKeys []string) (fieldValues map[string]any)
	HelpString(fieldSetKey, fieldKey string) string
}

Loader is the interface that configuration loaders must implement.

type LoaderKeyOverride

type LoaderKeyOverride struct {
	LoaderName     string
	KeyOverride    string
	IgnorePrefixes bool
}

LoaderKeyOverride allows overriding the key used by a specific loader for a field.

type YAMLFileLoader added in v0.7.0

type YAMLFileLoader struct {
	Decoder   YAMLUnmarshal
	FilePaths []string
	// contains filtered or unexported fields
}

YAMLFileLoader loads configuration values from YAML files.

func NewYAMLFileLoader added in v0.7.0

func NewYAMLFileLoader(opts ...YAMLFileLoaderOption) *YAMLFileLoader

NewYAMLFileLoader creates a new YAML file loader with the given options. If no decoder is provided, yaml.Unmarshal from gopkg.in/yaml.v3 is used.

func (*YAMLFileLoader) Clone added in v0.7.0

func (l *YAMLFileLoader) Clone() *YAMLFileLoader

Clone creates a copy of the YAMLFileLoader.

func (*YAMLFileLoader) CloneLoader added in v0.7.0

func (l *YAMLFileLoader) CloneLoader() Loader

CloneLoader creates a copy of the loader as a Loader interface.

func (*YAMLFileLoader) Get added in v0.7.0

func (l *YAMLFileLoader) Get(fieldSetKey, fieldKey string) (any, bool)

Get retrieves a single field value from the loaded YAML files.

func (*YAMLFileLoader) GetMap added in v0.7.0

func (l *YAMLFileLoader) GetMap(fieldSetKey string, fieldKeys []string) map[string]any

GetMap retrieves multiple field values from the loaded YAML files.

func (*YAMLFileLoader) HelpString added in v0.7.0

func (l *YAMLFileLoader) HelpString(fieldSetKey, fieldKey string) string

HelpString returns a help string describing where this field can be configured.

func (*YAMLFileLoader) Name added in v0.7.0

func (l *YAMLFileLoader) Name() string

Name returns the name of this loader.

type YAMLFileLoaderOption added in v0.7.0

type YAMLFileLoaderOption func(*YAMLFileLoader)

YAMLFileLoaderOption is a functional option for configuring a YAMLFileLoader.

func WithYAMLDecoder added in v0.7.0

func WithYAMLDecoder(decoder YAMLUnmarshal) YAMLFileLoaderOption

WithYAMLDecoder sets a custom YAML decoder for the loader.

func WithYAMLFilePaths added in v0.7.0

func WithYAMLFilePaths(paths ...string) YAMLFileLoaderOption

WithYAMLFilePaths adds file paths to load configuration from.

type YAMLUnmarshal added in v0.7.0

type YAMLUnmarshal func(data []byte, v any) error

YAMLUnmarshal defines the function signature for YAML unmarshaling.

Directories

Path Synopsis
Package bconfconst provides constants used by the bconf package.
Package bconfconst provides constants used by the bconf package.

Jump to

Keyboard shortcuts

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