ckoanf

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 3, 2024 License: MIT Imports: 15 Imported by: 1

README

ckoanf

Composable koanf

This package is a wrapper around koanf which allows for

  • Composition of config sources in a specific order through composition.
  • Defining initial values (for easy testing).
  • Validation of config values (e.g. using the ozzo-validation package).
  • Strict typing - config is stored in a strictly typed struct (no interface{} or any).

This package does not mess with any globals.

Usage

package main 

import (
    _ "embed"
    "github.com/gzuidhof/ckoanf"
)

// You define the struct equivalent of you config file to allow for strict typing
type AppConfig struct {
    Port int `koanf:"port"`
    Name string `koanf:"name"`
}

// The config type must have a `Validate` method.
// I recommend you use the `github.com/go-ozzo/ozzo-validation` package.
func (c AppConfig) Validate() error {
    if c.Port <= 0 {
        return fmt.Errorf("port must be positive, but was %d", c.Port)
    }
    return nil
}

// go:embed config.toml
var myEmbeddedConfigFile []byte

func InitConfig() *ckoanf.Config[*AppConfig]{
    configModel := &AppConfig{} // You can specify initial values in this struct (useful for testing!)
    c, err := ckoanf.Init(configModel
        ckoanf.WithSource(
            ckoanf.EmbeddedDefaults[*AppConfig](myEmbeddedConfigFile, ckoanf.FileTypeTOML), // Use the embedded file for default values.
            ckoanf.LocalFile[*AppConfig]("path/to/config.toml"),
            ckoanf.Env[*AppConfig]("MY_PREFIX_"), // Only loads env vars with this specific prefix
        ),
    )
    if err != nil {
        panic("error initializing config: " + err.Error())
    }
    // `c.K` can be used to access the Koanf instance, or you can use `c.Model()` to get the config model itself.
    return c
}

Defaults

  • A delimiter of . is used (as is the default for koanf).
  • Environment varialbes are mapped such that a double underscore (__) becomes delimiter ..

Non-Goals

For now this package does not support dynamic loading of additional configs.

Testing

Test coverage is between 90% and 100%, let's try to keep it there.

License

MIT.

Documentation

Overview

Package ckoanf implements a config manager that uses koanf as its backend, the c stands for composable.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config[C ConfigModel] struct {
	K *koanf.Koanf
	// contains filtered or unexported fields
}

Config is a config manager that uses koanf as its backend, with a few extra features such as * A source system allowing you to compose multiple sources into a single config. * Validation. * A fixed config model (which can be retrieved using `Model()`).

func Init

func Init[C ConfigModel](c C, opts ...Option[C]) (*Config[C], error)

Init creates a new config manager and loads the config from the given sources. This is equivalent to calling `New` and `Load` in sequence.

func New

func New[C ConfigModel](c C, opts ...Option[C]) (*Config[C], error)

New creates a new config manager. Note: this does not call `Load`. You may want to use `Init` instead.

func (*Config[C]) Load

func (mgr *Config[C]) Load(ctxs ...context.Context) error

Load the config from the given sources. Optionally takes a context to use for the load operation.

func (*Config[C]) Model

func (mgr *Config[C]) Model() C

Model returns the underlying model of the config manager.

func (*Config[C]) Set

func (mgr *Config[C]) Set(key string, value interface{}) error

Set changes a value in the config by path key. Note that this requires unmarshaling and is fairly expensive.

func (*Config[C]) Validate

func (mgr *Config[C]) Validate() error

Validate the config model by calling its `Validate` method.

type ConfigFileType

type ConfigFileType string

ConfigFileType represents the type of the config file.

const (
	FileTypeYAML ConfigFileType = "yaml"
	FileTypeTOML ConfigFileType = "toml"
	FileTypeJSON ConfigFileType = "json"
)

func (ConfigFileType) Parser

func (c ConfigFileType) Parser() koanf.Parser

Parser returns the parser for the config file type. Panics if the config file type is invalid (use `Valid()` first to check). nolint:ireturn,nolintlint // This is required to return this interface to be a valid Source.

func (ConfigFileType) String

func (c ConfigFileType) String() string

String returns the string representation of the config file type.

func (ConfigFileType) Valid

func (c ConfigFileType) Valid() error

Valid checks if the config file type is valid.

type ConfigModel

type ConfigModel interface {
	Validate() error
}

ConfigModel is the interface a config model must implement to be used with the config manager. We want to be able to validate the config model after it is unmarshalled from a config source.

type Option

type Option[C ConfigModel] func(*Config[C]) error

Option is a functional option that can be used to configure the config manager.

func WithSource

func WithSource[C ConfigModel](srcs ...SourceFunc[C]) Option[C]

WithSource adds one or more sources to the config manager.

The order of the sources is important, as the config will be loaded in the same order. Later sources will override values from earlier sources.

func WithValidation

func WithValidation[C ConfigModel](v bool) Option[C]

WithValidation enables or disables validation of the config.

type Source

type Source struct {
	Type SourceType
	Load func(context.Context, *koanf.Koanf) error
}

Source is a config source, which is something that can be loaded into a koanf config.

type SourceFunc

type SourceFunc[C ConfigModel] func(*Config[C]) (Source, error)

func EmbeddedDefaults

func EmbeddedDefaults[C ConfigModel](b []byte, filetype ConfigFileType) SourceFunc[C]

EmbeddedDefaults is a source that loads the config from an embedded config file.

func Env

func Env[C ConfigModel](prefix string) SourceFunc[C]

Env is a source that loads the config from environment variables.

Only environment variables with the given prefix will be loaded.

func LocalFile

func LocalFile[C ConfigModel](filepath string) SourceFunc[C]

LocalFile is a source that loads the config from a local file. The filetype is inferred from the file extension.

func OptionalSource

func OptionalSource[C ConfigModel](src SourceFunc[C], allowedErrors ...error) SourceFunc[C]

OptionalSource wraps a source and makes it optional to load. If initialization of the source fails it will still error.

If the source fails to load, but the error is allowed, the source will be skipped. If no allowed errors are provided, all errors are allowed.

func PFlags

func PFlags[C ConfigModel](flagset *pflag.FlagSet) SourceFunc[C]

PFlags is a source that loads the config from posix command line flags.

func Struct

func Struct[C ConfigModel](s ConfigModel) SourceFunc[C]

Struct is a source that loads the config from a struct.

type SourceType

type SourceType string
const (
	SourceTypeDefault   SourceType = "default"
	SourceTypeLocalFile SourceType = "file"
	SourceTypeEnv       SourceType = "env"
	SourceTypePFlag     SourceType = "pflag"
	SourceTypeStruct    SourceType = "struct"
)

func (SourceType) String

func (p SourceType) String() string

func (SourceType) Valid

func (p SourceType) Valid() error

Directories

Path Synopsis
source
urfavecli
Package urfavecli implements a koanf.Source that loads the config from urfave/cli/v3 flags.
Package urfavecli implements a koanf.Source that loads the config from urfave/cli/v3 flags.

Jump to

Keyboard shortcuts

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