Documentation ¶
Overview ¶
Package config provides tools to retrieve configuration from various sources and present it to the application through a unified API.
Index ¶
- Variables
- type Alias
- type Config
- func (c *Config) Append(g Getter)
- func (c *Config) Close() error
- func (c *Config) Get(key string, opts ...ValueOption) (Value, error)
- func (c *Config) GetConfig(node string, options ...Option) *Config
- func (c *Config) Insert(g Getter)
- func (c *Config) MustGet(key string, opts ...ValueOption) Value
- func (c *Config) NewKeyWatcher(key string, opts ...ValueOption) *KeyWatcher
- func (c *Config) NewWatcher() *Watcher
- func (c *Config) Unmarshal(node string, obj interface{}) (rerr error)
- func (c *Config) UnmarshalToMap(node string, objmap map[string]interface{}) (rerr error)
- type Decorator
- func WithAlias(a *Alias) Decorator
- func WithFallback(d Getter) Decorator
- func WithGraft(prefix string) Decorator
- func WithKeyReplacer(r keys.Replacer) Decorator
- func WithPrefix(prefix string) Decorator
- func WithRegexAlias(r *RegexAlias) Decorator
- func WithTrace(t TraceFunc) Decorator
- func WithUpdateHandler(handler UpdateHandler) Decorator
- type DefaultOption
- type DefaultValueOption
- type ErrorHandler
- type ErrorHandlerOption
- type GetErrorHandlerOption
- type Getter
- type GetterAsOption
- type GetterUpdate
- type GetterWatcher
- type KeyWatcher
- type NotFoundError
- type Notifier
- type Option
- type RegexAlias
- type SeparatorOption
- type Stack
- type TagOption
- type TraceFunc
- type UnmarshalError
- type UpdateCommit
- type UpdateHandler
- type Value
- func (v Value) Bool() bool
- func (v Value) Duration() time.Duration
- func (v Value) Float() float64
- func (v Value) Int() int
- func (v Value) Int64() int64
- func (v Value) Int64Slice() []int64
- func (v Value) IntSlice() []int
- func (v Value) Slice() []interface{}
- func (v Value) String() string
- func (v Value) StringSlice() []string
- func (v Value) Time() time.Time
- func (v Value) Uint() uint
- func (v Value) Uint64() uint64
- func (v Value) Uint64Slice() []uint64
- func (v Value) UintSlice() []uint
- func (v Value) Value() interface{}
- type ValueErrorHandlerOption
- type ValueOption
- type WatchableGetter
- type Watcher
Constants ¶
This section is empty.
Variables ¶
var ( // ErrCanceled indicates the Watch has been canceled. ErrCanceled = errors.New("config: canceled") // ErrClosed indicates the Config has been closed. ErrClosed = errors.New("config: closed") // ErrInvalidStruct indicates Unmarshal was provided an object to populate // which is not a pointer to struct. ErrInvalidStruct = errors.New("unmarshal: provided obj is not pointer to struct") )
var WithMust = ErrorHandlerOption{func(err error) error { panic(err) }}
WithMust makes an object panic on error. For Config this applies to Get and is propagated to returned Values. For Value this applies to all type conversions.
var WithMustGet = func(g Getter) Getter {
return mustDecorator{getterDecorator{g}}
}
WithMustGet provides a Decorator that panics if a key is not found by the decorated Getter.
var WithZeroDefaults = ErrorHandlerOption{func(err error) error { return nil }}
WithZeroDefaults makes an object ignore errors and instead return zeroed default values. For Config this applies to Get and is propagated to returned Values. For Value this applies to all type conversions.
Functions ¶
This section is empty.
Types ¶
type Alias ¶
type Alias struct {
// contains filtered or unexported fields
}
Alias provides a mapping from a key to a set of old or alternate keys.
func (*Alias) Append ¶
Append adds an alias from the new key to the old. If aliases already exist for the new key then this appended to the end of the existing list.
func (*Alias) Insert ¶
Insert adds an alias from the new key to the old. If aliases already exist for the new key then this inserted to the beginning of the existing list.
func (Alias) NewWatcher ¶
func (g Alias) NewWatcher(done <-chan struct{}) GetterWatcher
NewWatcher implements the WatchableGetter interface.
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Config is a wrapper around a Getter that provides a set of conversion functions that return the requested type, if possible, or an error if not.
func (*Config) Append ¶ added in v0.2.0
Append adds a getter to the end of the list of getters searched by the config, but still before a default getter specified by WithDefault. This function is not safe to call from multiple goroutines, and should only be called to set up configuration in a single goroutine before passing the final config to other goroutines.
func (*Config) Close ¶
Close releases any resources allocated to the Config including cancelling any actve watches.
func (*Config) Get ¶
func (c *Config) Get(key string, opts ...ValueOption) (Value, error)
Get gets the raw value corresponding to the key. Returns a zero Value and an error if the value cannot be retrieved.
func (*Config) GetConfig ¶
GetConfig gets the Config corresponding to a subtree of the config, where the node identifies the root node of the config returned.
func (*Config) Insert ¶ added in v0.2.0
Insert adds a getter to the beginning of the list of getters searched by the config. This function is not safe to call from multiple goroutines, and should only be called to set up configuration in a single goroutine before passing the final config to other goroutines.
func (*Config) MustGet ¶
func (c *Config) MustGet(key string, opts ...ValueOption) Value
MustGet gets the value corresponding to the key, or panics if the key is not found. This is a convenience wrapper that allows chaining of calls to value conversions when the application is certain the config field will be present.
func (*Config) NewKeyWatcher ¶
func (c *Config) NewKeyWatcher(key string, opts ...ValueOption) *KeyWatcher
NewKeyWatcher creates a watch on the given key. The key should correspond to a field, not a node.
func (*Config) NewWatcher ¶
NewWatcher creates a watch on the whole configuration.
func (*Config) Unmarshal ¶
Unmarshal a section of the config tree into a struct.
The node identifies the section of the tree to unmarshal. The obj is a pointer to a struct with fields corresponding to config values. The config values will be converted to the type defined in the corresponding struct fields. Overflow checks are performed during conversion to ensure the value returned by the getter can fit within the designated field.
By default the config field names are drawn from the struct field, converted to LowerCamelCase (as per typical JSON naming conventions). This can be overridden using `config:"<name>"` tags.
Struct fields which do not have corresponding config fields are ignored, as are config fields which have no corresponding struct field.
The error identifies the first type conversion error, if any.
func (*Config) UnmarshalToMap ¶
UnmarshalToMap unmarshals a section of the config tree into a map[string]interface{}.
The node identifies the section of the tree to unmarshal. The objmap keys define the fields to be populated from config. If non-nil, the config values will be converted to the type already contained in the map. If nil then the value is set to the raw value returned by the Getter.
Nested objects can be populated by adding them as map[string]interface{}, with keys set corresponding to the nested field names.
Map keys which do not have corresponding config fields are ignored, as are config fields which have no corresponding map key.
The error identifies the first type conversion error, if any.
type Decorator ¶
Decorator is a func that takes one Getter and returns a decorated Getter.
func WithAlias ¶
WithAlias provides a decorator that calls the Getter, and falls back to a set of aliases if the lookup of the key fails.
func WithFallback ¶ added in v0.2.0
WithFallback provides a Decorator that falls back to a default Getter if the key is not found in the decorated Getter.
func WithGraft ¶
WithGraft returns a decorator that attaches the root of the decorated Getter to a node in the config space. The prefix defines where the root node of the getter is located in the config space. The prefix must include any separator prior to the first field.
e.g. with a prefix "a.module.", reading the key "a.module.field" from the WithGraft will return the "field" from the wrapped Getter.
func WithKeyReplacer ¶
WithKeyReplacer provides a decorator which performs a transformation on the key using the ReplacerFunc before calling the Getter.
func WithPrefix ¶
WithPrefix provides a Decorator that adds a prefix to the key before calling the Getter. This is a common special case of KeyReplacer where the key is prefixed with a fixed string.
func WithRegexAlias ¶
func WithRegexAlias(r *RegexAlias) Decorator
WithRegexAlias provides a decorator that calls the Getter, and falls back to a set of regular expression aliases if the lookup of the key fails.
func WithTrace ¶
WithTrace provides a decorator that calls the Getter, and then calls a TraceFunc with the result.
func WithUpdateHandler ¶
func WithUpdateHandler(handler UpdateHandler) Decorator
WithUpdateHandler adds an update processing decorator to a Getter.
type DefaultOption ¶ added in v0.2.0
type DefaultOption struct {
// contains filtered or unexported fields
}
DefaultOption defines default configuration uses as a fall back if a field is not returned by the main getter.
func WithDefault ¶
func WithDefault(d Getter) DefaultOption
WithDefault is an Option that sets the default configuration. If applied multiple times, the earlier defaults are ignored.
type DefaultValueOption ¶ added in v0.5.0
type DefaultValueOption struct {
// contains filtered or unexported fields
}
DefaultValueOption defines a default value used as a fall back if a field is not found in the config.
func WithDefaultValue ¶ added in v0.5.0
func WithDefaultValue(defVal interface{}) DefaultValueOption
WithDefaultValue is an Option that sets the default value for an individual field.
type ErrorHandler ¶
ErrorHandler handles an error. The passed error is processed and an error, which may be the same or different, is returned. The returned error may be nil to indicate the error has been handled.
type ErrorHandlerOption ¶
type ErrorHandlerOption struct {
// contains filtered or unexported fields
}
ErrorHandlerOption defines the handler for errors.
func WithErrorHandler ¶
func WithErrorHandler(e ErrorHandler) ErrorHandlerOption
WithErrorHandler is an Option that sets the error handling for a Config or Value. For Config this applies to Get and is propagated to returned Values. For Value this applies to all type conversions.
type GetErrorHandlerOption ¶ added in v0.2.0
type GetErrorHandlerOption struct {
// contains filtered or unexported fields
}
GetErrorHandlerOption defines the handler for errors returned by Gets.
func WithGetErrorHandler ¶ added in v0.2.0
func WithGetErrorHandler(e ErrorHandler) GetErrorHandlerOption
WithGetErrorHandler is an Option that sets the error handling for a Config Gets.
type Getter ¶
type Getter interface { // Get the value of the named config leaf key. // Also returns an ok, similar to a map read, to indicate if the value was // found. // The type underlying the returned interface{} must be convertable to the // expected type by cfgconv. // // Get does not need to support getting of objects, as returning of complete // objects is neither supported nor required. // // But it does support getting of arrays. // For arrays, referenced by the array name say "ax", a []interface{} must // be returned. // Array elements are referenced using keys of form "ax[idx]", where idx is // the zero-based index into the array. // The length of the array is returned by a key of form "ax[]". // If the getter only contains part of the array then it should return only // the elements it contains, not "ax" or "ax[]". // // For arrays of objects the array must be returned, to be consistent with // other arrays, but the elements may be nil. // // Must be safe to call from multiple goroutines. Get(key string) (value interface{}, found bool) }
Getter specifies the minimal interface for a configuration Getter.
A Getter must be safe for concurrent use by multiple goroutines.
func Decorate ¶
Decorate applies an ordered list of decorators to a Getter. The decorators are applied in reverse order, to create a decorator chain with the first decorator being the first link in the chain. When the returned getter is used, the first decorator is called first, then the second, etc and finally the decorated Getter itself.
type GetterAsOption ¶ added in v0.2.0
type GetterAsOption struct { }
GetterAsOption allows a Getter to be passed to New as an option.
type GetterUpdate ¶
type GetterUpdate interface {
Commit()
}
GetterUpdate contains an update from a getter.
type GetterWatcher ¶
type GetterWatcher interface {
Update() <-chan GetterUpdate
}
GetterWatcher contains channels returning updates and errors from Getter watchers.
type KeyWatcher ¶
type KeyWatcher struct {
// contains filtered or unexported fields
}
KeyWatcher watches a particular key/value, with the next returning changed values. The KeyWatcher should not be called from multiple goroutines simulataneously. If you need to watch the key in multiple goroutines then create a KeyWatcher per goroutine.
func (*KeyWatcher) Watch ¶
func (w *KeyWatcher) Watch(done <-chan struct{}) (Value, error)
Watch returns the next value of the watched field. On the first call it immediately returns the current value. On subsequent calls it blocks until the value changes or the done is closed. Returns an error if the watch was ended unexpectedly. Watch should only be called once at a time - it does not support being called by multiple goroutines simultaneously.
type NotFoundError ¶
type NotFoundError struct {
Key string
}
NotFoundError indicates that the Key could not be found in the config tree.
func (NotFoundError) Error ¶
func (e NotFoundError) Error() string
type Notifier ¶
type Notifier struct {
// contains filtered or unexported fields
}
Notifier provides broadcast signalling of an anonymous event. It provides many to many connectivity - any number of sources may trigger the notification and any number of sinks may wait on it.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option is a construction option for a Config.
type RegexAlias ¶
type RegexAlias struct {
// contains filtered or unexported fields
}
RegexAlias provides a mapping from a key to an old key. New keys are expected to contain regular expressions.
func (*RegexAlias) Append ¶
func (r *RegexAlias) Append(new, old string) error
Append adds an alias from a regular expression matching a new key to the old.
type SeparatorOption ¶
type SeparatorOption struct {
// contains filtered or unexported fields
}
SeparatorOption defines the string that separates tiers in keys.
func WithSeparator ¶
func WithSeparator(s string) SeparatorOption
WithSeparator is an Option that sets the config namespace separator. This is an option to ensure it can only set at construction time, as changing it at runtime makes no sense.
type Stack ¶
type Stack struct {
// contains filtered or unexported fields
}
Stack attempts a get using a list of Getters, in the order provided, returning the first result found. Additional layers may be added to the stack at runtime.
func (*Stack) Append ¶
Append appends a getter to the set of getters for the Stack. This means this getter is only used as a last resort, relative to the existing getters.
func (*Stack) Get ¶
Get gets the raw value corresponding to the key. It iterates through the list of getters, searching for a matching key. Returns the first match found, or an error if none is found.
func (*Stack) Insert ¶
Insert inserts a getter to the set of getters for the Stack. This means this getter is used before the existing getters.
func (*Stack) NewWatcher ¶
func (s *Stack) NewWatcher(done <-chan struct{}) GetterWatcher
NewWatcher implements the WatchableGetter interface.
type TagOption ¶
type TagOption struct {
// contains filtered or unexported fields
}
TagOption defines the string that identifies field names during unmarshaling.
type UnmarshalError ¶
UnmarshalError indicates an error occurred while unmarhalling config into a struct or map. The error indicates the problematic Key and the specific error.
func (UnmarshalError) Error ¶
func (e UnmarshalError) Error() string
type UpdateCommit ¶
type UpdateCommit func()
UpdateCommit is a function that commits an update to a getter. After the call the change becomes visible to Get.
type UpdateHandler ¶
type UpdateHandler func(done <-chan struct{}, in <-chan GetterUpdate, out chan<- GetterUpdate)
UpdateHandler receives an update, performs some transformation on it, and forwards (or not) the transformed update. Must return if either the done or in channels are closed. May close the out chan to indicate that no further updates are possible.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value contains a value read from the configuration.
func NewValue ¶ added in v0.2.0
func NewValue(value interface{}, options ...ValueOption) Value
NewValue creates a Value given a raw value. Values are generally returned by Config.Get or Config.GetMust, so you probably don't want to be calling this function.
func (Value) Duration ¶
Duration gets the value corresponding to the key and converts it to a time.Duration. Returns 0 if conversion is not possible.
func (Value) Float ¶
Float converts the value to a float64. Returns 0 if conversion is not possible.
func (Value) Int64 ¶ added in v0.4.0
Int64 converts the value to an int64. Returns 0 if conversion is not possible.
func (Value) Int64Slice ¶ added in v0.4.0
Int64Slice converts the value to a slice of int64s. Returns nil if conversion is not possible.
func (Value) IntSlice ¶
IntSlice converts the value to a slice of ints. Returns nil if conversion is not possible.
func (Value) Slice ¶
func (v Value) Slice() []interface{}
Slice converts the value to a slice of []interface{}. Returns nil if conversion is not possible.
func (Value) String ¶
String converts the value to a string. Returns an empty string if conversion is not possible.
func (Value) StringSlice ¶
StringSlice converts the value to a slice of string. Returns nil if conversion is not possible.
func (Value) Time ¶
Time converts the value to a time.Time. Returns time.Time{} if conversion is not possible.
func (Value) Uint64 ¶ added in v0.4.0
Uint64 converts the value to a iint64. Returns 0 if conversion is not possible.
func (Value) Uint64Slice ¶ added in v0.4.0
Uint64Slice converts the value to a slice of uint64. Returns nil if conversion is not possible.
type ValueErrorHandlerOption ¶ added in v0.2.0
type ValueErrorHandlerOption struct {
// contains filtered or unexported fields
}
ValueErrorHandlerOption defines the error handler added to Values returned by Config Gets. These may be overridden by ValueOptions.
func WithValueErrorHandler ¶ added in v0.2.0
func WithValueErrorHandler(e ErrorHandler) ValueErrorHandlerOption
WithValueErrorHandler is an Option that sets the error handling for a Config Gets.
type ValueOption ¶
type ValueOption interface {
// contains filtered or unexported methods
}
ValueOption is a construction option for a Value.
type WatchableGetter ¶
type WatchableGetter interface { // Create a watcher on the getter. // Watcher will exit if the done chan closes. // Watcher will send updates via the update channel. // Watcher will send terminal errors via the err channel. NewWatcher(done <-chan struct{}) GetterWatcher }
WatchableGetter is the interface supported by Getters that may support being watched.
type Watcher ¶
type Watcher struct {
// contains filtered or unexported fields
}
Watcher provides a synchronous watch of the overall configuration state. The Watcher should not be called from multiple goroutines at a time. If you need to watch the config in multiple goroutines then create a Watcher per goroutine.
func (*Watcher) Watch ¶
Watch returns when the configuration has been changed or the done is closed. Returns an error if the watch was ended unexpectedly. Watch should only be called once at a time. To prevent races, multiple simultaneous calls are serialised. If you need to watch the config in multiple goroutines then create a Watcher per goroutine.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package blob provides a getter that loads and decodes configuration from a source where the configuration is stored in a known format.
|
Package blob provides a getter that loads and decodes configuration from a source where the configuration is stored in a known format. |
decoder
Package decoder contains decoders that convert blobs of configuration from raw bytes into map[string]interface{}.
|
Package decoder contains decoders that convert blobs of configuration from raw bytes into map[string]interface{}. |
decoder/hcl
Package hcl provides a HCL format decoder for config.
|
Package hcl provides a HCL format decoder for config. |
decoder/ini
Package ini provides an INI format decoder for config.
|
Package ini provides an INI format decoder for config. |
decoder/json
Package json provides a JSON format decoder for config.
|
Package json provides a JSON format decoder for config. |
decoder/properties
Package properties provides a Java properties format decoder for config.
|
Package properties provides a Java properties format decoder for config. |
decoder/toml
Package toml provides a TOML format decoder for config.
|
Package toml provides a TOML format decoder for config. |
decoder/yaml
Package yaml provides a YAML format decoder for config.
|
Package yaml provides a YAML format decoder for config. |
loader
Package loader contains loaders that read blobs of configuration from various sources.
|
Package loader contains loaders that read blobs of configuration from various sources. |
loader/bytes
Package bytes provides a loader from []byte for config.
|
Package bytes provides a loader from []byte for config. |
loader/file
Package file provides a file loader for config.
|
Package file provides a file loader for config. |
Package cfgconv provides type conversions from incoming configuration types to requested internal types.
|
Package cfgconv provides type conversions from incoming configuration types to requested internal types. |
Package dict provides a simple Getter that wraps a key/value map.
|
Package dict provides a simple Getter that wraps a key/value map. |
Package env provides an environment variable Getter for config.
|
Package env provides an environment variable Getter for config. |
example
|
|
app
A simple app using a variety of config sources.
|
A simple app using a variety of config sources. |
Package flag provides a command line Getter using Go's flag.
|
Package flag provides a command line Getter using Go's flag. |
Package keys provides utilities to manipulate key strings.
|
Package keys provides utilities to manipulate key strings. |
Package list contains helpers to convert values from strings to lists.
|
Package list contains helpers to convert values from strings to lists. |
Package pflag provides a POSIX/GNU style style command line parser/config Getter.
|
Package pflag provides a POSIX/GNU style style command line parser/config Getter. |
Package tree provides functions to get from common tree structures.
|
Package tree provides functions to get from common tree structures. |