conf

package module
v2.0.2 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2024 License: MIT Imports: 6 Imported by: 0

README

conf

GoDoc Build Status Go Report Card

Package conf is an extensible solution for cascading configuration. Package conf provides configuration processor that can load configuration layers from different sources and merges them into the one configuration tree. In addition configuration processor can expand references on configuration parameters in string values and process $ref and _include directives in resulting configuration tree. Package conf comes with built-in configuration loaders: fileconf and envconf, and can be extended by third-party configuration loaders. Package conf do not watch for configuration changes, but you can implement this feature in the custom configuration loader. You can find full example in repository.

See full documentation on GoDoc for more information.

Documentation

Overview

Package conf is an extensible solution for cascading configuration. Package conf provides configuration processor, that can load configuration layers from different sources and merges them into the one configuration tree. In addition configuration processor can expand references on configuration parameters in string values, and process $ref and _include directives in resulting configuration tree (see below). Package conf comes with built-in configuration loaders: fileconf and envconf, maploader and can be extended by third-party configuration loaders. Package conf do not watch for configuration changes, but you can implement this feature in the custom configuration loader. You can find full example in repository.

Configuration processor can expand references to configuration parameters in string values (if you need reference to complex structures, see $ref directive). For example, you have a YAML file:

myapp:
  mediaFormats: ["images", "audio", "video"]

  dirs:
    rootDir: "/myapp"
    templatesDir: "${myapp.dirs.rootDir}/templates"
    sessionsDir: "${myapp.dirs.rootDir}/sessions"

    mediaDirs:
      - "${myapp.dirs.rootDir}/media/${myapp.mediaFormats.0}"
      - "${myapp.dirs.rootDir}/media/${myapp.mediaFormats.1}"
      - "${myapp.dirs.rootDir}/media/${myapp.mediaFormats.2}"

After processing of the file you get a map:

"myapp": conf.M{
  "mediaFormats": conf.A{"images", "audio", "video"},

  "dirs": conf.M{
    "rootDir": "/myapp",
    "templatesDir": "/myapp/templates",
    "sessionsDir": "/myapp/sessions",

    "mediaDirs": conf.A{
      "/myapp/media/images",
      "/myapp/media/audio",
      "/myapp/media/video",
    },
  },
}

To escape expansion of references, add one more "$" symbol. For example:

templatesDir: "$${myapp.dirs.rootDir}/templates"

After processing we will get:

templatesDir: "${myapp.dirs.rootDir}/templates"

Package conf supports special directives in configuration layers: $ref and $include. $ref directive tries to get a value of a configuration parameter by his name. $ref directive can take three forms:

$ref: <name>
$ref: { name: <name>, default: <value> }
$ref: { firstDefined: [ <name1>, ... ], default: <value> }

In the first form $ref directive just try to get a value by name. In the second form $ref directive tries to get a value by name and if no value is found, uses default value. In the third form $ref directive tries to get a value of a first defined configuration parameter and, if no value is found, uses default value. Default value in second and third forms can be omitted. Below is an example of TOML file with $ref directives:

db:
  defaultOptions:
    serverPrepare: true
    expandArray: true
    errorLevel: 2

  connectors:
    stat:
      host: "stat.mydb.com"
      port: 1234
      dbname: "stat"
      username: "stat"
      password:
        $ref: {name: "MYAPP_DB_STAT_PASSWORD", default: "stat_pass"}
      options: {$ref: "db.defaultOptions"}

    metrics:
      host: "metrics.mydb.com"
      port: 1234
      dbname: "metrics"
      username: "metrics"
      password:
        $ref: {name: "MYAPP_DB_METRICS_PASSWORD", default: "metrics_pass"}
      options: {$ref: "db.defaultOptions"}

$include directive loads configuration layer from external sources and inserts it to configuration tree. $include directive accepts a list of configuration locators as argument.

db:
  defaultOptions:
    serverPrepare: true
    expandArray: true
    errorLevel: 2

  connectors: { $include: [ "file:connectors.yml" ] }

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Decode

func Decode(configRaw, config any) error

Decode method decodes raw configuration data into structure. Note that the conf tags defined in the struct type can indicate which fields the values are mapped to (see the example below). The decoder will make the following conversions:

  • bools to string (true = "1", false = "0")
  • numbers to string (base 10)
  • bools to int/uint (true = 1, false = 0)
  • strings to int/uint (base implied by prefix)
  • int to bool (true if value != 0)
  • string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. Anything else is an error)
  • empty array = empty map and vice versa
  • negative numbers to overflowed uint values (base 10)
  • slice of maps to a merged map
  • single values are converted to slices if required. Each element also can be converted. For example: "4" can become []int{4} if the target type is an int slice.
Example
type DBConfig struct {
	Host     string `conf:"server_host"`
	Port     int    `conf:"server_port"`
	DBName   string
	Username string
	Password string
}

configRaw := conf.M{
	"server_host": "stat.mydb.com",
	"server_port": 1234,
	"dbname":      "stat",
	"username":    "stat_writer",
	"password":    "some_pass",
}

var config DBConfig
conf.Decode(configRaw, &config)

fmt.Printf("%v", config)
Output:

{stat.mydb.com 1234 stat stat_writer some_pass}

Types

type A added in v2.0.1

type A = []any

A type is a convenient alias for a []any slice.

type Loader

type Loader interface {
	Load(*Locator) (any, error)
}

Loader is an interface for configuration loaders.

type Locator

type Locator struct {
	Loader string
	Value  string
}

Locator is used by configuration processor and loaders to load configuration layers.

func ParseLocator

func ParseLocator(locStr string) (*Locator, error)

ParseLocator method creates Locator instance from the string.

func (*Locator) String

func (l *Locator) String() string

String method convert Locator instance to the string.

type M

type M = map[string]any

M type is a convenient alias for a map[string]any map.

type Processor

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

Processor loads configuration layers from different sources and merges them into the one configuration tree. In addition configuration processor can expand references on configuration parameters in string values and process $ref and $include directives in resulting configuration tree. Processing can be disabled if not needed.

func NewProcessor

func NewProcessor(config ProcessorConfig) *Processor

NewProcessor method creates new configuration processor instance.

func (*Processor) Load

func (p *Processor) Load(locators ...any) (M, error)

Load method loads configuration tree using configuration locators. The merge priority of loaded configuration layers depends on the order of configuration locators. Layers loaded by rightmost locator have highest priority.

type ProcessorConfig

type ProcessorConfig struct {
	// Loaders specifies configuration loaders. Map keys reperesents names of
	// configuration loaders, that further can be used in configuration locators.
	Loaders map[string]Loader

	// DisableProcessing disables expansion of references and processing of
	// directives.
	DisableProcessing bool
}

ProcessorConfig is a structure with configuration parameters for configuration processor.

Directories

Path Synopsis
Package envconf is configuration loader for the conf package.
Package envconf is configuration loader for the conf package.
examples
basic command
Package fileconf is configuration loader for the conf package.
Package fileconf is configuration loader for the conf package.

Jump to

Keyboard shortcuts

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