cfg

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2019 License: MIT Imports: 9 Imported by: 2

README

cfg

GoDoc Build Status

Go package for app configuration. Supports chained configuration sources for multiple levels of defaults. Includes APIs for loading Linux style configuration files (name/value pairs) or INI files, map based properties, or easily create new configuration sources (e.g. load from database).

Supports monitoring configuration sources for changes, hot loading properties, and notifying listeners of changes.

Usage

config := &cfg.Config{}
defer config.Shutdown() // stops monitoring

// load file via filespec string, os.File
src, err := Config.NewSrcFileFromFilespec("./myfile.conf")
if err != nil {
    return err
}
// add src to top of chain, meaning first searched
cfg.PrependSource(src)

// fetch prop 'retries', default to 3 if not found
val := config.Int("retries", 3)

See example for more complete example, including listening for configuration changes.

Config API parses the following data types:

type method example property values
string Config.String test, ""
int Config.Int -1, 77, 0
int64 Config.Int64 -9223372036854775, 372036854775808
float64 Config.Float64 -77.3456, 95642331.1
bool Config.Bool T,t,true,True,1,0,False,false,f,F
time.Duration Config.Duration "10ms", "2 hours", "5 min" *

* Units of measure supported: ms, sec, min, hour, day, week, year.

Documentation

Overview

Example
package main

import (
	"fmt"
	"math/rand"
	"strconv"
	"time"

	"github.com/wiggin77/cfg"
)

func sampleMap() map[string]string {
	return map[string]string{
		"fps":        "30",
		"retryDelay": "1 minute",
		"logRotate":  "1 day",
		"ratio":      "1.85",
	}
}

type listener struct {
	// empty
}

func (l *listener) ConfigChanged(cfg *cfg.Config, src cfg.SourceMonitored) {
	fmt.Println("Config changed!")
}

func main() {
	// create a Config instance
	config := &cfg.Config{}
	// shutdown will stop monitoring the sources for changes
	defer config.Shutdown()

	// for this sample use a source backed by a simple map
	m := sampleMap()
	src := cfg.NewSrcMapFromMap(m)

	// add the source to the end of the searched sources
	config.AppendSource(src)

	// add a source to the beginning of the searched sources,
	// providing defaults for missing properties.
	config.PrependSource(cfg.NewSrcMapFromMap(map[string]string{"maxRetries": "10"}))

	// listen for changes (why not use a func type here intead of interface? Because we
	// need to be able to remove listeners and cannot do that with funcs).
	config.AddChangedListener(&listener{})

	// change a property every 1 seconds for 5 seconds.
	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()
	done := time.After(5 * time.Second)
	rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
	for {
		select {
		case <-ticker.C:
			m["fps"] = strconv.Itoa(rnd.Intn(30))
		case <-done:
			return
		}
	}
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound returned when an operation is attempted on a resource that doesn't exist, such as fetching a non-existing property name.

Functions

This section is empty.

Types

type AbstractSourceMonitor added in v1.0.2

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

AbstractSourceMonitor can be embedded in a custom `Source` to provide the basic plumbing for monitor frequency.

func (*AbstractSourceMonitor) GetMonitorFreq added in v1.0.2

func (asm *AbstractSourceMonitor) GetMonitorFreq() (freq time.Duration)

GetMonitorFreq returns the frequency as a `time.Duration` between checks for changes to this config source.

func (*AbstractSourceMonitor) SetMonitorFreq added in v1.0.2

func (asm *AbstractSourceMonitor) SetMonitorFreq(freq time.Duration)

SetMonitorFreq sets the frequency between checks for changes to this config source.

type ChangedListener

type ChangedListener interface {

	// Changed is called when one or more properties in a `SourceMonitored` has a
	// changed value.
	ConfigChanged(cfg *Config, src SourceMonitored)
}

ChangedListener interface is for receiving notifications when one or more properties within monitored config sources (SourceMonitored) have changed values.

type Config

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

Config provides methods for retrieving property values from one or more configuration sources.

func (*Config) AddChangedListener

func (config *Config) AddChangedListener(l ChangedListener)

AddChangedListener adds a listener that will receive notifications whenever one or more property values change within the config.

func (*Config) AppendSource

func (config *Config) AppendSource(srcs ...Source)

AppendSource appends one or more `Sources` at the end of the list of sources such that the last source will be the source checked last when resolving a property value.

func (*Config) Bool

func (config *Config) Bool(name string, def bool) (val bool, err error)

Bool returns the value of the named prop as a `bool`. If the property is not found then the supplied default `def` and `ErrNotFound` are returned.

Supports (t, true, 1, y, yes) for true, and (f, false, 0, n, no) for false, all case-insensitive.

See config.String

func (*Config) Duration

func (config *Config) Duration(name string, def time.Duration) (val time.Duration, err error)

Duration returns the value of the named prop as a `time.Duration`, representing a span of time.

Units of measure are supported: ms, sec, min, hour, day, week, year. See config.UnitsToMillis for a complete list of units supported.

If the property is not found then the supplied default `def` and `ErrNotFound` are returned.

See config.String

func (*Config) Float64

func (config *Config) Float64(name string, def float64) (val float64, err error)

Float64 returns the value of the named prop as a `float64`. If the property is not found then the supplied default `def` and `ErrNotFound` are returned.

See config.String

func (*Config) Int

func (config *Config) Int(name string, def int) (val int, err error)

Int returns the value of the named prop as an `int`. If the property is not found then the supplied default `def` and `ErrNotFound` are returned.

See config.String

func (*Config) Int64

func (config *Config) Int64(name string, def int64) (val int64, err error)

Int64 returns the value of the named prop as an `int64`. If the property is not found then the supplied default `def` and `ErrNotFound` are returned.

See config.String

func (*Config) PrependSource

func (config *Config) PrependSource(srcs ...Source)

PrependSource inserts one or more `Sources` at the beginning of the list of sources such that the first source will be the source checked first when resolving a property value.

func (*Config) RemoveChangedListener

func (config *Config) RemoveChangedListener(l ChangedListener) error

RemoveChangedListener removes all instances of a ChangedListener. Returns `ErrNotFound` if the listener was not present.

func (*Config) SetWantPanicOnError added in v1.0.2

func (config *Config) SetWantPanicOnError(b bool)

SetWantPanicOnError sets the flag determining if Config should panic when `GetProps` or `GetLastModified` errors for a `Source`.

func (*Config) ShouldPanicOnError added in v1.0.2

func (config *Config) ShouldPanicOnError() (b bool)

ShouldPanicOnError gets the flag determining if Config should panic when `GetProps` or `GetLastModified` errors for a `Source`.

func (*Config) Shutdown

func (config *Config) Shutdown()

Shutdown can be called to stop monitoring of all config sources.

func (*Config) String

func (config *Config) String(name string, def string) (val string, err error)

String returns the value of the named prop as a string. If the property is not found then the supplied default `def` and `ErrNotFound` are returned.

type Source

type Source interface {

	// GetProps fetches all the properties from a source and returns
	// them as a map.
	GetProps() (map[string]string, error)
}

Source is the interface required for any source of name/value pairs.

type SourceMonitored

type SourceMonitored interface {
	Source

	// GetLastModified returns the time of the latest modification to any
	// property value within the source. If a source does not support
	// modifying properties at runtime then the zero value for `Time`
	// should be returned to ensure reload events are not generated.
	GetLastModified() (time.Time, error)

	// GetMonitorFreq returns the frequency as a `time.Duration` between
	// checks for changes to this config source.
	//
	// Returning zero (or less) will temporarily suspend calls to `GetLastModified`
	// and `GetMonitorFreq` will be called every 10 seconds until resumed, after which
	// `GetMontitorFreq` will be called at a frequency roughly equal to the `time.Duration`
	// returned.
	GetMonitorFreq() time.Duration
}

SourceMonitored is the interface required for any config source that is monitored for changes.

type SrcFile added in v1.0.2

type SrcFile struct {
	AbstractSourceMonitor
	// contains filtered or unexported fields
}

SrcFile is a configuration `Source` backed by a file containing name/value pairs or INI format.

func NewSrcFile added in v1.0.2

func NewSrcFile(file *os.File) (*SrcFile, error)

NewSrcFile creates a new SrcFile with the specified os.File.

func NewSrcFileFromFilespec added in v1.0.2

func NewSrcFileFromFilespec(filespec string) (*SrcFile, error)

NewSrcFileFromFilespec creates a new SrcFile with the specified filespec.

func (*SrcFile) GetLastModified added in v1.0.2

func (sf *SrcFile) GetLastModified() (time.Time, error)

GetLastModified returns the time of the latest modification to any property value within the source.

func (*SrcFile) GetProps added in v1.0.2

func (sf *SrcFile) GetProps() (map[string]string, error)

GetProps fetches all the properties from a source and returns them as a map.

type SrcMap

type SrcMap struct {
	AbstractSourceMonitor
	// contains filtered or unexported fields
}

SrcMap is a configuration `Source` backed by a simple map.

func NewSrcMap

func NewSrcMap() *SrcMap

NewSrcMap creates an empty `SrcMap`.

func NewSrcMapFromMap

func NewSrcMapFromMap(mapIn map[string]string) *SrcMap

NewSrcMapFromMap creates a `SrcMap` containing a copy of the specified map.

func (*SrcMap) GetLastModified

func (sm *SrcMap) GetLastModified() (last time.Time, err error)

GetLastModified returns the time of the latest modification to any property value within the source. If a source does not support modifying properties at runtime then the zero value for `Time` should be returned to ensure reload events are not generated.

func (*SrcMap) GetMonitorFreq

func (sm *SrcMap) GetMonitorFreq() (freq time.Duration)

GetMonitorFreq returns the frequency as a `time.Duration` between checks for changes to this config source. Defaults to 1 minute unless changed with `SetMonitorFreq`.

func (*SrcMap) GetProps added in v1.0.2

func (sm *SrcMap) GetProps() (m map[string]string, err error)

GetProps fetches all the properties from a source and returns them as a map.

func (*SrcMap) Put

func (sm *SrcMap) Put(key string, val string)

Put inserts or updates a value in the `SrcMap`.

func (*SrcMap) PutAll

func (sm *SrcMap) PutAll(mapIn map[string]string)

PutAll inserts a copy of `mapIn` into the `SrcMap`

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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