setting

package module
v2.2.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2019 License: MIT Imports: 9 Imported by: 0

README

Setting

Build Status Coverage Status Go Report Card GoDoc

setting is a simple package for the management and loading of settings. Beware setting is still in development and there WILL be breaking changes.

Installation

Installation is the same as with any other go library

go get github.com/iZettle/setting

Getting Started

The quickest way to get started is to use the FillerBuilder. This helper allows you to attach n Fillers and iterate through them to load the relevant Settings.

For example the below Load function looks for relevant Settings first within the environment (using OSLoad) and then in a settings file.

func LoadSettings(settingFile string) setting.Filler {
    return setting.NewFillerBuilder().
    	WithEnvProvider().
    	WithFileProvider(settingFile).
    	Build()
}

Setting, Provider, and Filler

There are three main components of setting, Setting, Provider, and Filler. Together these three main components make the setting package.

Setting

A setting is an interface type, a Setting is the core representation of a setting value.

type Setting interface {
	Bool() (bool, error)
	Int64() (int64, error)
	UInt64() (uint64, error)
	fmt.Stringer
}

A Setting MUST be at-least representable as a string, and MAY return errors upon an attempt to be represented as another type, if conversion to that type is not applicable.

setting implements the Setting interface for you on a string type, it's called Value, it's unlikely that you'll need anything more than that, we recommend that you return Value from your Provider implementation.

Provider

A Provider is an interface type, it takes a list of keys and provides a Setting for each in a map[string]Setting

type Provider interface {
	Load(keys ...string) (map[string]Setting, Error)
}

A provider is an interface to be implemented to give you a Setting from a source. setting implements Provider in a few ways.

  • AggregateProvider a Provider, that takes many instances of Provider, and will return Settings from the first Provider instance that it finds in.
  • CachedProvider a Provider will cache Setting instances retrieved from its fallback Provider for as long as the lifetime of the CachedProvider, or the TTL of the Setting provided by its fallback Provider if it has one.
  • File is an implementation of a Provider that will create Value instances from a supplied text file.
Filler

ProviderFiler implements the Filler interface, and is an object that takes a Provider, and will fill correctly tagged structs with the values loaded from the supplied provider.

Tagged structs can be filled like so:

type Config struct{
	Username	string	`setting:"CONFIG_USERNAME"`
	Server		string	`setting:"CONFIG_SERVER"`
	Port		int		`setting:"CONFIG_PORT"`
	Production	bool	`setting:"CONFIG_PRODUCTION"`
}

func Load(){
	cfg := Config{}
	filler := setting.ProviderFiller{
		Provider: &setting.File{
			Filename:"settings.txt",
		},
	}
	if err := filler.Fill(&cfg); err != nil{
		panic(err)
	}
}

MapFill is no longer supported as it's need has been removed by go 1.8s ability to convert two equivalent structs between each other.

OSLoad

OSLoad loads settings from environmental variables, and implements the Provider interface through ProviderFunc

p := ProviderFunc(OSLoad)
s, err := p.Load("foo")
File

File loads settings from a file on disk

file := setting.File{FileName: *settingsFileName}
s, err := file.Load("foo")

The loaded file should contain a single setting definition per line. Each setting should be defined in the form setting_name=value

// This is a comment with a SETTING=foobar in it, it is ignored.
MY_FOO_SETTING=42
MY_BAR_SETTING=setting string
not a setting
Error

Error is a wrapper for generic errors.

  1. Error adds extra context to generic errors by allowing the user to return a list of keys that weren't successfully retrieved when used in one of the loader/provider calls
  2. Error also contains a FatalError property that can be used to interpret if the error that has been thrown is "fatal" and thus requires a separate course of action than a generic error.
type Error interface {
	error
	MissingKeys() []string
	FatalError() error
}

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AggregateProvider

type AggregateProvider []Provider

AggregateProvider allows multiple settings providers to be combined so as settings can be loaded from multiple sources.

func NewAggregateProviderWithDefault

func NewAggregateProviderWithDefault(provider Provider, structReceived interface{}) AggregateProvider

NewAggregateProviderWithDefault sets up a defaultProvider and makes sure this is added first into the aggregate provider method

func (AggregateProvider) Load

func (ap AggregateProvider) Load(keys ...string) (map[string]Setting, Error)

Load implements the SettingsProvider interface, and will check providers for key values. Returns a map of key to Setting, and a Error containing a list of keys which could not be found.

type CachedProvider

type CachedProvider struct {
	Fallback Provider
	Lifetime int64
	// contains filtered or unexported fields
}

CachedProvider takes a settings provider, and a lifetime, CachedProvider will hold a setting for as long as its lifetime, or the lifetime of the ExpirableSetting passed to it from its fallback, if an ExpirableSetting is passed. Already expired ExpirableSettings, will be passed to the caller, but will not be cached.

func (*CachedProvider) Clear

func (cp *CachedProvider) Clear()

Clear will completely empty the cache of CachedSettingsProvider

func (*CachedProvider) Load

func (cp *CachedProvider) Load(keys ...string) (map[string]Setting, Error)

Load implements the settings provider interface, and will prefer to return settings from it's in memory cache, and then its fallback provider. If expired settings are provided, they will be returned to the caller, but they will not be saved.

If you wish for Settings not to be cached, simply implement ExpirableSetting interface so as that TTL always returns 0 and Expired() always returns false.

type CachedValue

type CachedValue struct {
	Setting
	Expiry time.Time
}

CachedValue is a setting that implements ExpirableSetting interface, so that CachedProvider may determine whether a setting has expired from the cache and should be reloaded from the fallback

func (CachedValue) Expired

func (cv CachedValue) Expired() bool

Expired is whether the setting in question has expired in the cache

func (CachedValue) TTL

func (cv CachedValue) TTL() time.Duration

TTL is the number of seconds from the expiry of the setting

type DefaultProvider

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

DefaultProvider struct where target is the struct that will be extracted within the default load function

func NewDefaultProvider

func NewDefaultProvider(target interface{}) *DefaultProvider

NewDefaultProvider setups the DefaultProvider struct for use with default load the passed target interface should be a pointer to a struct

func (*DefaultProvider) Load

func (dp *DefaultProvider) Load(keys ...string) (map[string]Setting, Error)

Load receives a target struct via the NewDefaultProvider method, from this default values for keys are pulled out and returned using the structextract package

type Error

type Error interface {
	error
	MissingKeys() []string
	FatalError() error
}

Error is a generic error wrapper that can be used to list missing keys if errors occur. If a fatal error has been added to the type this should signify a type of error where execution should cease.

func OSLoad

func OSLoad(keys ...string) (map[string]Setting, Error)

OSLoad will load environment variables into settings if they are found, and will return a Error if a key is not found.

type Expirable

type Expirable interface {
	Expired() bool
	TTL() time.Duration
}

Expirable allows CachedProvider to determine the lifetime of an item in its cache.

type ExpirableSetting

type ExpirableSetting interface {
	Expirable
	Setting
}

ExpirableSetting combines the Setting and Expirable interface to be checked in Cached settings provider.

type File

type File struct {
	FileName string
	// contains filtered or unexported fields
}

File implements the setting.Provider interface

func (*File) Load

func (f *File) Load(keys ...string) (map[string]Setting, Error)

Load implements the setting.File interface, allowing settings to be loaded from disk in the settings provider library.

func (*File) LoadFile

func (f *File) LoadFile() error

LoadFile loads the settings file line by line from the file and reads them into a map.

type Filler

type Filler interface {
	Fill(interface{}) error
}

Filler fills a struct from the tags on the struct itself

type FillerBuilder

type FillerBuilder struct {
	Providers AggregateProvider
}

FillerBuilder is used to compose commonly used Providers together

func NewFillerBuilder

func NewFillerBuilder() FillerBuilder

NewFillerBuilder is the default constructor for a FillerBuilder

func (FillerBuilder) Build

func (fb FillerBuilder) Build() Filler

Build builds the filler

func (FillerBuilder) WithEnvProvider

func (fb FillerBuilder) WithEnvProvider() FillerBuilder

WithEnvProvider adds the OSLoad Provider to the Providers Slice

func (FillerBuilder) WithFileProvider

func (fb FillerBuilder) WithFileProvider(settingsFile string) FillerBuilder

WithFileProvider loads the specified file using the file provider and adds it to the Providers Slice

func (FillerBuilder) WithProvider

func (fb FillerBuilder) WithProvider(provider ProviderFunc) FillerBuilder

WithProvider add the specified provider to the Providers Slice

type Provider

type Provider interface {
	Load(keys ...string) (map[string]Setting, Error)
}

Provider is a simple interface, that can your types should accept if you want access to raw settings, or that you should implement if you want your structs to be auto-filled from a source of your choice

type ProviderError

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

ProviderError defines the struct to handle for a fatal error.

func NewFatalProviderError

func NewFatalProviderError(err error, keys ...string) *ProviderError

NewFatalProviderError returns a fatal error and a list of keys that were supplied to the service that threw the fatal error.

func NewProviderError

func NewProviderError(keys ...string) *ProviderError

NewProviderError returns a list of keys that could not be found or aren't set in the searched location.

func (*ProviderError) AppendMissingKeys

func (pe *ProviderError) AppendMissingKeys(keys ...string) *ProviderError

AppendMissingKeys either adds a key to a pre-existing slice of keys or instantiates a new slice of keys

func (*ProviderError) Error

func (pe *ProviderError) Error() string

Error returns the fatal with a joined list of missing keys.

func (*ProviderError) FatalError

func (pe *ProviderError) FatalError() error

FatalError returns the error object that was thrown.

func (*ProviderError) MissingKeys

func (pe *ProviderError) MissingKeys() []string

MissingKeys returns a list of keys that could not be found in the searched location.

type ProviderFiller

type ProviderFiller struct {
	Provider  Provider
	CustomTag string
}

ProviderFiller fills a tagged struct with the settings from the settingProvider

func NewProviderFiller

func NewProviderFiller(provider Provider) *ProviderFiller

NewProviderFiller constructs an instance of ProviderFiller, with no custom tag.

func (*ProviderFiller) Fill

func (pf *ProviderFiller) Fill(configPtr interface{}) error

Fill fills a struct's fields that are tagged with `setting:"SETTING_KEY"` with the value provided from the Provider, the setting must be able to be represented as the type of the field.

type ProviderFunc

type ProviderFunc func(...string) (map[string]Setting, Error)

ProviderFunc allows functions that accept and return the same as as a Provider to implement the Provider interface

func (ProviderFunc) Load

func (pf ProviderFunc) Load(keys ...string) (map[string]Setting, Error)

Load implements the Provider interface, and calls the ProviderFunc when called

type Setting

type Setting interface {
	Bool() (bool, error)
	Int64() (int64, error)
	UInt64() (uint64, error)
	fmt.Stringer
}

Setting is the core interface type of setting, it represents a setting value a Setting MUST at least be representable as a string, and as such implements the fmt.Stringer interface. A setting MAY return an error upon attempt to be used as a non applicable type.

type StringMapProvider

type StringMapProvider map[string]string

StringMapProvider implements the setting.Provider interface to provide compatibility with other packages such as viper

func (StringMapProvider) Load

func (smp StringMapProvider) Load(keys ...string) (map[string]Setting, Error)

Load implements the setting.Provider interface, allowing settings to be loaded from a map of strings

type Value

type Value string

Value a string type to store the raw setting, implements Setting.

func (Value) Bool

func (s Value) Bool() (bool, error)

Bool returns value as boolean, or error, implements Setting interface

func (Value) Int64

func (s Value) Int64() (int64, error)

Int64 returns value as int64, or error, implements Setting interface

func (Value) String

func (s Value) String() string

String implements the stringer interface, and return a string.

func (Value) UInt64

func (s Value) UInt64() (uint64, error)

UInt64 returns value as uint64, or error, implements Setting interface

Jump to

Keyboard shortcuts

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