conf

package
v1.3.0-rc Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2026 License: Apache-2.0 Imports: 13 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:

1. RegisterProvider: Add configuration source providers 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

This section is empty.

Functions

func Bind added in v1.3.0

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

Bind maps property values from storage into the target object. The target must be a pointer to a struct. An optional tag specifies the root property key using ${key} syntax. Supports default values: ${key:=default}. If no tag is provided, uses ${ROOT} (binds from the root).

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 not exist 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 Properties instance from a configuration source. The source format is [optional:]<provider>:<path> or just <path>. 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 type T, such as time.Time, time.Duration, or other user-defined types. Must be called in init functions only.

func RegisterProvider added in v1.3.0

func RegisterProvider(name string, p provider.Provider)

RegisterProvider registers a Provider for a specific configuration source. Must be called in init functions only.

func RegisterReader

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

RegisterReader registers its Reader for some kind of file extension. Must be called in init functions only.

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. Must be called in init functions only.

func Resolve added in v1.3.0

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

Resolve 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: - Returns invalid syntax if braces are unbalanced.

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: - Returns invalid syntax 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. Dynamic configuration fields have the same syntax, they need to be filtered out.

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 invalid syntax.

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"
"${:=fallback}"        -> Key="", HasDef=true, Def="fallback"

Errors:

  • Returns invalid syntax 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