config

package module
v3.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2023 License: MIT Imports: 18 Imported by: 2

README

Nacelle logo

Configuration loading and validation for Nacelle

PkgGoDev Build status Latest release


See the package documentation on nacelle.dev.

Documentation

Index

Constants

View Source
const (
	DefaultTag  = "default"
	RequiredTag = "required"
	EnvTag      = "env"
	FlagTag     = "flag"
	FileTag     = "file"
	DisplayTag  = "display"
	MaskTag     = "mask"
)

Variables

View Source
var (
	ErrInvalidMaskTag = errors.New("invalid mask tag")
)

Functions

func ApplyTagModifiers

func ApplyTagModifiers(obj interface{}, modifiers ...TagModifier) (modified interface{}, err error)

ApplyTagModifiers returns a new struct with a dynamic type whose fields are equivalent to the given object but whose field tags are run through each tag modifier in sequence.

func LoadFromContext

func LoadFromContext(ctx context.Context, target interface{}, modifiers ...TagModifier) error

func ParseTOML

func ParseTOML(content []byte) (map[string]interface{}, error)

ParseTOML parses the given content as JSON.

func ParseYAML

func ParseYAML(content []byte) (map[string]interface{}, error)

ParseYAML parses the given content as YAML.

func WithConfig

func WithConfig(ctx context.Context, cfg *Config) context.Context

Types

type Config

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

Config is a structure that can populate the exported fields of a struct based on the value of the field `env` tags.

func FromContext

func FromContext(ctx context.Context) *Config

func NewConfig

func NewConfig(sourcer Sourcer, configs ...ConfigOptionsFunc) *Config

NewConfig creates a config loader with the given sourcer.

func (*Config) Assets

func (c *Config) Assets() []string

Assets returns a list of names of assets that compose the underlying sourcer. This can be a list of matched files that are read, or a token that denotes a fixed source.

func (*Config) Describe

func (c *Config) Describe(target interface{}, modifiers ...TagModifier) (*StructDescription, error)

Describe returns a description of the struct relevant to the given config object. Field descriptions include the field name, the values of struct tags matching the configured sourcer, whether or not the field must be populated, and a default value (if any).

func (*Config) Dump

func (c *Config) Dump() map[string]string

Dump returns the full content of the underlying sourcer. This is used by the logging package to show the content of the environment and config files when a value is missing or otherwise illegal.

func (*Config) Init

func (c *Config) Init() error

Init prepares state required by the registered sourcer. This method should be called before calling any other method.

func (*Config) Load

func (c *Config) Load(target interface{}, modifiers ...TagModifier) error

Load populates a configuration object. The given tag modifiers are applied to the configuration object pre-load.

type ConfigOptionsFunc

type ConfigOptionsFunc func(*configOptions)

ConfigOptionsFunc is a function used to configure instances of config.

func WithLogger

func WithLogger(logger Logger) ConfigOptionsFunc

WithLogger sets the Logger instance.

func WithMaskedKeys

func WithMaskedKeys(maskedKeys []string) ConfigOptionsFunc

WithMaskedKeys sets the field names of values masked in log messages.

type DirectorySourcerConfigFunc

type DirectorySourcerConfigFunc func(*directorySourcerOptions)

DirectorySourcerConfigFunc is a function used to configure instances of directory sourcers.

func WithDirectorySourcerFS

func WithDirectorySourcerFS(fs FileSystem) DirectorySourcerConfigFunc

WithDirectorySourcerFS sets the FileSystem instance.

type FieldDescription

type FieldDescription struct {
	Name      string
	Default   string
	Required  bool
	TagValues map[string]string
}

type FileParser

type FileParser func(content []byte) (map[string]interface{}, error)

type FileSourcerConfigFunc

type FileSourcerConfigFunc func(*fileSourcerOptions)

FileSourcerConfigFunc is a function used to configure instances of file sourcers.

func WithFileSourcerFS

func WithFileSourcerFS(fs FileSystem) FileSourcerConfigFunc

WithFileSourcerFS sets the FileSystem instance.

type FileSystem

type FileSystem interface {
	// Exists determines if the given path exists.
	Exists(path string) (bool, error)

	// ListFiles returns the names of the files that are a direct
	// child of the directory at the given path.
	ListFiles(path string) ([]string, error)

	// Glob returns the paths that the given pattern matches.
	Glob(pattern string) ([]string, error)

	// ReadFile returns the content of the file at the given path.
	ReadFile(path string) ([]byte, error)
}

FileSystem is an interface wrapping filesystem operations for sourcers that read information from disk. This is necessary in order to allow remote and in-memory filesystems that may be present in some application deployments. Third-party libraries such as spf13/afero that provide FS-like functionality can be shimmed into this interface.

type FlagSourcerConfigFunc

type FlagSourcerConfigFunc func(*flagSourcerOptions)

FlagSourcerConfigFunc is a function used to configure instances of flag sourcers.

func WithFlagSourcerArgs

func WithFlagSourcerArgs(args []string) FlagSourcerConfigFunc

WithFlagSourcerArgs sets raw command line arguments.

type GlobSourcerConfigFunc

type GlobSourcerConfigFunc func(*globSourcerOptions)

GlobSourcerConfigFunc is a function used to configure instances of glob sourcers.

func WithGlobSourcerFS

func WithGlobSourcerFS(fs FileSystem) GlobSourcerConfigFunc

WithGlobSourcerFS sets the FileSystem instance.

type LoadError

type LoadError struct {
	// Errors that were found while loading a config.
	Errors []error
}

LoadError is an error returned when a config fails to load. It contains Errors, a slice of any errors that occurred during config load.

func (*LoadError) Error

func (le *LoadError) Error() string

type Logger

type Logger interface {
	// Printf logs a message. Arguments should be handled in the manner of fmt.Printf.
	Printf(format string, args ...interface{})
}

Logger is an interface to the logger where config values are printed.

type PostLoadConfig

type PostLoadConfig interface {
	PostLoad() error
}

PostLoadConfig is a marker interface for configuration objects which should do some post-processing after being loaded. This can perform additional casting (e.g. ints to time.Duration) and more sophisticated validation (e.g. enum or exclusive values).

type PostLoadError

type PostLoadError struct {
	Err error
}

PostLoadError is an error returned when a config's PostLoad method fails.

func (*PostLoadError) Error

func (ple *PostLoadError) Error() string

func (*PostLoadError) Unwrap

func (ple *PostLoadError) Unwrap() error

type ReflectField

type ReflectField struct {
	Field     reflect.Value
	FieldType reflect.StructField
}

type SerializeError

type SerializeError struct {
	FieldName string
	Err       error
}

SerializeError is an error returned when a config loader fails to serialize a field in a config struct.

func (*SerializeError) Error

func (se *SerializeError) Error() string

func (*SerializeError) Unwrap

func (se *SerializeError) Unwrap() error

type Sourcer

type Sourcer interface {
	// Init is a hook for certain classes of sourcers to read and normalize
	// the source data. This gives a canonical place where external errors
	// can occur that are not directly related to validation.
	Init() error

	// Tags returns a list of tags which are required to get a value from
	// the source. Order matters.
	Tags() []string

	// Get will retrieve a value from the source with the given tag values.
	// The tag values passed to this method will be in the same order as
	// returned from the Tags method. The flag return value directs config
	// population whether or not this value should be treated as missing or
	// skippable.
	Get(values []string) (string, SourcerFlag, error)

	// Assets returns a list of names of assets that compose the sourcer.
	// This can be a list of matched files that are read, or a token that
	// denotes a fixed source.
	Assets() []string

	// Dump returns the full content of the sourcer. This is used by the
	// logging package to show the content of the environment and config
	// files when a value is missing or otherwise illegal.
	Dump() map[string]string
}

Sourcer pulls requested names from a variable source. This can be the environment, a file, a remote server, etc. This can be done on-demand per variable, or a cache of variables can be built on startup and then pulled from a cached mapping as requested.

func NewDirectorySourcer

func NewDirectorySourcer(dirname string, parser FileParser, configs ...DirectorySourcerConfigFunc) Sourcer

NewDirectorySourcer creates a sourcer that reads files from a directory. For details on parsing format, refer to NewFileParser. Each file in a directory is read in alphabetical order. Nested directories are ignored when reading directory content, and each found regular file is assumed to be parseable by the given FileParser.

func NewEnvSourcer

func NewEnvSourcer(prefix string) Sourcer

NewEnvSourcer creates a Sourcer that pulls values from the environment. The environment variable {PREFIX}_{NAME} is read before and, if empty, the environment variable {NAME} is read as a fallback. The prefix is normalized by replacing all non-alpha characters with an underscore, removing leading and trailing underscores, and collapsing consecutive underscores with a single character.

func NewFileSourcer

func NewFileSourcer(filename string, parser FileParser, configs ...FileSourcerConfigFunc) Sourcer

NewFileSourcer creates a sourcer that reads content from a file. The format of the file is read by the given FileParser. The content of the file must be an encoding of a map from string keys to JSON-serializable values. If a nil parser is supplied, one will be selected based on the extension of the file. JSON, YAML, and TOML files are supported.

func NewFlagSourcer

func NewFlagSourcer(configs ...FlagSourcerConfigFunc) Sourcer

NewFlagSourcer creates a Sourcer that pulls values from the application flags.

func NewGlobSourcer

func NewGlobSourcer(pattern string, parser FileParser, configs ...GlobSourcerConfigFunc) Sourcer

NewGlobSourcer creates a sourcer that reads all files that match the given glob pattern. Each matching file is read in alphabetical order of path. Each matching pathis assumed to be parseable by the given FileParser.

func NewMultiSourcer

func NewMultiSourcer(sourcers ...Sourcer) Sourcer

NewMultiSourcer creates a sourcer that reads form each sourcer. The last value found is returned - sourcers should be provided from low priority to high priority.

func NewOptionalDirectorySourcer

func NewOptionalDirectorySourcer(dirname string, parser FileParser, configs ...DirectorySourcerConfigFunc) Sourcer

NewOptionalDirectorySourcer creates a directory sourcer that does not error on init if the directory does not exist. In this case, the underlying sourcer returns no values.

func NewOptionalFileSourcer

func NewOptionalFileSourcer(filename string, parser FileParser, configs ...FileSourcerConfigFunc) Sourcer

NewOptionalFileSourcer creates a file sourcer that does not error on init if the file does not exist. The underlying sourcer returns no values.

func NewTOMLFileSourcer

func NewTOMLFileSourcer(filename string) Sourcer

NewTOMLFileSourcer creates a file sourcer that parses conent as TOML.

func NewTestEnvSourcer

func NewTestEnvSourcer(values map[string]string) Sourcer

NewTestEnvSourcer creates a Sourcer that returns values from a given map.

func NewYAMLFileSourcer

func NewYAMLFileSourcer(filename string) Sourcer

NewYAMLFileSourcer creates a file sourcer that parses conent as YAML.

type SourcerFlag

type SourcerFlag int
const (
	FlagUnknown SourcerFlag = iota
	FlagFound
	FlagMissing
	FlagSkip
)

type StructDescription

type StructDescription struct {
	Fields []FieldDescription
}

type TagModifier

type TagModifier interface {
	// AlterFieldTag modifies the tags reference by setting or deleting
	// values from the given tag wrapper. The given tag wrapper is the
	// parsed version of the tag for the given field. Returns an error
	// if there is an internal consistency problem.
	AlterFieldTag(field reflect.StructField, tags *structtag.Tags) error
}

TagModifier is an interface that rewrites a set of tags for a struct field. This interface is used by the ApplyTagModifiers function.

func NewDefaultTagSetter

func NewDefaultTagSetter(field string, defaultValue string) TagModifier

NewDefaultTagSetter creates a new TagModifier which sets the value of the default tag for a particular field. This is used to change the default values provided by third party libraries (for which a source change would be otherwise required).

func NewDisplayTagSetter

func NewDisplayTagSetter() TagModifier

NewDisplayTagSetter creates a new TagModifier which sets the value of the display tag to be the same as the env tag.

func NewEnvTagPrefixer

func NewEnvTagPrefixer(prefix string) TagModifier

NewEnvTagPrefixer creates a new TagModifier which adds a prefix to the values of `env` tags. This can be used to register one config multiple times and have their initialization be read from different environment variables.

func NewFileTagPrefixer

func NewFileTagPrefixer(prefix string) TagModifier

NewFileTagPrefixer creates a new TagModifier which adds a prefix to the values of `file` tags. This can be used to register one config multiple times and have their initialization be read from different keys in a config file.

func NewFileTagSetter

func NewFileTagSetter() TagModifier

NewFileTagSetter creates a new TagModifier which sets the value of the file tag to be the same as the env tag.

func NewFlagTagPrefixer

func NewFlagTagPrefixer(prefix string) TagModifier

NewFlagTagPrefixer creates a new TagModifier which adds a prefix to the values of `flag` tags.

func NewFlagTagSetter

func NewFlagTagSetter() TagModifier

NewFlagTagSetter creates a new TagModifier which sets the value of the flag tag to be the same as the env tag.

Jump to

Keyboard shortcuts

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