go_config_reader

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2022 License: Apache-2.0 Imports: 16 Imported by: 0

README

go-config-reader

Simple configuration reader and validator that accepts a variety of sources.

How to use

  1. Import the library
import (
        cf "github.com/randlabs/go-config-reader"
)
  1. Create a struct that defines your configuration settings and add the required JSON tags to it.
type ConfigurationSettings struct {
        Name         string  `json:"name"`
        IntegerValue int     `json:"integerValue"`
        FloatValue   float64 `json:"floatValue"`
}
  1. Define the variable that will hold your settings
settings := ConfigurationSettings{}
  1. Setup the configuration load options
opts := cf.Options{
        Source: "/tmp/settings.json"",
}
  1. And execute load
err := cf.Load(opts, &settings)
if err != nil {
        return err
}

Loader options

The Options struct accept several modifiers that affects the load operation:

Field Meaning
Source Specifies the configuration source. Optional.
Used mostly for testing or templating.
EnvironmentVariable The environment variable used to lookup for the source. If specified, the source is the value of the environment variable. For example, this code:
opts.EnvironmentVariable = "MYSETTINGS"
expects you define an environment variable like this:
MYSETTINGS=/tmp/settings.json
so the source will be: /tmp/settings.json
NOTE: Source has priority over this field.
CmdLineParameter
CmdLineParameterShort
Long and short command-line parameters that contains source. Set to an empty string to disable. For example, this code:
s := "settings"
opts.CmdLineParameter = &s
expects you run your app like this: yourapp --settings /tmp/settings.json
NOTE: EnvironmentVariable has priority over this field.
Callback Use a custom loader for the configuration settings. For example:
func (ctx context.Context, source string) (string, error) {
dat, err := os.ReadFile(source)
if err != nil {
return "", err
}
return string(dat), nil
}
Schema Specifies an optional JSON schema to use to validate the loaded configuration. See this page for details about the schema format.
ExtendedValidator Specifies a custom validator function. For example:
func (settings interface{}) error {
s := settings.(*ConfigurationSettings)
if s.IntegerValue < 0 {
return errors.New("invalid integer value")
}
s.IntegerValue *= 2 // You can also modify them at this stage
return nil
}
Context Optional context.Context object to use while loading the configuration.

The source

The library contains several predefined loaders to load configuration settings from different locations. They are:

  • A file path like /tmp/settings.json or in URL format file:///tmp/settings.json used to load the configuration settings from the specified file.

  • An http or https URL like https://configurations.company/network/myapp/settings.json.

  • An embedded data URL like data://{ "integerValue": 10, .... }. A JSON object like { "integerValue": 10, .... } will be also taken as a data URL.

  • A Hashicorp Vault URL using a custom scheme: vault://server-domain?token={access-token}&path={vault-path}
    In this case, the loader will try to reach the vault-path secret located at http://server-domain using the provided access-token.

    By default, all the keys are read and returned as a JSON object but you can additionally add the &key={key} query parameter in order to read the specified value.

    NOTES:
    1. {vault-path} usually starts with /secret or /secret/data for KV engines v1 and v2 respectively.
    2. Use vaults:// to access a server using the https protocol.

Variable expansion

When data is loaded from the provided source, a macro expansion routine is executed. The following macros are processed:

  • ${SRC:some-source}: The loader will attempt to load the data located at some-source and replace the macro with it. some-source must be in any of the supported source formats.

  • ${ENV:some-environment-variable}: The loader will replace the macro with the content of the environment variable named some-environment-variable.

You can also embed macros inside other macros, for example:

${SRC:vault://my-vault-server.network?token=${ENV:VAULT_ACCESS_TOKEN}&path=/secret/data/mysecret}

LICENSE

See LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrWrongFormat = errors.New("wrong format")

Functions

func Load added in v1.1.0

func Load(options Options, settings interface{}) error

Load settings from the specified source.

Types

type ExtendedValidator

type ExtendedValidator func(settings interface{}) error

ExtendedValidator is a function to call in order to do configuration validation not covered by this library.

type LoaderCallback

type LoaderCallback func(ctx context.Context, source string) (string, error)

LoaderCallback is a function to call that must return a valid configuration json when possible.

type Options added in v1.1.0

type Options struct {
	// Optional embedded source.
	Source string

	// Environment variable that contains source.
	EnvironmentVariable string

	// Long and short command-line parameters that contains source. Set to
	// empty to disable. Environment variable has preference.
	CmdLineParameter      *string
	CmdLineParameterShort *string

	// Use a custom loader for the configuration settings.
	Callback LoaderCallback

	// Specifies an optional json schema validator.
	Schema string

	// Specifies an extended settings validator callback.
	ExtendedValidator ExtendedValidator

	// Optional context to use while loading the configuration.
	Context context.Context
}

Options indicates configurable loader options.

type ValidationError

type ValidationError struct {
	Failures []ValidationErrorFailure
}

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap added in v1.1.0

func (*ValidationError) Unwrap() error

type ValidationErrorFailure

type ValidationErrorFailure struct {
	Location string
	Message  string
}

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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