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: ¶
Expression validation using expr tag: type Config struct { Port int `expr:"$ > 0 && $ < 65535"` }
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 ¶
- Variables
- func Bind(p flatten.Storage, i any, tag ...string) error
- func BindValue(p flatten.Storage, v reflect.Value, t reflect.Type, param BindParam, ...) (RetErr error)
- func Load(source string) (*flatten.Properties, error)
- func RegisterConverter[T any](fn Converter[T])
- func RegisterProvider(name string, p provider.Provider)
- func RegisterReader(r reader.Reader, ext ...string)
- func RegisterValidateFunc[T any](name string, fn ValidateFunc[T])
- func ResolveString(p flatten.Storage, s string) (string, error)
- type BindParam
- type Converter
- type Filter
- type ParsedTag
- type ValidateFunc
Constants ¶
This section is empty.
Variables ¶
Functions ¶
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 ¶
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
RegisterProvider registers a Provider for a specific configuration source.
func RegisterReader ¶
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 ¶
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 ¶
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 Filter ¶ added in v1.1.2
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 ¶
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.
type ValidateFunc ¶ added in v1.2.0
ValidateFunc defines a type for validation functions, which accept a value of type T and return a boolean result.