conf

package
v1.3.0-alpha Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package conf provides a configuration binding framework with hierarchical resolution, type-safe mapping, and validation capabilities.

Core Concepts:

The framework enables mapping configuration data from multiple sources into Go structures with:

- Hierarchical property resolution using ${key} syntax - Type-safe binding with automatic conversions - Expression-based validation - Extensible architecture via pluggable components

Tag Syntax:

Struct tags use the following format:

value:"${key:=default}"

Key features: - Nested keys (e.g., service.endpoint) - Dynamic defaults (e.g., ${DB_HOST:=localhost:${DB_PORT:=3306}})

Data Binding:

Supports binding to various types with automatic conversion:

1. Primitives: Uses strconv for basic type conversions 2. Complex Types:

  • Slices: From indexed properties
  • Maps: Via subkey expansion
  • Structs: Recursive binding of nested structures

3. Custom Types: Register converters using RegisterConverter

Validation System:

  1. Expression validation using expr tag: type Config struct { Port int `expr:"$ > 0 && $ < 65535"` }

  2. Custom validators: RegisterValidateFunc("futureDate", func(t time.Time) bool { return t.After(time.Now()) })

File Support:

Built-in readers handle: - JSON (.json) - Properties (.properties) - YAML (.yaml/.yml) - TOML (.toml/.tml)

Register custom readers with RegisterReader.

Property Resolution:

- Recursive ${} substitution - Type-aware defaults - Chained defaults (${A:=${B:=C}})

Extension Points:

2. RegisterConverter: Add type converters 3. RegisterReader: Support new file formats 4. RegisterValidateFunc: Add custom validators

Examples:

Basic binding:

type ServerConfig struct {
    Host string `value:"${host:=localhost}"`
    Port int    `value:"${port:=8080}"`
}

Nested structure:

type AppConfig struct {
    DB      Database `value:"${db}"`
    Timeout string   `value:"${timeout:=5s}"`
}

Slice binding:

type Config struct {
    Endpoints []string `value:"${endpoints}"`
    Features  []string `value:"${features}"`
}

Validation:

type UserConfig struct {
    Age     int       `value:"${age}" expr:"$ >= 18"`
    Email   string    `value:"${email}" expr:"contains($, '@')"`
    Expires time.Time `value:"${expires}" expr:"futureDate($)"`
}

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotExist      = errutil.Explain(nil, "not exist")
	ErrInvalidSyntax = errutil.Explain(nil, "invalid syntax")
)

Functions

func Bind added in v1.3.0

func Bind(p flatten.Storage, i any, tag ...string) error

Bind maps property values into the provided target object.

func BindValue

func BindValue(p flatten.Storage, v reflect.Value, t reflect.Type, param BindParam, filter Filter) (RetErr error)

BindValue attempts to bind a property value from the property source `p` into the given reflect.Value `v`, based on metadata in `param`.

Supported binding targets: - Primitive types (string, int, float, bool, etc.). - Structs (recursively bound field by field). - Maps (bound by iterating subkeys). - Slices (bound by either indexed keys or split strings).

Errors: - Returns ErrNotExist if the property is missing without a default. - Returns type conversion errors if parsing fails. - Returns wrapped errors with context (path, type).

func Load

func Load(source string) (*flatten.Properties, error)

Load creates a MutableProperties instance from a configuration file. Returns an error if the file type is not supported or parsing fails.

func RegisterConverter

func RegisterConverter[T any](fn Converter[T])

RegisterConverter registers a Converter for a non-primitive type such as time.Time, time.Duration, or other user-defined value types.

func RegisterProvider added in v1.3.0

func RegisterProvider(name string, p provider.Provider)

RegisterProvider registers a Provider for a specific configuration source.

func RegisterReader

func RegisterReader(r reader.Reader, ext ...string)

RegisterReader registers its Reader for some kind of file extension.

func RegisterValidateFunc added in v1.2.0

func RegisterValidateFunc[T any](name string, fn ValidateFunc[T])

RegisterValidateFunc registers a validation function with a specific name. The function can then be used in validation expressions.

func ResolveString

func ResolveString(p flatten.Storage, s string) (string, error)

ResolveString expands property references of the form ${key} inside a string, recursively resolving nested expressions.

Supported features: - Nested references: e.g. "${outer${inner}}" - Default values: "${key:=fallback}" - Arbitrary string concatenation around references.

Example:

Storage:
  "host" = "localhost"
  "port" = "8080"
Input:
  "http://${host}:${port}"
Output:
  "http://localhost:8080"

Errors: - ErrInvalidSyntax if braces are unbalanced. - Propagates errors from resolve().

Types

type BindParam

type BindParam struct {
	Key      string            // full property key
	Path     string            // full property path
	Tag      ParsedTag         // parsed tag
	Validate reflect.StructTag // original struct field tag for validation
}

BindParam holds metadata needed to bind a single configuration value to a Go struct field, slice element, or map entry.

func (*BindParam) BindTag

func (param *BindParam) BindTag(tag string, validate reflect.StructTag) error

BindTag parses the tag string, stores the ParsedTag in BindParam, and resolves nested key expansion.

Special cases: - "${:=default}" -> Key is empty, only default is set. - "${ROOT}" -> explicitly resets Key to an empty string.

If a BindParam already has a Key, new keys are appended hierarchically, e.g. parent Key="db", tag="${host}" -> final Key="db.host".

Errors: - ErrInvalidSyntax if the tag string is malformed or empty without default.

type Converter

type Converter[T any] func(string) (T, error)

Converter converts a string to a target type T.

type Filter added in v1.1.2

type Filter interface {
	Do(i any, param BindParam) (bool, error)
}

Filter defines an interface for filtering configuration fields during binding.

type ParsedTag

type ParsedTag struct {
	Key    string // short property key
	Def    string // default value string
	HasDef bool   // indicates whether a default value exists
}

ParsedTag represents a parsed configuration tag that encodes metadata for binding configuration values from property sources.

A tag string generally follows the pattern:

${key:=default}

- "key": the property key used to look up a value. - "default": optional fallback value if the key does not exist.

Examples:

"${db.host:=localhost}"       -> key=db.host, default=localhost
"${ports:=8080,9090}"         -> key=ports, default=8080,9090
"${:=foo}"                    -> empty key, only default value "foo"

The parsing logic is strict; malformed tags will result in ErrInvalidSyntax.

func ParseTag

func ParseTag(tag string) (ret ParsedTag, err error)

ParseTag parses a tag string into a ParsedTag struct.

Supported syntax: `${key:=default}`

- The `${...}` block is mandatory. - ":=" introduces an optional default value.

Example parses:

"${foo}"               -> Key="foo"
"${foo:=bar}"          -> Key="foo", HasDef=true, Def="bar"
"${foo:=bar}"          -> Key="foo", HasDef=true, Def="bar"
"${:=fallback}"        -> Key="", HasDef=true, Def="fallback"

Errors:

  • Returns ErrInvalidSyntax if the string does not follow the pattern.

func (ParsedTag) String added in v1.2.0

func (tag ParsedTag) String() string

type ValidateFunc added in v1.2.0

type ValidateFunc[T any] func(T) bool

ValidateFunc defines a type for validation functions, which accept a value of type T and return a boolean result.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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