synthra

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: May 17, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

README

Synthra

CI codecov Go Reference Go Report Card License

From many sources, one config.

Synthra is a Go library that builds one configuration from many places. It reads from files, environment variables, Consul, in-memory bytes, and any custom source. It merges them in order, validates the result, and binds it to a struct if you want. The name comes from the Greek word synthesis, which means "to put together."

go get gopherly.dev/synthra

Requires Go 1.26 or later.

import "gopherly.dev/synthra"

How it works

flowchart LR
    S1[File] --> Merge
    S2[Env] --> Merge
    S3[Consul] --> Merge
    S4[Custom] --> Merge
    Merge --> Validate
    Validate --> Bind["Bind to struct"]
    Bind --> Ready["Synthra ready"]
    Ready --> Read["Get / String / Int / ..."]
    Ready --> Dump["Dump to file"]

    style S1 fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f
    style S2 fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f
    style S3 fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f
    style S4 fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f
    style Merge fill:#fef3c7,stroke:#f59e0b,color:#78350f
    style Validate fill:#fef3c7,stroke:#f59e0b,color:#78350f
    style Bind fill:#fef3c7,stroke:#f59e0b,color:#78350f
    style Ready fill:#d1fae5,stroke:#10b981,color:#064e3b
    style Read fill:#ede9fe,stroke:#8b5cf6,color:#3b0764
    style Dump fill:#ede9fe,stroke:#8b5cf6,color:#3b0764

Why Synthra

Most Go services load configuration from more than one place. A YAML file holds the defaults, environment variables override them in production, and a key-value store like Consul holds shared settings. Synthra makes this simple:

  • One small API for all sources.
  • Clear merge order: later sources win over earlier ones.
  • Twelve-Factor friendly environment support with clear source precedence, so config can move cleanly across environments.
  • Format detection from the file extension (.yaml, .yml, .json, .toml).
  • JSON Schema defaults applied automatically: any "default" declared in the schema fills missing keys, including patternProperties defaults for dynamic key names.
  • Dynamic schema selection (WithJSONSchemaSelector): choose the schema at Load time based on a value read from the config itself (e.g. apiVersion), no two-pass workaround needed.
  • Post-load transforms (WithTransform) and string interpolation (WithInterpolation) run before validation.
  • Struct binding with type conversion, default values, and validation.
  • Case-insensitive keys with dot notation (server.port).
  • Safe for use from many goroutines at the same time.
  • Small core, optional extras. Consul is the only heavy dependency; it ships with the module, but you only interact with it if you call WithConsul (optionally wrapped with WithIf).
  • A synthratest helper package for tests.

Contents

  1. How it works
  2. Quick start
  3. Sources
  4. Formats
  5. Struct binding
  6. Default values
  7. JSON Schema defaults
  8. Dynamic schema selection
  9. Transforms and interpolation
  10. Validation
  11. Reading values
  12. Merge order and precedence
  13. Case insensitivity and dot notation
  14. Environment variable naming
  15. Dumping configuration
  16. Testing helpers
  17. Custom sources and codecs
  18. Error handling
  19. Thread safety
  20. Examples
  21. License
  22. Contributing

Quick start

Create a config.yaml file:

server:
  host: "localhost"
  port: 8080
debug: true

Then load it:

package main

import (
    "context"
    "fmt"
    "log"

    "gopherly.dev/synthra"
)

type Config struct {
    Server struct {
        Host string `synthra:"host"`
        Port int    `synthra:"port"`
    } `synthra:"server"`
    Debug bool `synthra:"debug"`
}

func main() {
    var cfg Config

    s := synthra.MustNew(
        synthra.WithFile("config.yaml"),
        synthra.WithEnv("APP_"),
        synthra.WithBinding(&cfg),
    )

    if err := s.Load(context.Background()); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("listening on %s:%d (debug=%v)\n",
        cfg.Server.Host, cfg.Server.Port, cfg.Debug)
}

Set APP_SERVER_PORT=9090 to override the YAML port at runtime.

Sources

A source is any type whose Load method returns a map[string]any. Synthra ships several built-in sources.

File with automatic format detection

The format comes from the file extension. Supported extensions: .yaml, .yml, .json, .toml.

synthra.WithFile("config.yaml")
synthra.WithFile("config.json")
synthra.WithFile("config.toml")

Paths support shell-style environment variable expansion: ${VAR} or $VAR.

synthra.WithFile("${CONFIG_DIR}/app.yaml")
File with explicit format

Use this when the file has no extension, or when the extension does not match the real format.

import "gopherly.dev/synthra/codec"

synthra.WithFileAs("config", codec.YAML)
synthra.WithFileAs("config.dat", codec.JSON)
File inside an io/fs.FS

Useful for embedded files (embed.FS) and tests (testing/fstest.MapFS).

import (
    "embed"
    "gopherly.dev/synthra"
)

//go:embed config.yaml
var configFS embed.FS

s := synthra.MustNew(
    synthra.WithFileFS(configFS, "config.yaml"),
)

You can also use WithFileFSAs to pass an explicit decoder.

Environment variables

Pick a prefix. Synthra reads every variable with that prefix, removes it, lowercases the rest, and splits on _ to build a nested map.

synthra.WithEnv("APP_")

APP_SERVER_PORT=8080 becomes server.port = "8080".

See Environment variable naming for the full rules.

In-memory content

Pass raw bytes and a decoder. Good for baked-in defaults.

defaults := []byte(`
server:
  port: 3000
`)

synthra.WithContent(defaults, codec.YAML)
Consul key-value store

Reads a key from Consul and decodes the value. The format is detected from the path, like for files.

synthra.WithConsul("production/service.yaml")

CONSUL_HTTP_ADDR must be set. If it is missing, New returns an error at construction. For dev setups where Consul may not run, gate it with WithIf:

synthra.WithIf(os.Getenv("CONSUL_HTTP_ADDR") != "",
    synthra.WithConsul("production/service.yaml"),
)

This pattern does nothing when CONSUL_HTTP_ADDR is not set. The token, if any, comes from CONSUL_HTTP_TOKEN.

Use WithConsulAs when the path has no extension, or when the extension does not match the format:

synthra.WithConsulAs("production/service", codec.JSON)
synthra.WithIf(os.Getenv("CONSUL_HTTP_ADDR") != "",
    synthra.WithConsulAs("production/service", codec.JSON),
)
Custom source

Implement the Source interface and pass it through WithSource:

type Source interface {
    Load(ctx context.Context) (map[string]any, error)
}

s := synthra.MustNew(
    synthra.WithSource(mySource),
)

The source.NewMap helper is useful for tests and embedded trees:

import "gopherly.dev/synthra/source"

s := synthra.MustNew(
    synthra.WithSource(source.NewMap(map[string]any{
        "server": map[string]any{"port": 8080},
    })),
)

Formats

The codec package ships ready-to-use codecs:

Codec Reads Writes
codec.YAML yes yes
codec.JSON yes yes
codec.TOML yes yes
codec.EnvVar yes no

It also offers scalar decoders for single-value sources (for example, a Consul key that holds one number):

codec.ParseInt("port")       // bytes -> map{"port": int(...)}
codec.ParseBool("debug")
codec.ParseString("name")
codec.ParseDuration("timeout")
codec.ParseTime("start")
codec.ParseAs("count", strconv.Atoi)  // generic parser

Struct binding

Binding turns the merged map into a typed struct. Add WithBinding and pass a pointer to a struct.

type Config struct {
    Host    string        `synthra:"host"`
    Port    int           `synthra:"port"`
    Timeout time.Duration `synthra:"timeout"`
    Roles   []string      `synthra:"roles"`
    URL     *url.URL      `synthra:"url"`
}

var cfg Config
s := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithBinding(&cfg),
)

if err := s.Load(context.Background()); err != nil {
    log.Fatal(err)
}

The default struct tag is synthra. You can pick another tag name:

synthra.WithTag("cfg")

Built-in type conversions:

  • Strings, numbers, and booleans through the cast library.
  • time.Duration from strings like "30s" or "5m".
  • time.Time from RFC 3339 strings (for example "2025-01-01T00:00:00Z").
  • *url.URL from any string URL.
  • Slices from comma-separated strings or YAML/JSON arrays.

Default values

Use the default struct tag for fallback values. A default applies only when the field stays at its zero value after binding.

type Config struct {
    Host    string        `synthra:"host"    default:"localhost"`
    Port    int           `synthra:"port"    default:"8080"`
    Debug   bool          `synthra:"debug"   default:"false"`
    Timeout time.Duration `synthra:"timeout" default:"30s"`
}

You can also pass in defaults as a source. This is good when you want them visible in the merged map (for example, for Dump):

defaults := []byte(`server: { port: 3000 }`)

synthra.MustNew(
    synthra.WithContent(defaults, codec.YAML),
    synthra.WithFile("config.yaml"),
    synthra.WithEnv("APP_"),
)

JSON Schema defaults

When you pass a schema with WithJSONSchema, Synthra automatically extracts every "default" value declared in the schema and applies it to any key that is missing from the loaded configuration. This happens after sources are merged and before validation runs, so the schema validator always sees a fully populated map.

schema := []byte(`{
    "type": "object",
    "properties": {
        "port":      {"type": "integer", "default": 8080},
        "log_level": {"type": "string",  "default": "info",
                      "enum": ["debug", "info", "warn", "error"]}
    }
}`)

s := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithJSONSchema(schema),
)
// If config.yaml omits "port" and "log_level", they are set to 8080 and "info"
// before validation. Values present in config.yaml are never overridden.

Defaults are applied at every level of nesting, including patternProperties. For dynamic key names (e.g. a map of named components), Synthra applies the patternProperties defaults to every existing key that matches the pattern:

schema := []byte(`{
    "properties": {
        "components": {
            "patternProperties": {
                "^[a-z0-9-]+$": {
                    "properties": {
                        "role":     {"type": "string",  "default": "service"},
                        "replicas": {"type": "integer", "default": 1}
                    }
                }
            }
        }
    }
}`)

// config.yaml:
//   components:
//     web:
//       image: nginx
//     worker:
//       image: my-app
//       replicas: 3
//
// After Load:
//   components.web.role     => "service"  (from schema default)
//   components.web.replicas => 1          (from schema default)
//   components.worker.role  => "service"  (from schema default)
//   components.worker.replicas => 3       (from config.yaml, not overridden)
Dynamic schema selection

Use WithJSONSchemaSelector when the right schema depends on a value inside the config itself — the most common case being an apiVersion field. The selector is a callback that receives the merged values at Load time and returns the schema bytes to use:

cfg := synthra.MustNew(
    synthra.WithFile("manifest.yaml"),
    synthra.WithJSONSchemaSelector(func(values map[string]any) ([]byte, error) {
        version, ok := values["apiversion"].(string)
        if !ok || version == "" {
            return nil, errors.New("apiVersion is required")
        }
        return schemaRegistry.Get(version)  // your own lookup
    }),
)

The selector runs after sources are merged and before schema defaults, transforms, and validation — so the selected schema drives the whole pipeline exactly as if WithJSONSchema had been used.

WithJSONSchema and WithJSONSchemaSelector are mutually exclusive; using both in one New call is a construction-time error.

Transforms and interpolation

WithTransform registers a function that processes the merged configuration map after schema defaults and before validation. Multiple transforms run as a pipeline in registration order.

s := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithTransform(func(values map[string]any) (map[string]any, error) {
        if level, ok := values["log_level"].(string); ok {
            values["log_level"] = strings.ToLower(level)
        }
        return values, nil
    }),
    synthra.WithJSONSchema(schema), // sees the transformed values
)

WithInterpolation is a convenience transform that replaces {key} placeholders in all string values with entries from a provided map. Unmatched placeholders are left as-is.

s := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithJSONSchema(schema),
    synthra.WithInterpolation(map[string]string{
        "env":    "production",
        "region": "eu-west-1",
    }),
)
// If config.yaml has: envFile: ".env.{env}"
// After Load:         envFile => ".env.production"

Interpolation also works with patternProperties defaults. If the schema default for a field is ".env.{name}", the interpolation transform substitutes {name} after the default is applied.

Validation

Synthra supports three ways to validate, and you can combine them.

1. Validator interface on the bound struct

Add a Validate() error method on your struct. Synthra calls it after binding.

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, got %d", c.Port)
    }
    return nil
}
2. JSON Schema

Pass a schema as raw bytes. Synthra fills in "default" values, then validates the merged map before binding.

schema := []byte(`{
    "type": "object",
    "required": ["service", "port"],
    "properties": {
        "service": {"type": "string", "minLength": 1},
        "port":    {"type": "integer", "minimum": 1, "maximum": 65535, "default": 8080}
    }
}`)

s := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithJSONSchema(schema),
)

Synthra supports JSON Schema Draft 4, Draft 6, Draft 7, Draft 2019-09, and Draft 2020-12. See JSON Schema defaults for details on default application.

3. Custom validator function

Use WithValidator for cross-field rules or any logic that does not fit a schema.

synthra.WithValidator(func(m map[string]any) error {
    server, _ := m["server"].(map[string]any)
    tls, _ := server["tls"].(map[string]any)
    if enabled, _ := tls["enabled"].(bool); enabled {
        if tls["cert"] == nil || tls["key"] == nil {
            return errors.New("tls.cert and tls.key are required when tls.enabled is true")
        }
    }
    return nil
})

You can add more than one validator. Synthra runs them in order. The first error stops Load.

Reading values

After Load, you have several ways to read values.

Bound struct (preferred for typed code)

If you used WithBinding, just use the struct.

fmt.Println(cfg.Server.Host, cfg.Server.Port)
Strict typed methods

These return an error when the key is missing or the value cannot be converted.

port, err := s.Int("server.port")
host, err := s.String("server.host")
debug, err := s.Bool("debug")
rate, err := s.Float64("rate")
timeout, err := s.Duration("timeout")
when, err := s.Time("start_time")
tags, err := s.StringSlice("tags")
ports, err := s.IntSlice("ports")
meta, err := s.StringMap("metadata")

Use errors.Is(err, synthra.ErrKeyNotFound) to check for a missing key.

"Or" methods with a default

These never return an error. They return the default when the key is missing or cannot be converted.

host := s.StringOr("server.host", "localhost")
port := s.IntOr("server.port", 8080)
debug := s.BoolOr("debug", false)
timeout := s.DurationOr("timeout", 30*time.Second)
tags := s.StringSliceOr("tags", []string{"default"})

Other Or methods exist for Int64, Float64, Time, IntSlice, and StringMap. See the API docs for the full list.

Generic Get and GetOr

For type-safe access with one function, use the generic helpers:

port, err := synthra.Get[int](s, "server.port")
host := synthra.GetOr(s, "server.host", "localhost")

The type comes from the type parameter, or from the default value.

Raw access

Get(key) returns any and nil when the key is missing.

v := s.Get("server.port")  // any

Values() returns a pointer to a shallow copy of the merged map. Treat it as read-only.

all := s.Values() // *map[string]any

Merge order and precedence

Sources are merged in the order you add them. Later sources override earlier ones. Nested maps merge by key. Other values (strings, numbers, slices) are replaced as a whole.

synthra.MustNew(
    synthra.WithContent(defaults, codec.YAML),   // 1. baked-in defaults
    synthra.WithFile("config.yaml"),             // 2. file on disk
    synthra.WithFile("override.json"),           // 3. another file
    synthra.WithEnv("APP_"),                     // 4. environment (wins)
)

In this example, environment variables have the highest precedence.

Case insensitivity and dot notation

Synthra lowercases every key when it merges sources. Reads are also case-insensitive.

s.Int("server.port")  // works
s.Int("Server.Port")  // also works
s.Int("SERVER.PORT")  // also works

Keys use dot notation: server.port walks into server and reads port. A key with a real dot in its name (not used as a separator) is not supported. If you store such keys, read them through Values().

Environment variable naming

Given prefix APP_:

  1. The prefix is removed.
  2. The rest is lowercased.
  3. Underscores split into nested keys.
Variable Key
APP_PORT=8080 port
APP_SERVER_HOST=db server.host
APP_DATABASE_PRIMARY_HOST=db database.primary.host
APP_TAGS=a,b,c tags (string, splits to slice on read)

A field like server.read.timeout maps to APP_SERVER_READ_TIMEOUT when the prefix is APP_.

Dumping configuration

Synthra can write the merged configuration to a file. The format comes from the file extension, just like for sources.

s := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithEnv("APP_"),
    synthra.WithFileDumper("effective.yaml"),  // format from extension
)

s.Load(context.Background())
s.Dump(context.Background())  // writes effective.yaml

For an explicit format:

synthra.WithFileDumperAs("output", codec.JSON)

You can also write your own dumper by implementing the Dumper interface and passing it with WithDumper.

type Dumper interface {
    Dump(ctx context.Context, values *map[string]any) error
}

Testing helpers

The synthratest package provides helpers for tests.

import (
    "testing"

    "github.com/stretchr/testify/require"
    "gopherly.dev/synthra"
    "gopherly.dev/synthra/source"
    "gopherly.dev/synthra/synthratest"
)

func TestServer(t *testing.T) {
    cfg := synthratest.Load(t, map[string]any{
        "server": map[string]any{"port": 8080, "host": "127.0.0.1"},
    })

    port, err := cfg.Int("server.port")
    require.NoError(t, err)
    require.Equal(t, 8080, port)
}

Highlights:

  • synthratest.Config(t, opts...): build a *Synthra without calling Load.
  • synthratest.Load(t, map, opts...): build and load with a map source.
  • synthratest.LoadFile(t, format, content): write a temp file and load it.
  • synthratest.WriteFile(t, format, content): write a temp config file and return its path.
  • synthratest.Dumper: a recording dumper for tests.
  • synthratest.FuncCodec: a codec test double with function fields for Decode and Encode.
  • synthratest.ErrSource(err): a source that always returns the given error.
  • synthratest.AssertString, AssertInt, AssertBool, AssertStringSlice, AssertDumped: shortcut assertions.

Custom sources and codecs

Custom source

Implement Source:

type vaultSource struct {
    path string
}

func (s *vaultSource) Load(ctx context.Context) (map[string]any, error) {
    // fetch from your secret store
    return map[string]any{
        "db": map[string]any{
            "password": "from-vault",
        },
    }, nil
}

synthra.WithSource(&vaultSource{path: "secret/data/db"})
Custom codec

Implement codec.Codec (or codec.Decoder only if you do not need to dump):

type myCodec struct{}

func (myCodec) Decode(data []byte, v any) error { /* ... */ }
func (myCodec) Encode(v any) ([]byte, error)   { /* ... */ }

synthra.WithFileAs("config.custom", myCodec{})

Error handling

Synthra returns structured errors of type *ConfigError. They follow the shape of os.PathError:

type ConfigError struct {
    Op   string  // "new", "load", "dump", or "get"
    Path string  // diagnostic locator (source index, field, schema name, ...)
    Err  error   // the underlying cause
}

Use errors.As to read the operation:

if err := s.Load(ctx); err != nil {
    var ce *synthra.ConfigError
    if errors.As(err, &ce) {
        log.Error("load failed", "op", ce.Op, "path", ce.Path, "err", ce.Err)
    }
    return err
}

Use errors.Is for fixed reasons:

_, err := s.Int("server.port")
if errors.Is(err, synthra.ErrKeyNotFound) {
    return useDefaultPort()
}

Sentinel errors:

  • synthra.ErrNilConfig: a typed accessor was called on a nil *Synthra.
  • synthra.ErrKeyNotFound: the key is missing for a strict accessor.
  • synthra.ErrNilContext: Load or Dump got a nil context.

New can return a joined error when more than one option is invalid. Use errors.As on it the same way.

Thread safety

A *Synthra is safe for use by many goroutines:

  • Load can be called many times. The internal map is replaced atomically when loading succeeds.
  • All read methods (Get, String, Int, Values, ...) hold a read lock.
  • Dump reads a snapshot of the current values, so dumpers do not block reads.
  • The bound struct is not protected. If you re-load while another goroutine reads the struct, you need your own synchronization.

Examples

The examples/ folder has small, runnable programs. Each one has its own README and tests.

Folder Topic
basic YAML file and struct binding
environment Environment variables only
webapp YAML defaults plus WEBAPP_* overrides, binding, and Validate
formats JSON and TOML with explicit codecs
defaults Baked-in defaults, then file, then env
jsonschema JSON Schema validation
jsonschema-defaults JSON Schema defaults and WithInterpolation
customvalidator Cross-field check with WithValidator
dump Writing the merged state to a file
consul Optional Consul source for dev and prod
testing Using synthratest and source.NewMap

Run them all with:

go test ./examples/...

License

Synthra is released under the Apache License 2.0.

Contributing

Contributions are welcome. Please open an issue first to discuss larger changes before sending a pull request.

This project uses Nix for development. Run nix develop to enter the shell, then:

  • nix run .#lint to run the linter.
  • nix run .#test-unit to run unit tests.
  • nix run .#fmt-check to check formatting.

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)
  • JSON Schema defaults: "default" values declared in the schema are automatically applied to missing keys, including patternProperties
  • Dynamic schema selection (WithJSONSchemaSelector) for version-based or content-based schema routing at Load time
  • Post-load transforms (WithTransform) and string interpolation (WithInterpolation) run before validation
  • 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 (also applies "default" values automatically):

schema := []byte(`{
    "type": "object",
    "properties": {
        "port": {"type": "integer", "minimum": 1, "maximum": 65535, "default": 8080}
    },
    "required": ["port"]
}`)

cfg := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithJSONSchema(schema), // validates AND fills in "default" values
)
// If config.yaml omits "port", Load sets it to 8080 before validating.

Use WithJSONSchemaSelector when the schema to use depends on a value inside the config itself — for example an apiVersion field:

cfg := synthra.MustNew(
    synthra.WithFile("manifest.yaml"),
    synthra.WithJSONSchemaSelector(func(values map[string]any) ([]byte, error) {
        version, ok := values["apiversion"].(string)
        if !ok || version == "" {
            return nil, errors.New("apiVersion is required")
        }
        return schemaRegistry.Get(version)
    }),
)
// The selector is called at Load time with the merged values, so it can
// branch on any config value. The selected schema applies defaults and
// validates exactly like WithJSONSchema. WithJSONSchema and
// WithJSONSchemaSelector are mutually exclusive.

Transforms and Interpolation

WithTransform registers a function that processes the merged values after schema defaults and before validation. Multiple transforms run as a pipeline. WithInterpolation is a convenience transform that replaces {key} placeholders in string values with entries from a provided map:

cfg := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithJSONSchema(schema),
    synthra.WithInterpolation(map[string]string{
        "env":    "production",
        "region": "eu-west-1",
    }),
)
// If config.yaml has: envFile: ".env.{env}"
// After Load: cfg.Get("envFile") => ".env.production"

cfg := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithTransform(func(values map[string]any) (map[string]any, error) {
        if level, ok := values["log_level"].(string); ok {
            values["log_level"] = strings.ToLower(level)
        }
        return values, nil
    }),
    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/jsonschema-defaults — JSON Schema defaults and WithInterpolation
  • 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

Examples

Constants

View Source
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

View Source
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.

View Source
var ErrNilConfig = errors.New("synthra: nil Synthra")

ErrNilConfig is returned when a typed accessor or Get is used on a nil *Synthra.

View Source
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

func Get[T any](c *Synthra, key string) (T, error)

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

func GetOr[T any](c *Synthra, key string, defaultVal T) T

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

type ConfigError struct {
	Op   string
	Path string
	Err  error
}

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.

func (*ConfigError) Unwrap

func (e *ConfigError) Unwrap() error

Unwrap returns the underlying error for errors.Is and errors.As.

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

func WithBinding(v any) Option

WithBinding returns an Option that configures the Synthra instance to bind configuration data to a struct. The target must be a non-nil pointer.

Example:

type Config struct {
    Server struct {
        Host string `synthra:"host"`
        Port int    `synthra:"port"`
    } `synthra:"server"`
}

var appCfg Config
cfg := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithBinding(&appCfg),
)
fmt.Println(appCfg.Server.Port) // populated from config
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

func WithConsul(path string) Option

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

func WithConsulAs(path string, decoder codec.Decoder) Option

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

func WithContent(data []byte, decoder codec.Decoder) Option

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

func WithDumper(d Dumper) Option

WithDumper adds a custom Dumper to the configuration dumper. Use it to plug in dumpers not covered by the built-in options (e.g. a database, remote API, or custom file format). The dumper must not be nil.

Example:

cfg := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithDumper(myCustomDumper),
)

func WithEnv

func WithEnv(prefix string) Option

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

func WithFile(path string) Option

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

func WithFileAs(path string, decoder codec.Decoder) Option

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

func WithFileDumper(path string) Option

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

func WithFileDumperAs(path string, encoder codec.Encoder) Option

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

func WithFileFS(fsys fs.FS, path string) Option

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

func WithFileFSAs(fsys fs.FS, path string, decoder codec.Decoder) Option

WithFileFSAs returns an Option that loads configuration from path inside fsys using an explicit decoder. It combines WithFileFS (embedded filesystem) with WithFileAs (explicit decoder) for files that have no extension or need a format override.

Paths support environment variable expansion using ${VAR} or $VAR syntax. If fsys is nil, New returns a validation error.

Example:

//go:embed configs
var configFS embed.FS

cfg := synthra.MustNew(
    synthra.WithFileFSAs(configFS, "configs/app", codec.YAML),
)

func WithIf

func WithIf(condition bool, opts ...Option) Option

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 WithInterpolation added in v0.2.0

func WithInterpolation(vars map[string]string) Option

WithInterpolation registers a transform that replaces {key} placeholders in all string values with the corresponding value from vars. Placeholders for keys not present in vars are left unchanged.

Interpolation runs after JSON Schema defaults are applied and before JSON Schema validation, so the validated values reflect the substituted strings.

Example — substitute the environment name into file paths:

cfg := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithInterpolation(map[string]string{
        "name":   "production",
        "region": "eu-west-1",
    }),
    synthra.WithJSONSchema(schema),
)
// If config.yaml contains:
//   envFile: ".env.{name}"
//   cluster: "{region}-cluster"
// After Load:
//   cfg.Get("envFile") => ".env.production"
//   cfg.Get("cluster") => "eu-west-1-cluster"

func WithJSONSchema

func WithJSONSchema(schema []byte) Option

WithJSONSchema adds a JSON Schema for validation and automatic default application. Synthra supports JSON Schema drafts 4, 6, 7, 2019-09, and 2020-12.

Validation

The merged configuration map is validated against the schema during [Load], after schema defaults are applied and after any registered WithTransform functions have run. If validation fails, Load returns a *ConfigError with Op OpLoad and Path "json-schema".

Automatic defaults

Synthra also extracts every "default" value declared in the schema and applies it to any key that is missing from the loaded configuration. This happens before transforms and validation run, so the schema validator always sees a fully populated map.

Defaults are applied recursively at every level:

  • "properties" — fills missing fixed-name keys in an object
  • "patternProperties" — fills missing keys inside every existing map entry whose name matches the regular-expression pattern
  • "items" — fills missing keys inside each element of an array

User-provided values are never overridden; only absent keys are filled.

Example:

schema := []byte(`{
    "type": "object",
    "required": ["service"],
    "properties": {
        "service":   {"type": "string"},
        "port":      {"type": "integer", "default": 8080},
        "log_level": {"type": "string",  "default": "info",
                      "enum": ["debug","info","warn","error"]},
        "components": {
            "type": "object",
            "patternProperties": {
                "^[a-z0-9-]+$": {
                    "properties": {
                        "role":     {"type": "string",  "default": "service"},
                        "replicas": {"type": "integer", "default": 1}
                    }
                }
            }
        }
    }
}`)

cfg := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithJSONSchema(schema),
)
// If config.yaml contains only:
//   service: my-app
//   components:
//     web:
//       image: nginx
//
// After Load:
//   cfg.Get("port")                        => 8080      (schema default)
//   cfg.Get("log_level")                   => "info"    (schema default)
//   cfg.Get("components.web.role")         => "service" (patternProperties default)
//   cfg.Get("components.web.replicas")     => 1         (patternProperties default)

func WithJSONSchemaSelector added in v0.2.0

func WithJSONSchemaSelector(fn func(map[string]any) ([]byte, error)) Option

WithJSONSchemaSelector registers a lazy schema resolver that is called during Synthra.Load with the merged configuration values and returns the JSON Schema bytes to use for that load. This enables the schema to be chosen based on a value read from the config itself — for example an `apiVersion` field — without requiring a two-pass read.

The selector runs after all sources are merged and before schema defaults, transforms, and validation. The bytes it returns are compiled and the schema's "default" values are extracted, so the full pipeline (defaults → transforms → validation) applies exactly as if WithJSONSchema had been used.

WithJSONSchema and WithJSONSchemaSelector are mutually exclusive. Using both in the same New call is a construction-time error.

Errors returned by the selector abort [Load] with a *ConfigError whose Op is OpLoad and Path is "json-schema-selector". Schema bytes that fail to compile produce the same error shape.

Example — select schema version from the config's own apiVersion key:

cfg := synthra.MustNew(
    synthra.WithFile("deployah.yaml"),
    synthra.WithJSONSchemaSelector(func(values map[string]any) ([]byte, error) {
        version, ok := values["apiversion"].(string)
        if !ok || version == "" {
            return nil, errors.New("apiVersion is required")
        }
        return schema.GetManifestSchema(version)
    }),
)
err := cfg.Load(context.Background())

func WithSource

func WithSource(loader Source) Option

WithSource adds a custom Source to the configuration loader. Use it to plug in sources not covered by the built-in options (e.g. a database, remote API, or custom file format). The source must not be nil.

Example:

cfg := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithSource(myCustomSource),
)

func WithTag

func WithTag(tagName string) Option

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 WithTransform added in v0.2.0

func WithTransform(fn func(map[string]any) (map[string]any, error)) Option

WithTransform registers a function that transforms the merged configuration values during Load. Transforms run after JSON Schema defaults are applied and before JSON Schema validation, in the order they were registered. This means the schema validator sees the final, transformed values.

The function receives the current values map and must return the (possibly modified) values map. Returning a nil map is treated as an empty map. Returning an error aborts Load with a *ConfigError whose Path identifies the failing transform by its index ("transform[0]", "transform[1]", …).

Multiple transforms are applied as a pipeline: the output of transform N becomes the input of transform N+1.

Example — normalize log level to lowercase before validation:

cfg := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithTransform(func(values map[string]any) (map[string]any, error) {
        if level, ok := values["log_level"].(string); ok {
            values["log_level"] = strings.ToLower(level)
        }
        return values, nil
    }),
    synthra.WithJSONSchema(schema),
)

func WithValidator

func WithValidator(fn func(map[string]any) error) Option

WithValidator adds a custom validation function that runs against the merged configuration map after all sources are loaded. Multiple validators are executed in the order they are added; the first error stops evaluation. The function must not be nil.

Example:

cfg, err := synthra.New(
    synthra.WithFile("config.yaml"),
    synthra.WithValidator(func(m map[string]any) error {
        port, _ := m["port"].(int)
        if port < 1 || port > 65535 {
            return fmt.Errorf("port %d out of range", port)
        }
        return nil
    }),
)
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

func MustNew(opts ...Option) *Synthra

MustNew is like New but panics if validation fails. Use it in main() or package-level initialization where a panic is acceptable. For explicit error handling, use New instead.

Example:

cfg := synthra.MustNew(
    synthra.WithFile("config.yaml"),
    synthra.WithEnvPrefix("APP"),
    synthra.WithBinding(&appCfg),
)
fmt.Println(cfg.Get("server.port"))
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

func New(opts ...Option) (*Synthra, error)

New creates a new Synthra instance with the provided options. Options are applied in order to an internal config. Validation errors are collected and reported after all options are applied, so callers never receive a partially-initialized instance. A nil option is treated as a validation error.

Use MustNew in main() or initialization code where a panic on error is acceptable.

Example:

cfg, err := synthra.New(
    synthra.WithFile("config.yaml"),
    synthra.WithEnvPrefix("APP"),
    synthra.WithBinding(&appCfg),
)
if err != nil {
    log.Fatal(err)
}
fmt.Println(cfg.Get("server.port"))
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

func (c *Synthra) Bool(key string) (bool, error)

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

func (c *Synthra) BoolOr(key string, defaultVal bool) bool

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

func (c *Synthra) Dump(ctx context.Context) error

Dump writes the current configuration values to the registered dumpers.

Errors:

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

func (c *Synthra) Duration(key string) (time.Duration, error)

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

func (c *Synthra) DurationOr(key string, defaultVal time.Duration) time.Duration

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

func (c *Synthra) Float64(key string) (float64, error)

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

func (c *Synthra) Float64Or(key string, defaultVal float64) float64

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

func (c *Synthra) Get(key string) any

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

func (c *Synthra) Int(key string) (int, error)

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

func (c *Synthra) Int64(key string) (int64, error)

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

func (c *Synthra) Int64Or(key string, defaultVal int64) int64

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

func (c *Synthra) IntOr(key string, defaultVal int) int

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

func (c *Synthra) IntSlice(key string) ([]int, error)

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

func (c *Synthra) IntSliceOr(key string, defaultVal []int) []int

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

func (c *Synthra) Load(ctx context.Context) error

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.

The pipeline runs in this order:

  1. Load and merge all sources (later sources override earlier ones).
  2. If WithJSONSchemaSelector is set, call it with the merged values to obtain schema bytes; compile them and extract raw defaults.
  3. Apply JSON Schema defaults (WithJSONSchema or selector) to missing keys.
  4. Run transforms (WithTransform, WithInterpolation) in registration order.
  5. Validate merged values against the JSON Schema.
  6. Run custom validators (WithValidator).
  7. Decode into the bound struct (WithBinding), apply struct-tag defaults, and call the struct's Validate method if it implements Validator.

Errors:

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

func (c *Synthra) String(key string) (string, error)

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

func (c *Synthra) StringMap(key string) (map[string]any, error)

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

func (c *Synthra) StringMapOr(key string, defaultVal map[string]any) map[string]any

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

func (c *Synthra) StringOr(key, defaultVal string) string

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

func (c *Synthra) StringSlice(key string) ([]string, error)

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

func (c *Synthra) StringSliceOr(key string, defaultVal []string) []string

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

func (c *Synthra) Time(key string) (time.Time, error)

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

func (c *Synthra) TimeOr(key string, defaultVal time.Time) time.Time

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

func (c *Synthra) Values() *map[string]any

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.

type Validator

type Validator interface {
	Validate() error
}

Validator is an interface for structs that can validate their own configuration. The validation package uses the same contract (validation.Validator); a type implementing either satisfies both.

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.
jsonschema-defaults command
Package main demonstrates JSON Schema defaults and WithInterpolation.
Package main demonstrates JSON Schema defaults and WithInterpolation.
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.

Jump to

Keyboard shortcuts

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