config

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2017 License: MIT Imports: 18 Imported by: 229

README

🎣 config GoDoc GitHub release Build Status Coverage Status Report Card

Package config allows users to:

  • Get components working with minimal configuration
  • Override any field if the default doesn't make sense for their use case

Installation

We recommend locking to SemVer range ^1 using Glide:

glide get 'go.uber.org/config#^1

Stability

This library is v1 and follows SemVer strictly.

No breaking changes will be made to exported APIs before v2.0.0.

Documentation

Overview

Package config allows users to get components working with minimal configuration and override any field if the default doesn't make sense for their use case.

Index

Examples

Constants

View Source
const Root = ""

Root marks the root node in a Provider.

View Source
const Version = "1.1.0"

Version is the current version of config.

Variables

This section is empty.

Functions

This section is empty.

Types

type NopProvider

type NopProvider struct{}

NopProvider is an implementation of config provider that does nothing.

func (NopProvider) Get

func (p NopProvider) Get(key string) Value

Get returns an invalid Value.

func (NopProvider) Name

func (p NopProvider) Name() string

Name is NopProvider.

type Provider

type Provider interface {
	// the Name of the provider (YAML, Env, etc)
	Name() string
	// Get pulls a config value
	Get(key string) Value
}

A Provider provides a unified interface to accessing configuration systems.

func NewProviderGroup

func NewProviderGroup(name string, providers ...Provider) (Provider, error)

NewProviderGroup creates a configuration provider from a group of providers. The highest priority provider is the last. The merge strategy for two objects from the first provider(A) and the last provider(B) is following: If A and B are maps, A and B will form a new map with keys from A and B and values from B will overwrite values of A. e.g.

A:                B:                 merge(A, B):
  keep:A            new:B              keep:A
  update:fromA      update:fromB       update:fromB
                                       new:B

If A is a map and B is not, this function will return a Value with an error inside.

In all the remaining cases B will overwrite A.

Example
package main

import (
	"fmt"
	"log"

	"go.uber.org/config"
)

func main() {
	base, err := config.NewYAMLProviderFromBytes([]byte(`
config:
  name: fx
  pool: development
  ports:
  - 80
  - 8080
`))

	if err != nil {
		log.Fatal(err)
	}

	prod, err := config.NewYAMLProviderFromBytes([]byte(`
config:
  pool: production
  ports:
  - 443
`))

	if err != nil {
		log.Fatal(err)
	}

	// Provider is going to keep name from the base provider,
	// but ports and pool values will be overridden by prod.
	p, err := config.NewProviderGroup("merge", base, prod)
	if err != nil {
		log.Fatal(err)
	}

	var c struct {
		Name  string
		Pool  string
		Ports []uint
	}

	if err := p.Get("config").Populate(&c); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%+v\n", c)
}
Output:

{Name:fx Pool:production Ports:[443]}

func NewScopedProvider

func NewScopedProvider(prefix string, provider Provider) Provider

NewScopedProvider creates a child provider with a prefix.

func NewStaticProvider

func NewStaticProvider(data interface{}) (Provider, error)

NewStaticProvider returns a provider that wraps data and it's fields can be accessed via Get method. It is using the yaml marshaler to encode data first, and is subject to panic if data contains a fixed sized array.

func NewStaticProviderWithExpand

func NewStaticProviderWithExpand(
	data interface{},
	mapping func(string) (string, bool)) (Provider, error)

NewStaticProviderWithExpand returns a static provider with values replaced by a mapping function.

func NewYAMLProviderFromBytes

func NewYAMLProviderFromBytes(yamls ...[]byte) (Provider, error)

NewYAMLProviderFromBytes creates a config provider from a byte-backed YAML blobs. As above, all the objects are going to be merged and arrays/values overridden in the order of the yamls.

func NewYAMLProviderFromFiles

func NewYAMLProviderFromFiles(files ...string) (Provider, error)

NewYAMLProviderFromFiles creates a configuration provider from a set of YAML file names. All the objects are going to be merged and arrays/values overridden in the order of the files.

func NewYAMLProviderFromReader

func NewYAMLProviderFromReader(readers ...io.Reader) (Provider, error)

NewYAMLProviderFromReader creates a configuration provider from a list of io.Readers. As above, all the objects are going to be merged and arrays/values overridden in the order of the files.

func NewYAMLProviderFromReaderWithExpand

func NewYAMLProviderFromReaderWithExpand(
	mapping func(string) (string, bool),
	readers ...io.Reader) (Provider, error)

NewYAMLProviderFromReaderWithExpand creates a configuration provider from a list of `io.Readers and uses the mapping function to expand values in the underlying provider.

func NewYAMLProviderWithExpand

func NewYAMLProviderWithExpand(mapping func(string) (string, bool), files ...string) (Provider, error)

NewYAMLProviderWithExpand creates a configuration provider from a set of YAML file names with ${var} or $var values replaced based on the mapping function. Variable names not wrapped in curly braces will be parsed according to the shell variable naming rules:

...a word consisting solely of underscores, digits, and
alphabetics from the portable character set. The first
character of a name is not a digit.

For variables wrapped in braces, all characters between '{' and '}' will be passed to the expand function. e.g. "${foo:13}" will cause "foo:13" to be passed to the expand function. The sequence '$$' will be replaced by a literal '$'. All other sequences will be ignored for expansion purposes.

type Value

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

A Value holds the value of a configuration

func NewValue

func NewValue(
	provider Provider,
	key string,
	value interface{},
	found bool,
) Value

NewValue creates a configuration value from a provider and a set of parameters describing the key.

func (Value) Get

func (cv Value) Get(key string) Value

Get returns a value scoped in the current value.

func (Value) HasValue

func (cv Value) HasValue() bool

HasValue returns whether the configuration has a value that can be used.

func (Value) Populate

func (cv Value) Populate(target interface{}) error

Populate fills in an object from configuration.

Example
package main

import (
	"fmt"
	"log"

	"go.uber.org/config"
)

func main() {
	p, err := config.NewStaticProvider(map[string]interface{}{
		"example": map[string]interface{}{
			"name":    "uber",
			"founded": 2009,
		},
	})

	if err != nil {
		log.Fatal(err)
	}

	var c struct {
		Name    string
		Founded int
	}

	if err := p.Get("example").Populate(&c); err != nil {
		log.Fatal(err)
	}

	fmt.Println(c)
}
Output:

{uber 2009}
Example (Error)
package main

import (
	"fmt"
	"log"

	"go.uber.org/config"
)

func main() {
	p, err := config.NewYAMLProviderFromBytes([]byte(`
bool: notBool
`))

	if err != nil {
		log.Fatal(err)
	}

	var b bool
	fmt.Println(p.Get("bool").Populate(&b))
}
Output:

for key "bool": strconv.ParseBool: parsing "notBool": invalid syntax
Example (Slice)
package main

import (
	"fmt"
	"log"

	"go.uber.org/config"
)

func main() {
	p, err := config.NewYAMLProviderFromBytes([]byte(`
slice:
  - 1
  - 2
  - 3
`))

	if err != nil {
		log.Fatal(err)
	}

	var s []int
	if err := p.Get("slice").Populate(&s); err != nil {
		log.Fatal(err)
	}

	fmt.Println(s)
}
Output:

[1 2 3]

func (Value) Source

func (cv Value) Source() string

Source returns a configuration provider's name.

func (Value) String

func (cv Value) String() string

String prints out underlying value in Value with fmt.Sprint.

func (Value) Value

func (cv Value) Value() interface{}

Value returns the underlying configuration's value.

Example
package main

import (
	"fmt"
	"log"

	"github.com/spf13/cast"
	"go.uber.org/config"
)

func main() {
	p, err := config.NewStaticProvider(map[string]interface{}{
		"string": "example",
		"float":  "2.718281828",
		"int":    42,
		"bool":   true,
	})

	if err != nil {
		log.Fatal(err)
	}

	s := cast.ToString(p.Get("string").Value())
	fmt.Println(s)

	f := cast.ToString(p.Get("float").Value())
	fmt.Println(f)

	i := cast.ToInt(p.Get("int").Value())
	fmt.Println(i)

	b := cast.ToBool(p.Get("bool").Value())
	fmt.Println(b)
}
Output:

example
2.718281828
42
true
Example (Maps)
package main

import (
	"fmt"
	"log"

	"github.com/spf13/cast"
	"go.uber.org/config"
)

func main() {
	p, err := config.NewStaticProvider(map[string]interface{}{
		"struct": struct{ Car string }{Car: "Mazda"},
		"map":    map[string]int{"uno": 1},
	})

	if err != nil {
		log.Fatal(err)
	}

	s := cast.ToStringMap(p.Get("struct").Value())
	fmt.Println(s)

	m := cast.ToStringMap(p.Get("map").Value())
	fmt.Println(m)

}
Output:

map[car:Mazda]
map[uno:1]
Example (Slices)
package main

import (
	"fmt"
	"log"

	"github.com/spf13/cast"
	"go.uber.org/config"
)

func main() {
	p, err := config.NewStaticProvider(map[string]interface{}{
		"strings": []string{"one", "two", "three"},
		"ints":    []int{1, 2, 3},
	})

	if err != nil {
		log.Fatal(err)
	}

	s := cast.ToStringSlice(p.Get("strings").Value())
	fmt.Println(s)

	i := cast.ToSlice(p.Get("ints").Value())
	fmt.Println(i)

}
Output:

[one two three]
[1 2 3]

func (Value) WithDefault

func (cv Value) WithDefault(value interface{}) (Value, error)

WithDefault sets the default value that can be overridden by providers with a highger priority.

Example
package main

import (
	"fmt"
	"log"

	"go.uber.org/config"
)

func main() {
	p, err := config.NewYAMLProviderFromBytes([]byte(`
example:
  override: fromYAML
`))

	if err != nil {
		log.Fatal(err)
	}

	type example struct {
		Base     string
		Override string
	}

	d := example{Override: "default", Base: "default"}
	fmt.Printf("Default value:\n%+v\n", d)

	v, err := p.Get("example").WithDefault(d)
	if err != nil {
		log.Fatal(err)
	}

	if err := v.Populate(&d); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Populate:\n%+v\n", d)
}
Output:

Default value:
{Base:default Override:default}
Populate:
{Base:default Override:fromYAML}

Jump to

Keyboard shortcuts

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