Documentation
¶
Overview ¶
Package synthra synthesizes configuration for Go applications from many sources into one coherent runtime state.
The name follows σύνθεσις (synthesis): to put together, to compose into a whole. Modern systems are configured in layers—files, environment variables, defaults, flags, secret stores, and remote providers. Each layer is incomplete alone; Synthra merges them in order (later overrides earlier), validates, binds to structs, and exposes the result through Synthra. **From many sources, one state.**
Keys are case-insensitive; access uses dot notation.
The package uses the same functional options pattern as other Gopherly packages: options apply to an internal config struct, and the constructor validates and builds the public Synthra from it. The returned Synthra is the runtime object used for Load, Get, and Dump.
Key Features ¶
- Multiple configuration sources (files, io/fs.FS, environment variables, Consul)
- Automatic format detection and decoding (JSON, YAML, TOML)
- Struct binding with automatic type conversion
- Validation using JSON Schema or custom validators
- Case-insensitive key access with dot notation
- Thread-safe configuration loading and access
- Configuration dumping to files or custom destinations
Quick Start ¶
Create a configuration instance with sources. Options are applied in order; any validation errors are reported when the config is built (by New or MustNew). Options must not be nil; passing a nil option results in a validation error.
cfg := synthra.MustNew(
synthra.WithFile("config.yaml"),
synthra.WithEnv("APP_"),
)
Load the configuration:
if err := cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
Access configuration values (strict reads return an error if the key is missing or the value cannot be coerced; use *Or methods for defaults):
port, err := cfg.Int("server.port")
if err != nil {
log.Fatal(err)
}
host := cfg.StringOr("server.host", "localhost")
debug, err := cfg.Bool("debug")
if err != nil {
log.Fatal(err)
}
Configuration Sources ¶
The package supports multiple configuration sources that can be combined:
Files with automatic format detection:
synthra.WithFile("config.yaml") // Detects YAML
synthra.WithFile("config.json") // Detects JSON
synthra.WithFile("config.toml") // Detects TOML
Files with explicit format:
synthra.WithFileAs("config", codec.YAML)
Virtual files inside an io/fs.FS (tests, embed.FS, etc.):
synthra.WithFileFS(fsys, "config.yaml") synthra.WithFileFSAs(fsys, "config", codec.YAML)
Environment variables with prefix:
synthra.WithEnv("APP_") // Loads APP_SERVER_PORT as server.port
Consul key-value store (CONSUL_HTTP_ADDR required; construction fails if unset):
synthra.WithConsul("production/service.yaml")
Conditional Consul (e.g. for local dev without Consul):
synthra.WithIf(os.Getenv("CONSUL_HTTP_ADDR") != "",
synthra.WithConsul("production/service.yaml"),
)
Raw content:
yamlData := []byte("port: 8080")
synthra.WithContent(yamlData, codec.YAML)
Struct Binding ¶
Bind configuration to a struct for type-safe access:
type AppConfig struct {
Port int `synthra:"port"`
Host string `synthra:"host"`
Timeout time.Duration `synthra:"timeout"`
Debug bool `synthra:"debug" default:"false"`
}
var appConfig AppConfig
cfg := synthra.MustNew(
synthra.WithFile("config.yaml"),
synthra.WithBinding(&appConfig),
)
if err := cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
// Access typed fields directly
fmt.Printf("Server: %s:%d\n", appConfig.Host, appConfig.Port)
Validation ¶
Validate configuration using struct methods:
type Config struct {
Port int `synthra:"port"`
}
func (c *Config) Validate() error {
if c.Port < 1 || c.Port > 65535 {
return fmt.Errorf("port must be between 1 and 65535")
}
return nil
}
Validate using JSON Schema:
schema := []byte(`{
"type": "object",
"properties": {
"port": {"type": "integer", "minimum": 1, "maximum": 65535}
},
"required": ["port"]
}`)
cfg := synthra.MustNew(
synthra.WithFile("config.yaml"),
synthra.WithJSONSchema(schema),
)
Validate using custom functions:
cfg := synthra.MustNew(
synthra.WithFile("config.yaml"),
synthra.WithValidator(func(values map[string]any) error {
if port, ok := values["port"].(int); ok && port < 1 {
return fmt.Errorf("invalid port: %d", port)
}
return nil
}),
)
Accessing Configuration Values ¶
Type-specific methods return (value, error). Missing keys and failed coercions are errors; use errors.Is with ErrKeyNotFound or ErrNilConfig as needed. Methods on a nil *Synthra return ErrNilConfig.
// Basic types (strict)
port, err := cfg.Int("server.port")
if err != nil {
return err
}
host, err := cfg.String("server.host")
if err != nil {
return err
}
debug, err := cfg.Bool("debug")
if err != nil {
return err
}
rate, err := cfg.Float64("rate")
if err != nil {
return err
}
// Optional keys with defaults (no error when missing)
host := cfg.StringOr("server.host", "localhost")
port := cfg.IntOr("server.port", 8080)
// Collections (strict)
tags, err := cfg.StringSlice("tags")
if err != nil {
return err
}
ports, err := cfg.IntSlice("ports")
if err != nil {
return err
}
metadata, err := cfg.StringMap("metadata")
if err != nil {
return err
}
// Time-related (strict)
timeout, err := cfg.Duration("timeout")
if err != nil {
return err
}
startTime, err := cfg.Time("start_time")
if err != nil {
return err
}
Generic Get for typed reads (same missing-key errors; primitive coercion matches GetOr for unsupported kinds):
port, err := synthra.Get[int](cfg, "server.port")
if err != nil {
log.Fatalf("port configuration required: %v", err)
}
Configuration Dumping ¶
Save the current configuration to a file:
cfg := synthra.MustNew(
synthra.WithFile("config.yaml"),
synthra.WithFileDumper("output.yaml"),
)
cfg.Load(context.Background())
cfg.Dump(context.Background()) // Writes to output.yaml
Thread Safety ¶
Synthra is safe for concurrent use by multiple goroutines. Configuration loading and reading are protected by internal locks. Multiple goroutines can safely call Load() and access configuration values simultaneously.
Escape hatches ¶
For debugging or custom serialization, *Synthra.Values returns a shallow copy of the merged top-level map. Nested maps, slices, and pointers are not deep-copied; do not mutate nested values—treat the snapshot as read-only.
Error Handling ¶
Construction failures, load/dump failures, and accessor type-conversion failures are returned as *ConfigError, shaped like os.PathError: Op names the entrypoint (OpNew, OpLoad, OpDump, or OpGet); Path is a diagnostic locator whose meaning depends on Op; Err is the cause for errors.Unwrap, errors.Is, and errors.As.
Use errors.As to inspect the structured error and switch on Op:
if err := cfg.Load(ctx); err != nil {
var ce *synthra.ConfigError
if errors.As(err, &ce) {
switch ce.Op {
case synthra.OpLoad:
log.Error("load failed", "path", ce.Path, "err", ce.Err)
}
}
return err
}
Use errors.Is for fixed outcomes such as a missing key, nil receiver, or nil context:
_, err := cfg.Int("server.port")
if errors.Is(err, synthra.ErrKeyNotFound) {
return useDefaultPort()
}
New may return errors.Join of multiple *ConfigError values. A single errors.As finds the first in the tree; to log every construction error, iterate using the errors.Join unwrap slice (see errors.Join).
Examples ¶
See the examples directory for complete working examples demonstrating various configuration patterns and use cases including:
- examples/basic — file loading and struct binding
- examples/environment — environment-only configuration
- examples/webapp — layered YAML + env, binding, and Validate
- examples/jsonschema — JSON Schema validation
- examples/customvalidator — custom validation functions
- examples/dump — configuration dumping
- examples/consul — optional Consul integration
For more details, see the package documentation at https://pkg.go.dev/gopherly.dev/synthra
Example ¶
Example demonstrates basic configuration usage.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
"gopherly.dev/synthra/codec"
)
func exampleString(cfg *synthra.Synthra, key string) string {
v, err := cfg.String(key)
if err != nil {
log.Fatal(err)
}
return v
}
func exampleInt(cfg *synthra.Synthra, key string) int {
v, err := cfg.Int(key)
if err != nil {
log.Fatal(err)
}
return v
}
func main() {
// Create config with YAML content
yamlContent := []byte(`
server:
host: localhost
port: 8080
database:
name: mydb
`)
cfg, err := synthra.New(
synthra.WithContent(yamlContent, codec.YAML),
)
if err != nil {
log.Fatal(err)
}
// Load configuration
if err = cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
// Access values
fmt.Println(exampleString(cfg, "server.host"))
fmt.Println(exampleInt(cfg, "server.port"))
fmt.Println(exampleString(cfg, "database.name"))
}
Output: localhost 8080 mydb
Example (EnvironmentVariables) ¶
Example_environmentVariables demonstrates loading configuration from environment variables.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
)
func main() {
// In real usage, set environment variables like:
// export APP_SERVER_HOST=localhost
// export APP_SERVER_PORT=8080
cfg, err := synthra.New(
synthra.WithEnv("APP_"),
)
if err != nil {
log.Fatal(err)
}
if err = cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
// Access environment variables without the prefix
// e.g., APP_SERVER_HOST becomes server.host
fmt.Println("Environment variables loaded")
}
Output: Environment variables loaded
Example (MultipleSources) ¶
Example_multipleSources demonstrates merging multiple configuration sources.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
"gopherly.dev/synthra/codec"
)
func exampleString(cfg *synthra.Synthra, key string) string {
v, err := cfg.String(key)
if err != nil {
log.Fatal(err)
}
return v
}
func exampleInt(cfg *synthra.Synthra, key string) int {
v, err := cfg.Int(key)
if err != nil {
log.Fatal(err)
}
return v
}
func main() {
// Base configuration
baseConfig := []byte(`
server:
host: localhost
port: 8080
`)
// Override configuration
overrideConfig := []byte(`
server:
port: 9090
`)
cfg, err := synthra.New(
synthra.WithContent(baseConfig, codec.YAML),
synthra.WithContent(overrideConfig, codec.YAML),
)
if err != nil {
log.Fatal(err)
}
if err = cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
// Later sources override earlier ones
fmt.Println(exampleString(cfg, "server.host"))
fmt.Println(exampleInt(cfg, "server.port"))
}
Output: localhost 9090
Index ¶
- Constants
- Variables
- func Get[T any](c *Synthra, key string) (T, error)
- func GetOr[T any](c *Synthra, key string, defaultVal T) T
- type ConfigError
- type Dumper
- type Option
- func WithBinding(v any) Option
- func WithConsul(path string) Option
- func WithConsulAs(path string, decoder codec.Decoder) Option
- func WithContent(data []byte, decoder codec.Decoder) Option
- func WithDumper(d Dumper) Option
- func WithEnv(prefix string) Option
- func WithFile(path string) Option
- func WithFileAs(path string, decoder codec.Decoder) Option
- func WithFileDumper(path string) Option
- func WithFileDumperAs(path string, encoder codec.Encoder) Option
- func WithFileFS(fsys fs.FS, path string) Option
- func WithFileFSAs(fsys fs.FS, path string, decoder codec.Decoder) Option
- func WithIf(condition bool, opts ...Option) Option
- func WithJSONSchema(schema []byte) Option
- func WithSource(loader Source) Option
- func WithTag(tagName string) Option
- func WithValidator(fn func(map[string]any) error) Option
- type Source
- type Synthra
- func (c *Synthra) Bool(key string) (bool, error)
- func (c *Synthra) BoolOr(key string, defaultVal bool) bool
- func (c *Synthra) Dump(ctx context.Context) error
- func (c *Synthra) Duration(key string) (time.Duration, error)
- func (c *Synthra) DurationOr(key string, defaultVal time.Duration) time.Duration
- func (c *Synthra) Float64(key string) (float64, error)
- func (c *Synthra) Float64Or(key string, defaultVal float64) float64
- func (c *Synthra) Get(key string) any
- func (c *Synthra) Int(key string) (int, error)
- func (c *Synthra) Int64(key string) (int64, error)
- func (c *Synthra) Int64Or(key string, defaultVal int64) int64
- func (c *Synthra) IntOr(key string, defaultVal int) int
- func (c *Synthra) IntSlice(key string) ([]int, error)
- func (c *Synthra) IntSliceOr(key string, defaultVal []int) []int
- func (c *Synthra) Load(ctx context.Context) error
- func (c *Synthra) String(key string) (string, error)
- func (c *Synthra) StringMap(key string) (map[string]any, error)
- func (c *Synthra) StringMapOr(key string, defaultVal map[string]any) map[string]any
- func (c *Synthra) StringOr(key, defaultVal string) string
- func (c *Synthra) StringSlice(key string) ([]string, error)
- func (c *Synthra) StringSliceOr(key string, defaultVal []string) []string
- func (c *Synthra) Time(key string) (time.Time, error)
- func (c *Synthra) TimeOr(key string, defaultVal time.Time) time.Time
- func (c *Synthra) Values() *map[string]any
- type Validator
Examples ¶
Constants ¶
const ( OpNew = "new" OpLoad = "load" OpDump = "dump" OpGet = "get" )
Op values identify which Synthra entrypoint produced a ConfigError. They follow the lowercase convention used by os.PathError.Op, net.OpError.Op, and net/url.Error.Op.
Variables ¶
var ErrKeyNotFound = errors.New("synthra: key not found")
ErrKeyNotFound is returned when a configuration key is missing or cannot be resolved for strict accessors. Errors may wrap this value; use errors.Is to detect it.
var ErrNilConfig = errors.New("synthra: nil Synthra")
ErrNilConfig is returned when a typed accessor or Get is used on a nil *Synthra.
var ErrNilContext = errors.New("synthra: nil context")
ErrNilContext is returned when Synthra.Load or Synthra.Dump is called with a nil context.Context.
Functions ¶
func Get ¶
Get returns the value associated with the given key as type T. If c is nil, it returns ErrNilConfig. If the key is missing or empty, or the value cannot be converted to T, it returns an error.
Example:
port, err := synthra.Get[int](cfg, "server.port")
if err != nil {
return fmt.Errorf("server.port: %w", err)
}
timeout, err := synthra.Get[time.Duration](cfg, "timeout")
if err != nil {
return err
}
func GetOr ¶
GetOr returns the value associated with the given key as type T. If the key is not found or cannot be converted to type T, it returns the provided default value. The type T is inferred from the default value.
Example:
port := synthra.GetOr(cfg, "server.port", 8080) // type inferred as int host := synthra.GetOr(cfg, "server.host", "localhost") // type inferred as string timeout := synthra.GetOr(cfg, "timeout", 30*time.Second) // type inferred as time.Duration
Types ¶
type ConfigError ¶
ConfigError is the structured error returned by Synthra for construction, load, dump, and type conversion failures at accessors.
Its shape follows os.PathError: Op names the operation, Path locates the failure in a way that depends on Op (see package docs), and Err is the underlying cause for errors.Unwrap, errors.Is, and errors.As.
Path is diagnostic text only; its format is not a stable API contract. Callers should branch on Op and use errors.Is on Err for specific reasons, not parse Path or ConfigError.Error output.
func NewConfigError ¶
func NewConfigError(op, path string, err error) *ConfigError
NewConfigError returns a *ConfigError. Op should be one of OpNew, OpLoad, OpDump, or OpGet. Path is the polymorphic locator described on ConfigError; use "" when none applies (for example nil-context errors).
func (*ConfigError) Error ¶
func (e *ConfigError) Error() string
Error implements [error]. The format is pinned for tests:
synthra: <Op>[ <Path>]: <Err>
When Path is empty, the space before Path is omitted.
type Dumper ¶
type Dumper interface {
// Dump writes the configuration values to a destination.
// The values map should not be modified by implementations.
Dump(ctx context.Context, values *map[string]any) error
}
Dumper defines the interface for configuration dumpers. Implementations write configuration data to various destinations such as files or remote services.
Dump must be safe to call concurrently.
type Option ¶
type Option func(cfg *config)
Option is a functional option that can be used to configure an Synthra instance. Options apply to an internal config struct; the constructor validates and builds the public Synthra from it. Options must not be nil; passing nil results in a validation error at construction.
func WithBinding ¶
WithBinding returns an Option that configures the Synthra instance to bind configuration data to a struct.
Example ¶
ExampleWithBinding demonstrates binding configuration to a struct.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
"gopherly.dev/synthra/codec"
)
func main() {
type ServerConfig struct {
Host string `synthra:"host"`
Port int `synthra:"port"`
}
type AppConfig struct {
Server ServerConfig `synthra:"server"`
}
yamlContent := []byte(`
server:
host: localhost
port: 8080
`)
var appConfig AppConfig
cfg, err := synthra.New(
synthra.WithContent(yamlContent, codec.YAML),
synthra.WithBinding(&appConfig),
)
if err != nil {
log.Fatal(err)
}
if err = cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
fmt.Printf("%s:%d\n", appConfig.Server.Host, appConfig.Server.Port)
}
Output: localhost:8080
func WithConsul ¶
WithConsul returns an Option that configures the Synthra instance to load configuration data from a Consul server. The format is automatically detected from the path extension. For custom formats, use WithConsulAs instead.
CONSUL_HTTP_ADDR is required. If it is not set, New/MustNew returns a validation error at construction. For conditional Consul (e.g., development without Consul), wrap this option with WithIf.
Paths support environment variable expansion using ${VAR} or $VAR syntax. Example: "${APP_ENV}/service.yaml" expands to "production/service.yaml" when APP_ENV=production
Required environment variables:
- CONSUL_HTTP_ADDR: The address of the Consul server (e.g., "http://localhost:8500")
- CONSUL_HTTP_TOKEN: The access token for authentication with Consul (optional)
Example:
cfg := synthra.MustNew(
synthra.WithConsul("production/service.yaml"), // Fails at construction if CONSUL_HTTP_ADDR is unset
)
func WithConsulAs ¶
WithConsulAs returns an Option that configures the Synthra instance to load configuration data from a Consul server with explicit decoder. Use this when you need to override the format detection.
CONSUL_HTTP_ADDR is required. If it is not set, New/MustNew returns a validation error at construction. For conditional Consul (e.g., development without Consul), wrap this option with WithIf.
Paths support environment variable expansion using ${VAR} or $VAR syntax. Example: "${APP_ENV}/service" expands to "production/service" when APP_ENV=production
Required environment variables:
- CONSUL_HTTP_ADDR: The address of the Consul server (e.g., "http://localhost:8500")
- CONSUL_HTTP_TOKEN: The access token for authentication with Consul (optional)
Example:
cfg := synthra.MustNew(
synthra.WithConsulAs("production/service", codec.JSON()),
)
func WithContent ¶
WithContent returns an Option that configures the Synthra instance to load configuration data from a byte slice. The decoder parameter specifies how to decode the data (e.g., codec.YAML(), codec.JSON()).
Example:
yamlContent := []byte("server:\n port: 8080")
cfg := synthra.MustNew(
synthra.WithContent(yamlContent, codec.YAML()),
)
Example ¶
ExampleWithContent demonstrates loading configuration from byte content.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
"gopherly.dev/synthra/codec"
)
func exampleString(cfg *synthra.Synthra, key string) string {
v, err := cfg.String(key)
if err != nil {
log.Fatal(err)
}
return v
}
func main() {
jsonContent := []byte(`{
"app": {
"name": "MyApp",
"version": "1.0.0"
}
}`)
cfg, err := synthra.New(
synthra.WithContent(jsonContent, codec.JSON),
)
if err != nil {
log.Fatal(err)
}
if err = cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
fmt.Println(exampleString(cfg, "app.name"))
fmt.Println(exampleString(cfg, "app.version"))
}
Output: MyApp 1.0.0
func WithDumper ¶
WithDumper adds a dumper to the configuration loader.
func WithEnv ¶
WithEnv returns an Option that configures the Synthra instance to load configuration data from environment variables. The prefix parameter specifies the prefix for the environment variables to be loaded. Environment variables are converted to lowercase and underscores create nested structures.
Example:
cfg := synthra.MustNew(
synthra.WithFile("config.yaml"),
synthra.WithEnv("APP_"), // Loads APP_SERVER_PORT as server.port
)
func WithFile ¶
WithFile returns an Option that configures the Synthra instance to load configuration data from a file. The format is automatically detected from the file extension (.yaml, .yml, .json, .toml). For files without extensions or custom formats, use WithFileAs instead.
Paths support environment variable expansion using ${VAR} or $VAR syntax. Example: "${CONFIG_DIR}/app.yaml" expands to "/etc/myapp/app.yaml" when CONFIG_DIR=/etc/myapp
Example:
cfg := synthra.MustNew(
synthra.WithFile("config.yaml"), // Automatically detects YAML
synthra.WithFile("override.json"), // Automatically detects JSON
)
Example ¶
ExampleWithFile demonstrates loading configuration from a file.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
"gopherly.dev/synthra/codec"
)
func exampleString(cfg *synthra.Synthra, key string) string {
v, err := cfg.String(key)
if err != nil {
log.Fatal(err)
}
return v
}
func main() {
// Create a temporary config file (in real code, use an actual file path)
cfg, err := synthra.New(
synthra.WithContent([]byte(`{"name": "example"}`), codec.JSON),
)
if err != nil {
log.Fatal(err)
}
if err = cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
fmt.Println(exampleString(cfg, "name"))
}
Output: example
func WithFileAs ¶
WithFileAs returns an Option that configures the Synthra instance to load configuration data from a file with explicit decoder. Use this when the file doesn't have an extension or when you need to override the format detection.
Paths support environment variable expansion using ${VAR} or $VAR syntax. Example: "${CONFIG_DIR}/app" expands to "/etc/myapp/app" when CONFIG_DIR=/etc/myapp
Example:
cfg := synthra.MustNew(
synthra.WithFileAs("config", codec.YAML()), // No extension, specify YAML
synthra.WithFileAs("config.dat", codec.JSON()), // Wrong extension, specify JSON
)
func WithFileDumper ¶
WithFileDumper returns an Option that configures the Synthra instance to dump configuration data to a file. The format is automatically detected from the file extension (.yaml, .yml, .json, .toml). For files without extensions or custom formats, use WithFileDumperAs instead.
Paths support environment variable expansion using ${VAR} or $VAR syntax. Example: "${LOG_DIR}/config.yaml" expands to "/var/log/config.yaml" when LOG_DIR=/var/log
Example:
cfg := synthra.MustNew(
synthra.WithFile("config.yaml"),
synthra.WithFileDumper("output.yaml"), // Auto-detects YAML
)
func WithFileDumperAs ¶
WithFileDumperAs returns an Option that configures the Synthra instance to dump configuration data to a file with explicit encoder. Use this when the file doesn't have an extension or when you need to override the format detection.
Paths support environment variable expansion using ${VAR} or $VAR syntax. Example: "${OUTPUT_DIR}/config" expands to "/tmp/config" when OUTPUT_DIR=/tmp
Example:
cfg := synthra.MustNew(
synthra.WithFile("config.yaml"),
synthra.WithFileDumperAs("output", codec.YAML()), // No extension, specify YAML
)
func WithFileFS ¶
WithFileFS returns an Option that loads configuration from path inside fsys. The format is detected from path's file extension, like WithFile. Paths support environment variable expansion using ${VAR} or $VAR syntax.
If fsys is nil, New returns a validation error at construction.
Example (tests with testing/fstest.MapFS):
fsys := fstest.MapFS{"app.yaml": &fstest.MapFile{Data: []byte("port: 8080\n")}}
cfg := synthra.MustNew(synthra.WithFileFS(fsys, "app.yaml"))
func WithFileFSAs ¶
WithFileFSAs returns an Option that loads configuration from path inside fsys using an explicit decoder, like WithFileAs. Paths support environment variable expansion using ${VAR} or $VAR syntax.
If fsys is nil, New returns a validation error at construction.
func WithIf ¶
WithIf returns an Option that applies the provided options only when condition is true. When condition is false, this option is a no-op.
Example:
cfg := synthra.MustNew(
synthra.WithFile("config.yaml"),
synthra.WithIf(os.Getenv("CONSUL_HTTP_ADDR") != "",
synthra.WithConsul("production/service.yaml"),
),
)
func WithJSONSchema ¶
WithJSONSchema adds a JSON Schema for validation.
func WithSource ¶
WithSource adds a source to the configuration loader.
func WithTag ¶
WithTag sets a custom struct tag name for binding (default: "synthra"). Use it when the default tag clashes with another convention or you want a shorter key (for example "cfg" or "config").
Example:
type AppConfig struct {
Port int `cfg:"port"` // Using custom tag
}
cfg := synthra.MustNew(
synthra.WithFile("config.yaml"),
synthra.WithBinding(&appConfig),
synthra.WithTag("cfg"),
)
func WithValidator ¶
WithValidator adds a custom validation function.
Example ¶
ExampleWithValidator demonstrates using a custom validator.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
"gopherly.dev/synthra/codec"
)
func main() {
yamlContent := []byte(`name: myapp`)
cfg, err := synthra.New(
synthra.WithContent(yamlContent, codec.YAML),
synthra.WithValidator(func(cfgMap map[string]any) error {
// Custom validation logic
if _, ok := cfgMap["name"]; !ok {
return fmt.Errorf("name is required")
}
return nil
}),
)
if err != nil {
log.Fatal(err)
}
if err = cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
fmt.Println("Validation passed")
}
Output: Validation passed
type Source ¶
type Source interface {
// Load loads configuration data from the source.
// It returns a map containing the configuration key-value pairs.
// Keys are normalized to lowercase for case-insensitive access.
Load(ctx context.Context) (map[string]any, error)
}
Source defines the interface for configuration sources. Implementations load configuration data from various locations such as files, environment variables, or remote services.
Load must be safe to call concurrently.
type Synthra ¶
type Synthra struct {
// contains filtered or unexported fields
}
Synthra manages configuration data loaded from multiple sources. It provides thread-safe access to configuration values and supports binding to structs, validation, and dumping to files.
Synthra is the runtime object returned by New/MustNew; use it for Load, Get, and Dump. Synthra is safe for concurrent use by multiple goroutines.
func MustNew ¶
MustNew creates a new Synthra instance with the provided options. It panics if validation fails after applying options. Use this in main() or initialization code where panic is acceptable. For cases where error handling is needed, use New() instead.
Example ¶
ExampleMustNew demonstrates creating a configuration instance with panic on error.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
)
func main() {
cfg := synthra.MustNew()
if err := cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
fmt.Println("Synthra created successfully")
}
Output: Synthra created successfully
func New ¶
New creates a new Synthra instance with the provided options. Options are applied to an internal config; after validation, the public Synthra is built from it. Options are applied in order; validation errors are collected and reported after all options are applied, so callers never receive a partially-initialized config. Options must not be nil— passing a nil option results in a validation error. Use MustNew for main() or when panic on error is acceptable.
Example ¶
ExampleNew demonstrates creating a new configuration instance.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
)
func main() {
cfg, err := synthra.New()
if err != nil {
log.Fatal(err)
}
if err = cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
fmt.Println("Synthra created successfully")
}
Output: Synthra created successfully
func (*Synthra) Bool ¶
Bool returns the value at key as a bool. It returns an error if c is nil, the key is missing, or the value cannot be converted.
Example:
debug, err := cfg.Bool("debug")
if err != nil {
return err
}
Example ¶
ExampleSynthra_Bool demonstrates retrieving boolean values.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
"gopherly.dev/synthra/codec"
)
func exampleBool(cfg *synthra.Synthra, key string) bool {
v, err := cfg.Bool(key)
if err != nil {
log.Fatal(err)
}
return v
}
func main() {
jsonContent := []byte(`{"debug": true, "verbose": false}`)
cfg, err := synthra.New(
synthra.WithContent(jsonContent, codec.JSON),
)
if err != nil {
log.Fatal(err)
}
if err = cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
fmt.Println(exampleBool(cfg, "debug"))
fmt.Println(exampleBool(cfg, "verbose"))
}
Output: true false
func (*Synthra) BoolOr ¶
BoolOr returns the value associated with the given key as a boolean, or the default value if not found.
Example:
debug := cfg.BoolOr("debug", false)
func (*Synthra) Dump ¶
Dump writes the current configuration values to the registered dumpers.
Errors:
- Returns *ConfigError with OpDump if ctx is nil (ErrNilContext)
- Returns *ConfigError with OpDump if any dumper fails to write the configuration
Example ¶
ExampleSynthra_Dump demonstrates writing configuration to registered dumpers.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
"gopherly.dev/synthra/codec"
"gopherly.dev/synthra/synthratest"
)
func main() {
// Create a mock dumper for demonstration
dumper := &synthratest.Dumper{}
cfg := synthra.MustNew(
synthra.WithContent([]byte(`{"service": "api", "version": "1.0"}`), codec.JSON),
synthra.WithDumper(dumper),
)
if err := cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
if err := cfg.Dump(context.Background()); err != nil {
log.Fatal(err)
}
fmt.Println("Configuration dumped successfully")
}
Output: Configuration dumped successfully
func (*Synthra) Duration ¶
Duration returns the value at key as a time.Duration. It returns an error if c is nil, the key is missing, or the value cannot be converted.
Example:
timeout, err := cfg.Duration("timeout")
if err != nil {
return err
}
func (*Synthra) DurationOr ¶
DurationOr returns the value associated with the given key as a time.Duration, or the default value if not found.
Example:
timeout := cfg.DurationOr("timeout", 30*time.Second)
func (*Synthra) Float64 ¶
Float64 returns the value at key as a float64. It returns an error if c is nil, the key is missing, or the value cannot be converted.
Example:
rate, err := cfg.Float64("rate")
if err != nil {
return err
}
func (*Synthra) Float64Or ¶
Float64Or returns the value associated with the given key as a float64, or the default value if not found.
Example:
rate := cfg.Float64Or("rate", 0.5)
func (*Synthra) Get ¶
Get returns the value associated with the given key as an any type. If the key is not found, it returns nil.
Example ¶
ExampleSynthra_Get demonstrates retrieving configuration values.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
"gopherly.dev/synthra/codec"
)
func main() {
yamlContent := []byte(`
settings:
enabled: true
count: 42
`)
cfg, err := synthra.New(
synthra.WithContent(yamlContent, codec.YAML),
)
if err != nil {
log.Fatal(err)
}
if err = cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
fmt.Println(cfg.Get("settings.enabled"))
fmt.Println(cfg.Get("settings.count"))
}
Output: true 42
func (*Synthra) Int ¶
Int returns the value at key as an int. It returns an error if c is nil, the key is missing, or the value cannot be converted.
Example:
port, err := cfg.Int("server.port")
if err != nil {
return err
}
Example ¶
ExampleSynthra_Int demonstrates retrieving integer values.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
"gopherly.dev/synthra/codec"
)
func exampleInt(cfg *synthra.Synthra, key string) int {
v, err := cfg.Int(key)
if err != nil {
log.Fatal(err)
}
return v
}
func main() {
jsonContent := []byte(`{"port": 8080, "workers": 4}`)
cfg, err := synthra.New(
synthra.WithContent(jsonContent, codec.JSON),
)
if err != nil {
log.Fatal(err)
}
if err = cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
fmt.Println(exampleInt(cfg, "port"))
fmt.Println(exampleInt(cfg, "workers"))
}
Output: 8080 4
func (*Synthra) Int64 ¶
Int64 returns the value at key as an int64. It returns an error if c is nil, the key is missing, or the value cannot be converted.
Example:
maxSize, err := cfg.Int64("max_size")
if err != nil {
return err
}
func (*Synthra) Int64Or ¶
Int64Or returns the value associated with the given key as an int64, or the default value if not found.
Example:
maxSize := cfg.Int64Or("max_size", 1024)
func (*Synthra) IntOr ¶
IntOr returns the value associated with the given key as an int, or the default value if not found.
Example:
port := cfg.IntOr("server.port", 8080)
func (*Synthra) IntSlice ¶
IntSlice returns the value at key as a []int. It returns an error if c is nil, the key is missing, or the value cannot be converted.
Example:
ports, err := cfg.IntSlice("ports")
if err != nil {
return err
}
func (*Synthra) IntSliceOr ¶
IntSliceOr returns the value associated with the given key as a slice of integers, or the default value if not found.
Example:
ports := cfg.IntSliceOr("ports", []int{8080, 8081})
func (*Synthra) Load ¶
Load loads configuration data from the registered sources and merges it into the internal values map. The method validates the configuration data before atomically updating the internal state. Load is safe to call concurrently.
Errors:
- Returns *ConfigError with OpLoad if ctx is nil (ErrNilContext)
- Returns *ConfigError with OpLoad if any source fails to load or merge
- Returns *ConfigError with OpLoad and Path "json-schema" if JSON schema validation fails
- Returns *ConfigError with OpLoad if custom validators fail
- Returns *ConfigError with OpLoad if binding or struct validation fails
Example ¶
ExampleSynthra_Load demonstrates loading configuration.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
"gopherly.dev/synthra/codec"
)
func exampleString(cfg *synthra.Synthra, key string) string {
v, err := cfg.String(key)
if err != nil {
log.Fatal(err)
}
return v
}
func exampleInt(cfg *synthra.Synthra, key string) int {
v, err := cfg.Int(key)
if err != nil {
log.Fatal(err)
}
return v
}
func main() {
cfg := synthra.MustNew(
synthra.WithContent([]byte(`{"app": "example", "port": 8080}`), codec.JSON),
)
if err := cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
app := exampleString(cfg, "app")
port := exampleInt(cfg, "port")
fmt.Printf("App: %s, Port: %d\n", app, port)
}
Output: App: example, Port: 8080
func (*Synthra) String ¶
String returns the value at key as a string. It returns an error if c is nil, the key is missing, or the value cannot be converted.
Example:
host, err := cfg.String("server.host")
if err != nil {
return err
}
Example ¶
ExampleSynthra_String demonstrates retrieving string values.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
"gopherly.dev/synthra/codec"
)
func exampleString(cfg *synthra.Synthra, key string) string {
v, err := cfg.String(key)
if err != nil {
log.Fatal(err)
}
return v
}
func main() {
jsonContent := []byte(`{"name": "MyApp", "env": "production"}`)
cfg, err := synthra.New(
synthra.WithContent(jsonContent, codec.JSON),
)
if err != nil {
log.Fatal(err)
}
if err = cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
fmt.Println(exampleString(cfg, "name"))
fmt.Println(exampleString(cfg, "env"))
}
Output: MyApp production
func (*Synthra) StringMap ¶
StringMap returns the value at key as a map[string]any. It returns an error if c is nil, the key is missing, or the value cannot be converted.
Example:
metadata, err := cfg.StringMap("metadata")
if err != nil {
return err
}
Example ¶
ExampleSynthra_StringMap demonstrates retrieving string maps.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
"gopherly.dev/synthra/codec"
)
func exampleStringMap(cfg *synthra.Synthra, key string) map[string]any {
v, err := cfg.StringMap(key)
if err != nil {
log.Fatal(err)
}
return v
}
func main() {
yamlContent := []byte(`
metadata:
author: John Doe
version: 1.0.0
`)
cfg, err := synthra.New(
synthra.WithContent(yamlContent, codec.YAML),
)
if err != nil {
log.Fatal(err)
}
if err = cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
metadata := exampleStringMap(cfg, "metadata")
fmt.Println(metadata["author"])
fmt.Println(metadata["version"])
}
Output: John Doe 1.0.0
func (*Synthra) StringMapOr ¶
StringMapOr returns the value associated with the given key as a map[string]any, or the default value if not found.
Example:
metadata := cfg.StringMapOr("metadata", map[string]any{"version": "1.0"})
func (*Synthra) StringOr ¶
StringOr returns the value associated with the given key as a string, or the default value if not found.
Example:
host := cfg.StringOr("server.host", "localhost")
func (*Synthra) StringSlice ¶
StringSlice returns the value at key as a []string. It returns an error if c is nil, the key is missing, or the value cannot be converted.
Example:
tags, err := cfg.StringSlice("tags")
if err != nil {
return err
}
Example ¶
ExampleSynthra_StringSlice demonstrates retrieving string slices.
package main
import (
"context"
"fmt"
"log"
"gopherly.dev/synthra"
"gopherly.dev/synthra/codec"
)
func exampleStringSlice(cfg *synthra.Synthra, key string) []string {
v, err := cfg.StringSlice(key)
if err != nil {
log.Fatal(err)
}
return v
}
func main() {
yamlContent := []byte(`
tags:
- web
- api
- backend
`)
cfg, err := synthra.New(
synthra.WithContent(yamlContent, codec.YAML),
)
if err != nil {
log.Fatal(err)
}
if err = cfg.Load(context.Background()); err != nil {
log.Fatal(err)
}
tags := exampleStringSlice(cfg, "tags")
fmt.Printf("%v\n", tags)
}
Output: [web api backend]
func (*Synthra) StringSliceOr ¶
StringSliceOr returns the value associated with the given key as a slice of strings, or the default value if not found.
Example:
tags := cfg.StringSliceOr("tags", []string{"default"})
func (*Synthra) Time ¶
Time returns the value at key as a time.Time. It returns an error if c is nil, the key is missing, or the value cannot be converted.
Example:
startTime, err := cfg.Time("start_time")
if err != nil {
return err
}
func (*Synthra) TimeOr ¶
TimeOr returns the value associated with the given key as a time.Time, or the default value if not found.
Example:
startTime := cfg.TimeOr("start_time", time.Now())
func (*Synthra) Values ¶
Values returns a pointer to a shallow copy of the loaded configuration map. The copy is taken while holding a read lock; nested maps, slices, and pointers inside values are not deep-copied, so mutating nested data still affects the same objects held by this Synthra. If Load has not run yet, it returns a pointer to a new empty map.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package codec provides encoding and decoding functionality for configuration data.
|
Package codec provides encoding and decoding functionality for configuration data. |
|
Package dumper provides configuration dumper implementations.
|
Package dumper provides configuration dumper implementations. |
|
examples
|
|
|
basic
command
Package main shows YAML file loading and struct binding with Synthra.
|
Package main shows YAML file loading and struct binding with Synthra. |
|
consul
command
Package main loads local YAML, optionally merges Consul KV, then env.
|
Package main loads local YAML, optionally merges Consul KV, then env. |
|
customvalidator
command
Package main demonstrates cross-field checks with synthra.WithValidator.
|
Package main demonstrates cross-field checks with synthra.WithValidator. |
|
defaults
command
Package main shows merge order: baked-in defaults, then file, then env.
|
Package main shows merge order: baked-in defaults, then file, then env. |
|
dump
command
Package main writes the merged effective configuration to a YAML file.
|
Package main writes the merged effective configuration to a YAML file. |
|
environment
command
Package main demonstrates loading configuration from environment variables with Synthra.
|
Package main demonstrates loading configuration from environment variables with Synthra. |
|
formats
command
Package main loads JSON and TOML with explicit codecs via WithFileAs.
|
Package main loads JSON and TOML with explicit codecs via WithFileAs. |
|
jsonschema
command
Package main demonstrates JSON Schema validation on loaded configuration.
|
Package main demonstrates JSON Schema validation on loaded configuration. |
|
testing
command
Package main exists so `go run .` works; see README and *_test.go.
|
Package main exists so `go run .` works; see README and *_test.go. |
|
webapp
command
Package main demonstrates layered configuration (YAML defaults plus environment overrides), struct binding, and validation with Synthra.
|
Package main demonstrates layered configuration (YAML defaults plus environment overrides), struct binding, and validation with Synthra. |
|
Package source provides configuration source implementations.
|
Package source provides configuration source implementations. |
|
Package synthratest provides test helpers for packages that import gopherly.dev/synthra.
|
Package synthratest provides test helpers for packages that import gopherly.dev/synthra. |