confiq

package module
v1.3.3 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2024 License: MIT Imports: 11 Imported by: 0

README

godoc for greencoda/confiq Go 1.22 Build Status Go Coverage Go Report card

confiq

confiq is a Go package for populating structs or arrays from structured data formats such JSON, TOML, YAML or Env, by using struct tags to map the loaded values to fields, using a selector path syntax which can traverse maps by keys and arrays by their indices.

The data can be loaded either from files, strings, byte arrays, readers and in case of environment variable formats from the actual environment.

Install

go get -u github.com/greencoda/confiq

Example

Provide the configuration data in a supported format:

config.json

{
    "serverHost": "http://localhost",
    "port": 8000,
    "settings": {
        "readOnlyMode": true,
        "maxConnections": 10,
        "disallowedUsernames": ["badUser1", "badUser2"]
    },
    "apiKeys": [
        "testKey1",
        "testKey2"
    ]
}

Create a new configSet using confiq.New and load the data with the appropriate Load method, depending on how you'd like to provide it. In this example we're loading it from the file system:

configSet := confiq.New()

if err := configSet.Load(
    confiqjson.Load().FromFile("./config.json"),
); err != nil {
    log.Fatal(err)
}

Define the config struct and provide the mappings in its struct tags for each field.

You may define certain fields to be required, or to have a default value if it isn't (these are mutually exclusive), or mark certain fields as strict which would cause the entire decoding process to fail if the value can not be set from the provided config data.

type Config struct {
	ServerHost          *url.URL `cfg:"serverHost,required"`
	ServerPort          string   `cfg:"port"`
	AllowedUsernames    []string `cfg:"settings.allowedUsernames,default=root;admin;developer"`
	DisallowedUsernames []string `cfg:"settings.disallowedUsernames"`
	ReadOnlyMode        bool     `cfg:"settings.readOnlyMode"`
	MaxConnections      int      `cfg:"settings.maxConnections"`
	ClientID            string   `cfg:"settings.clientId,default=defaultClient"`
	APIKey              string   `cfg:"apiKeys[1]"`
}

var config Config

Then decode the data to this struct from the loaded config data using Decode:

if err := configSet.Decode(&config); err != nil {
   // ...
}

You may also use confiq.AsStrict() option to have all fields act as if they were strict:

if err := configSet.Decode(&config, confiq.AsStrict()); err != nil {
   // ...
}

The result will be an instance of the struct loaded with data from the specified addresses of the config file:

(main.Config) {
 ServerHost: (*url.URL)(0xc0000e2090)(http://localhost),
 ServerPort: (string) (len=4) "8000",
 AllowedUsernames: ([]string) (len=3 cap=3) {
  (string) (len=4) "root",
  (string) (len=5) "admin",
  (string) (len=9) "developer"
 },
 DisallowedUsernames: ([]string) (len=2 cap=2) {
  (string) (len=8) "badUser1",
  (string) (len=8) "badUser2"
 },
 ReadOnlyMode: (bool) true,
 MaxConnections: (int) 10,
 ClientID: (string) (len=13) "defaultClient",
 APIKey: (string) (len=8) "testKey2"
}

Supported types:

confiq supports recursively decoding values into structs with exported fields, maps and slices.

Structs
  • structs with exported fields of other supported types
Maps
  • maps with primitive types for keys, and other supported types for values
Slices
  • slices of other supported types
  • strings will be split up at semicolons, and attempted to be decoded as slices of other supported types
Primitives
  • string
  • int, int8, int16, int32, int64
  • uint, uint8, uint16, uint32, uint64
  • float32, float64
  • bool
Other common types
  • json.RawMessage
  • net.IP
  • time.Duration
  • time.Time
  • *url.URL
Custom types
  • structs implementing the Decoder interface
  • types implementing the encoding.TextUnmarshaler interface
Pointers
  • pointers to supported types are also supported

Defining decoders for custom structs

For fields with custom struct types, you may implement the Decoder interface by specifying a Decode method to your type:

type customType struct {
	Value string
}

func (t *customType) Decode(value any) error {
	if stringValue, ok := value.(string); !ok {
		return errors.New("value is not a string")
	} else {
		t.Value = stringValue

		return nil
	}
}

Documentation

Overview

Package confiq is a Go package for populating structs from structured data formats such JSON, TOML, YAML or Env.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidTarget        = errors.New("target must be non-nil pointer to a slice, map or struct that has at least one exported field with a the configured tag")
	ErrNoTargetFieldsAreSet = errors.New("none of the target fields were set from config values")
)

Collection of decode errors.

View Source
var (
	ErrCannotOpenConfig = errors.New("cannot open config")
	ErrCannotLoadConfig = errors.New("cannot load config")
)

Collection of loader errors.

Functions

func AsStrict added in v1.3.0

func AsStrict() decodeOption

AsStrict sets the decoder to decode the configuration values as if all fields are set to strict.

func FromPrefix added in v1.3.0

func FromPrefix(prefix string) decodeOption

FromPrefix sets the prefix to be used when decoding configuration values into the target struct.

func WithPrefix

func WithPrefix(prefix string) loadOption

WithPrefix sets the prefix to be used when loading configuration values into the ConfigSet.

func WithTag

func WithTag(tag string) configSetOption

WithTag sets the struct tag to be used by the decoder for reading configuration values of struct fields.

Types

type ConfigSet

type ConfigSet struct {
	// contains filtered or unexported fields
}

ConfigSet is a configuration set that can be used to load and decode configuration values into a struct.

func New

func New(options ...configSetOption) *ConfigSet

New creates a new ConfigSet with the given options.

func (*ConfigSet) Decode

func (c *ConfigSet) Decode(target interface{}, options ...decodeOption) error

Decode decodes the configuration values into the target struct.

func (*ConfigSet) Get

func (c *ConfigSet) Get(path string) (any, error)

Get returns the configuration value at the given path as an interface.

func (*ConfigSet) Load added in v1.2.0

func (c *ConfigSet) Load(valueContainer IValueContainer, options ...loadOption) error

func (*ConfigSet) LoadRawValue

func (c *ConfigSet) LoadRawValue(newValues []any, options ...loadOption) error

LoadRawValue loads a raw value into the config set. The value must be a map[string]any or a slice of any.

type ConfigSetOptions added in v1.3.1

type ConfigSetOptions []loadOption

ConfigSetOptions is exposed so that functions which wrap the New function can make adding the WithTag option easier.

type DecodeOptions added in v1.3.1

type DecodeOptions []decodeOption

DecodeOptions is exposed so that functions which wrap the Decode function can make adding the AsStrict and FromPrefix options easier.

type Decoder

type Decoder interface {
	Decode(value any) error
}

type IValueContainer added in v1.2.0

type IValueContainer interface {
	Get() []any
	Errors() []error
}

type LoadOptions added in v1.3.1

type LoadOptions []loadOption

LoadOptions is exposed so that functions which wrap the Load function can make adding the WithPrefix option easier.

Directories

Path Synopsis
_examples
loaders
env
Package confiqenv allows confiq values to be loaded from Env format.
Package confiqenv allows confiq values to be loaded from Env format.
json
Package confiqjson allows confiq values to be loaded from JSON format.
Package confiqjson allows confiq values to be loaded from JSON format.
toml
Package confiqtoml allows confiq values to be loaded from TOML format.
Package confiqtoml allows confiq values to be loaded from TOML format.
yaml
Package confiqyaml allows confiq values to be loaded from YAML format.
Package confiqyaml allows confiq values to be loaded from YAML format.

Jump to

Keyboard shortcuts

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