config

package module
v0.0.0-...-942f5e1 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2022 License: MIT Imports: 11 Imported by: 1

README

Config GoDoc

Package config provides convenient access methods to configuration stored as JSON or YAML.

This is a fork of olebedev/config, which in turn is a fork of original version.

It has incompatibilities with the original(s), and quite an extended functionality.

TODO:

  • test ExtendBy_v2() (not tested yet, at all)
  • Serk support
  • provide extensive examples of use, suitable for copy-paste
  • write tests, and make them work

Documentation

Overview

Package config provides convenient access methods to configuration stored as JSON or YAML.

Let's start with a simple YAML file config.yml:

development:
  database:
    host: localhost
  users:
    - name: calvin
      password: yukon
    - name: hobbes
      password: tuna
production:
  database:
    host: 192.168.1.1

We can parse it using ParseYaml(), which will return a *Config instance on success:

    file, err := os.ReadFile("config.yml")
    if err != nil {
		panic(err)
    }
    yamlString := string(file)

    cfg, err := config.ParseYaml(yamlString)

An equivalent JSON configuration could be built using ParseJson():

cfg, err := config.ParseJson(jsonString)

From now, we can retrieve configuration values using a path in dotted notation:

// "localhost"
host, err := cfg.String("development.database.host")

// or...

// "192.168.1.1"
host, err := cfg.String("production.database.host")

Besides String(), other types can be fetched directly: Bool(), Float64(), Int(), Map() and List(). All these methods will return an error if the path doesn't exist, or the value doesn't match or can't be converted to the requested type.

A nested configuration can be fetched using Get(). Here we get a new *Config instance with a subset of the configuration:

cfg, err := cfg.GetNestedConfig("development")

Then the inner values are fetched relatively to the subset:

// "localhost"
host, err := cfg.String("database.host")

For lists, the dotted path must use an index to refer to a specific value. To retrieve the information from a user stored in the configuration above:

// map[string]interface{}{ ... }
user1, err := cfg.Map("development.users.0")
// map[string]interface{}{ ... }
user2, err := cfg.Map("development.users.1")

// or...

// "calvin"
name1, err := cfg.String("development.users.0.name")
// "hobbes"
name2, err := cfg.String("development.users.1.name")

JSON or YAML strings can be created calling the appropriate Render*() functions. Here's how we render a configuration like the one used in these examples:

cfg := map[string]interface{}{
    "development": map[string]interface{}{
        "database": map[string]interface{}{
            "host": "localhost",
        },
        "users": []interface{}{
            map[string]interface{}{
                "name":     "calvin",
                "password": "yukon",
            },
            map[string]interface{}{
                "name":     "hobbes",
                "password": "tuna",
            },
        },
    },
    "production": map[string]interface{}{
        "database": map[string]interface{}{
            "host": "192.168.1.1",
        },
    },
}

json, err := config.RenderJson(cfg)

// or...

yaml, err := config.RenderYaml(cfg)

This results in a configuration string to be stored in a file or database.

For more more convenience it can parse OS environment variables and command line arguments.

cfg, err := config.ParseYaml(yamlString)
cfg.Env()

// or

cfg.Flag()

We can also specify the order of parsing:

cfg.Env().Flag()

// or

cfg.Flag().Env()

In case of OS environment all existing at the moment of parsing keys will be scanned in OS environment, but in uppercase and the separator will be `_` instead of a `.`. If EnvPrefix() is used the given prefix will be used to lookup the environment variable, e.g PREFIX_FOO_BAR will set foo.bar. In case of flags separator will be `-`. In case of command line arguments possible to use regular dot notation syntax for all keys. For see existing keys we can run application with `-h`.

We can use unsafe method to get value:

// ""
cfg.UString("undefined.key")

// or with default value
unsafeValue := cfg.UString("undefined.key", "default value")

There is unsafe methods, like regular, but wuth prefix `U`.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RenderJson

func RenderJson(c interface{}) (string, error)

RenderJson renders a JSON configuration.

func RenderYaml

func RenderYaml(c interface{}) (string, error)

RenderYaml renders a YAML configuration.

Types

type Config

type Config struct {
	Root interface{}
	// contains filtered or unexported fields
}

Config represents a configuration with convenient access methods.

func Must

func Must(c *Config, err error) *Config

Must is a wrapper for parsing functions to be used during initialization. It panics on failure.

func ParseJson

func ParseJson(c string) (*Config, error)

ParseJson reads a JSON configuration from the given string.

func ParseJsonFile

func ParseJsonFile(filename string) (*Config, error)

ParseJsonFile reads a JSON configuration from the given filename.

func ParseYaml

func ParseYaml(c string) (*Config, error)

ParseYaml reads a YAML configuration from the given string.

func ParseYamlBytes

func ParseYamlBytes(c []byte) (*Config, error)

ParseYamlBytes reads a YAML configuration from the given []byte.

func ParseYamlFile

func ParseYamlFile(filename string) (*Config, error)

ParseYamlFile reads a YAML configuration from the given filename.

func (*Config) Args

func (c *Config) Args(args ...string) *Config

Args command line arguments, based on existing config keys.

func (*Config) Bool

func (c *Config) Bool(path string) (bool, error)

Bool returns a bool according to a dotted path.

func (*Config) Duration

func (c *Config) Duration(path string) (time.Duration, error)

Duration returns a time.Duration according to a dotted path.

func (*Config) Env

func (c *Config) Env() *Config

Fetch data from system env, based on existing config keys.

func (*Config) EnvPrefix

func (c *Config) EnvPrefix(prefix string) *Config

Fetch data from system env using prefix, based on existing config keys.

func (*Config) Error

func (c *Config) Error() error

Error return last error

func (*Config) ExtendBy

func (c *Config) ExtendBy(c2 *Config) (err error)

ExtendBy() extends current config with another config: i.e. all values from another config are added to the current config, and overwritten with new values if already present. It implements prototype-based inheritance. Note that if you extend with different structure you will get an error. See: `.Set()` method for details.

func (*Config) ExtendBy_v2

func (c *Config) ExtendBy_v2(c2 *Config) (err error)

ExtendBy() extends current config with another config: i.e. all values from another config are added to the current config, and overwritten with new values if already present. It implements prototype-based inheritance.

func (*Config) Flag

func (c *Config) Flag() *Config

Parse command line arguments, based on existing config keys.

func (*Config) Float64

func (c *Config) Float64(path string) (float64, error)

Float64 returns a float64 according to a dotted path.

func (*Config) GetNestedConfig

func (c *Config) GetNestedConfig(path string) (*Config, error)

returns a nested config according to a dotted path.

func (*Config) Int

func (c *Config) Int(path string) (int, error)

Int returns an int according to a dotted path.

func (*Config) List

func (c *Config) List(path string) ([]interface{}, error)

List returns a []interface{} according to a dotted path.

func (*Config) ListConfig

func (c *Config) ListConfig(path string) ([]*Config, error)

ListConfig returns a nested []*Config according to a dotted path.

func (*Config) ListDuration

func (c *Config) ListDuration(path string) ([]time.Duration, error)

ListDuration returns an []time.Duration according to a dotted path.

func (*Config) ListFloat64

func (c *Config) ListFloat64(path string) ([]float64, error)

ListFloat64 returns an []float64 according to a dotted path.

func (*Config) ListInt

func (c *Config) ListInt(path string) ([]int, error)

ListInt returns an []int according to a dotted path.

func (*Config) ListString

func (c *Config) ListString(path string) ([]string, error)

ListString returns an []string according to a dotted path.

func (*Config) Map

func (c *Config) Map(path string) (map[string]interface{}, error)

Map returns a map[string]interface{} according to a dotted path.

func (*Config) MapConfig

func (c *Config) MapConfig(path string) (map[string]*Config, error)

MapConfig returns a nested map[string]*Config according to a dotted path.

func (*Config) MapDuration

func (c *Config) MapDuration(path string) (map[string]time.Duration, error)

MapDuration returns a map[string]time.Duration according to a dotted path.

func (*Config) MapFloat64

func (c *Config) MapFloat64(path string) (map[string]float64, error)

MapFloat64 returns a map[string]float64 according to a dotted path.

func (*Config) MapInt

func (c *Config) MapInt(path string) (map[string]int, error)

MapInt returns a map[string]int according to a dotted path.

func (*Config) MapString

func (c *Config) MapString(path string) (map[string]string, error)

MapString returns a map[string]string according to a dotted path.

func (*Config) Set

func (c *Config) Set(path string, v interface{}) error

Sets a nested config according to a dotted path.

func (*Config) String

func (c *Config) String(path string) (string, error)

String returns a string according to a dotted path.

func (*Config) UBool

func (c *Config) UBool(path string, defaults ...bool) bool

UBool returns a bool according to a dotted path or default value or false.

func (*Config) UDuration

func (c *Config) UDuration(path string, defaults ...time.Duration) time.Duration

UDuration returns a time.Duration according to a dotted path or default or zero duration

func (*Config) UFloat64

func (c *Config) UFloat64(path string, defaults ...float64) float64

UFloat64 returns a float64 according to a dotted path or default value or 0.

func (*Config) UInt

func (c *Config) UInt(path string, defaults ...int) int

UInt returns an int according to a dotted path or default value or 0.

func (*Config) UList

func (c *Config) UList(path string, defaults ...[]interface{}) []interface{}

UList returns a []interface{} according to a dotted path or defaults or []interface{}.

func (*Config) UMap

func (c *Config) UMap(path string, defaults ...map[string]interface{}) map[string]interface{}

UMap returns a map[string]interface{} according to a dotted path or default or map[string]interface{}.

func (*Config) UString

func (c *Config) UString(path string, defaults ...string) string

UString returns a string according to a dotted path or default or "".

Jump to

Keyboard shortcuts

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