Documentation
¶
Overview ¶
Package config loads settings from files, environment variables and command-line arguments into a configuration struct, following a schema that names, types and documents every setting.
Problems are collected, not returned one at a time: Load reports every invalid setting it finds, each with where it came from and how to fix it.
Index ¶
- Constants
- Variables
- func CertPool(file string) (*x509.CertPool, error)
- func ChoiceNames(choices []Choice) []string
- func Choose(choices []Choice, name string) (int64, error)
- func Describe(raw any) string
- func Display(s string) string
- func Encode(v any, format string) ([]byte, error)
- func Format(format string) (string, bool)
- func Formats() []string
- func Invalid(v Value, message, hint string) error
- func Items(v Value, fn func(item Value) error) error
- func LoadTLS(values map[string]Value, prefix string) (TLS, []Problem)
- func MemberStrings(v Value, fn func(name, s string)) error
- func Members(v Value, fn func(name string, member Value) error) error
- func Mismatch(v Value, want string, takes ...Kind) error
- func Parse(data []byte, format string) (any, error)
- func Section[S any](p **S, def S) *S
- func Toggle[S any](p **S, def S, on bool)
- type Choice
- type Error
- type Field
- type Flag
- type Kind
- type Problem
- type Schema
- func (s *Schema[T]) Decode(dst *T, v Value) error
- func (c *Schema) Flags() []Flag
- func (c *Schema) Keys() []string
- func (c *Schema) KindOf(key string) (Kind, bool)
- func (s *Schema[T]) Load(dst *T, sources []Source) (map[string]Value, error)
- func (s *Schema[T]) LoadOnly(dst *T, sources []Source) (map[string]Value, error)
- func (s *Schema[T]) Only(names ...string) *Schema[T]
- func (s *Schema[T]) Skip(names ...string) *Schema[T]
- func (c *Schema) Usage(envPrefix string) string
- type Source
- type TLS
- type Value
- type YAMLDocument
Constants ¶
const ( CodeUnknownKey = "unknown_key" CodeInvalidValue = "invalid_value" CodeMissingValue = "missing_value" CodeConflict = "conflict" CodeNotAllowed = "not_allowed" CodeFileNotFound = "file_not_found" CodeFileAmbiguous = "file_ambiguous" CodeUnsupportedFormat = "unsupported_format" CodeParseError = "parse_error" CodeReadError = "read_error" CodeUnexpectedArgument = "unexpected_argument" )
Codes of problems. They are stable, so tools can act on them.
Variables ¶
var LogLevels = []Choice{ {Name: "trace", Value: int64(zerolog.TraceLevel)}, {Name: "debug", Value: int64(zerolog.DebugLevel)}, {Name: "info", Value: int64(zerolog.InfoLevel)}, {Name: "warn", Value: int64(zerolog.WarnLevel)}, {Name: "error", Value: int64(zerolog.ErrorLevel)}, {Name: "fatal", Value: int64(zerolog.FatalLevel)}, {Name: "panic", Value: int64(zerolog.PanicLevel)}, {Name: "none", Value: int64(zerolog.NoLevel)}, {Name: "disabled", Value: int64(zerolog.Disabled)}, }
LogLevels are the choices of a log level setting, the levels of zerolog.
Functions ¶
func CertPool ¶
CertPool reads the PEM certificates in file. A file without any is an error: an empty pool would reject every client certificate.
func ChoiceNames ¶ added in v1.2.0
ChoiceNames lists the names of choices, in order.
func Choose ¶ added in v1.2.0
Choose returns the value of the choice of choices named name, in any case, as a setting with those choices reads it. The error lists the names a command can tell its user.
func Describe ¶
Describe names the type of a decoded value for messages, such as "a list" or "an object".
func Display ¶
Display hides the password of a URL, such as a proxy URL, before it goes into a message: see display.
func Encode ¶
Encode writes v, a value of the data model, as a JSON or YAML document. format is json, yaml or yml, in any case and with or without a leading dot. Decoding the result as a document gives v back.
func Format ¶
Format normalizes the format of a document, such as ".YAML", and reports whether it is JSON or YAML.
func Formats ¶
func Formats() []string
Formats returns the formats documents can be written in, as Format names them.
func Invalid ¶
Invalid returns an *Error with one invalid_value problem of v: message says what is wrong, and hint how to fix it. A Set returns it to report a problem with a hint, which a plain error can't carry.
func Items ¶
Items calls fn with every element of the list an Any value holds, in order, as a Value keyed "<key>[i]". An error from fn becomes a problem of that element; an *Error keeps its own problems. A value that isn't a list is a problem of v. The error is an *Error listing every problem.
func LoadTLS ¶
LoadTLS loads the files that the settings <prefix>cert, <prefix>key and <prefix>ca of values name: the server's certificate and its key, which go together, and the client CAs, which need them. It reports a missing setting and a file it can't load as problems of the setting that named it.
func MemberStrings ¶
MemberStrings calls fn with each string of each member of the object an Any value holds, sorted by name and then in order, as Members does: a member is a string, or a list of strings, such as the values of a header. A member of another type, or an item of a list that isn't a string, is a problem of its own. The error is an *Error listing every problem.
func Members ¶
Members calls fn with every member of the object an Any value holds, sorted by name, as a Value keyed "<key>.<name>". The names are kept as written, such as header names. An error from fn becomes a problem of that member; an *Error keeps its own problems. A value that isn't an object is a problem of v. The error is an *Error listing every problem.
func Mismatch ¶
Mismatch returns an *Error with the invalid_value problem of v, which holds a value of a type the setting doesn't take, worded as every such problem is: "<key> must be <want>, not <a number>". takes lists the kinds the setting takes, which pick the hint: a number or a bool where a String is taken is to be quoted, an integer in quotes where an Int is taken is not, and text where a List is taken is to be written as a list.
func Parse ¶
Parse parses data, a document in format, json, yaml or yml as Format takes it, into the data model of package value, as decode does.
Types ¶
type Error ¶
type Error struct {
// Scope starts the message, such as "mock". Empty means "config".
Scope string
Problems []Problem
}
Error lists every problem found while loading settings.
type Field ¶
type Field[T any] struct { // Key is the dotted, snake_case path of the setting, such as "log.level". // It is the nested key in files. Env and flag names derive from it. Key string // Short is an optional one-letter flag alias. Short string // Usage describes the setting in help text. Usage string // Default is the default value as help text shows it. It is not applied. Default string // Kind is the type of the value. Kind Kind // Choices lists the allowed values of an Int setting. Inputs give their names, in any case. Choices []Choice // Set validates the value and applies it to dst. Its error becomes a problem of the value. // A nil Set leaves the value to the caller, which reads it from Load's result. Set func(dst *T, v Value) error // Hidden keeps the setting out of Flags and Usage: it is read, and checked, as any other. Hidden bool // Secret marks a String setting, such as a password, that only files and environment variables set: the command // line shows to every user of the host. No problem of its value holds it. Secret bool }
Field declares a setting of a T.
type Flag ¶
type Flag struct {
Name string // long name without dashes, such as "log-level"
Shorthand string // one-letter alias, or ""
Usage string // the setting's usage
Bool bool // the flag takes no value
Values []string // names of the allowed values
}
Flag describes the command-line flag of a setting.
type Kind ¶
type Kind uint8
Kind is the type of a setting's value.
const ( // String takes a string. String Kind = iota // Bool takes what strconv.ParseBool reads: a bool, text such as true, 1 or f, or the number 1 or 0. Bool // Int takes a whole number that fits an int64. Text gives it in the JSON number grammar, so 5 and 5.0, // but not +5 or 05. With Choices, it takes only the name of a choice, in any case. Int // Duration takes whole milliseconds from 0, or an unsigned Go duration, such as 1.5s. // Text that is a number is milliseconds. Duration // List takes a list of strings. Text gives comma-separated items, and a repeated flag adds to them. List // Any takes any value as decoded, unchecked: a Set decodes it, for example a nested object with Decode. // Env and args give it their text. Any )
Kinds of setting values. A value in a document must have the type of its kind: nothing is converted, except that bools read everywhere the way strconv.ParseBool reads text. Env and args give text, which is parsed.
type Problem ¶
type Problem struct {
Code string // stable identifier, such as "unknown_key"
Origin string // where it happened, such as "env VLATTE_ADDR" or "file .vlatterc.json:3:7"
Key string // the setting's key, when known
Value string // the offending value, when there is one
Message string // what is wrong
Hint string // how to fix it, when known
}
Problem is one invalid setting: what is wrong, where it came from, and how to fix it.
func FileProblem ¶
FileProblem reports a file that can't be loaded, what names, as a problem of the setting v that named it.
func ProblemsOf ¶
ProblemsOf returns the problems of err, which Decode or a Set returned for v: none for nil, the problems of an *Error, and one problem of v for any other error. A caller adding problems of its own merges them, and drops no error.
type Schema ¶
type Schema[T any] struct { // contains filtered or unexported fields }
Schema holds the settings of a T, in the order they were declared.
func NewSchema ¶
NewSchema builds a schema from fields. It panics when a key, flag or environment variable name is invalid or used twice, since fields are declared in code.
func (*Schema[T]) Decode ¶
Decode applies the object an Any value holds to dst, the way Load applies a document. It is how a Set decodes a nested object with a schema of its own. Problems are keyed under v.Key, such as "response.status", and come from v.Origin. The error is an *Error listing every problem; returned by a Set, its problems join the caller's.
func (*Schema) Flags ¶
func (c *Schema) Flags() []Flag
Flags lists the command-line flags of the settings, in declaration order.
func (*Schema) Keys ¶
func (c *Schema) Keys() []string
Keys lists every key and group, sorted, such as "log" and "log.level".
func (*Schema) KindOf ¶
KindOf returns the kind of the setting key, or false when there is no such setting.
func (*Schema[T]) Load ¶
Load reads the sources and applies their values to dst through each field's Set. Sources are listed lowest precedence first: a later source overrides an earlier one.
It returns the winning value of every key a source set. The error is flag.ErrHelp when the arguments ask for help, or an *Error listing every problem found.
func (*Schema[T]) LoadOnly ¶
LoadOnly is like Load, but reads only the settings of the schema from sources that hold others too, such as those of another schema: an unknown key, environment variable or flag is no problem, and is skipped. A flag it doesn't know is skipped with the argument that follows it, unless that argument is a flag: an unknown flag takes its value after =, or as the next argument.
func (*Schema[T]) Only ¶
Only reads only the top-level settings names, such as "grpc", from files and environment variables: the schema leaves the others to the schemas that read the same sources, as Skip does.
func (*Schema[T]) Skip ¶
Skip leaves the top-level settings names, such as "grpc", to another schema that reads the same files and environment variables: the schema ignores them there, where it would report them as unknown. Flags are the caller's to split: an Args source reports every flag it doesn't know.
type Source ¶
type Source interface {
// contains filtered or unexported methods
}
Source is a place settings are read from: a file, environment variables or command-line arguments. Build one with File, Env or Args.
func Args ¶
Args reads settings from command-line arguments, such as --log-level=debug, -a :8080 or --cors. Flag names derive from keys, with "-" for "." and "_". A repeated list flag adds to the list. It never reads os.Args: the caller passes the arguments, such as os.Args[1:].
func Bytes ¶
Bytes reads settings from a JSON or YAML document held in memory, such as a request body. format is json, yaml or yml, in any case and with or without a leading dot. origin names the document in problems, such as "file mocks/users.yaml" or "admin request".
func Env ¶
Env reads settings from environment variables named prefix_KEY, such as VLATTE_LOG_LEVEL for log.level. Empty variables are ignored. Any other variable starting with prefix_ is a problem, so a typo doesn't go unnoticed, unless it is listed in reserved because something else reads it.
func File ¶
File reads settings from a JSON or YAML file, chosen by its extension: .json, .yaml or .yml.
With no dirs, path is the file to read, and it must exist. With dirs, path is a base name, such as ".vlatterc": the first dir that holds path with a .json, .yaml or .yml extension, in any case, is read, and finding none is fine. Other files named after path, such as editor backups, are ignored. A higher-precedence source that sets pathKey, such as a --config flag, replaces that lookup with the file it names.
type TLS ¶
type TLS struct {
// Certificates holds the server's certificate. Empty when the settings name none.
Certificates []tls.Certificate
// ClientCAs are the CAs that client certificates must be signed by, for mutual TLS. Nil when the settings name none.
ClientCAs *x509.CertPool
}
TLS is the TLS a server's settings name the files of.
type Value ¶
type Value struct {
Key string // the setting's key
Origin string // where the value came from, such as "env VLATTE_ADDR" or "flag --addr"
Raw string // the value as written
Str string
Bool bool
Int int64
Dur time.Duration
List []string
// Any is the value of an Any setting, as decoded: nil, bool, string, int64, float64, []any or map[string]any.
Any any
}
Value is a setting's value, converted to its Kind.
type YAMLDocument ¶ added in v1.1.0
type YAMLDocument struct {
// Number is its 1-based position in the stream, including empty documents.
Number int
// Data is a standalone YAML document. A sole first document keeps the original bytes, so its diagnostics keep
// their line numbers and formatting.
Data []byte
}
YAMLDocument is one nonempty document of a YAML stream.
func YAMLDocuments ¶ added in v1.1.0
func YAMLDocuments(data []byte) ([]YAMLDocument, error)
YAMLDocuments reads the complete YAML stream before returning its nonempty documents, in order. Implicit empty documents are skipped; explicit null, scalar and list values remain for the caller to validate. A failure names its document number and returns no documents. Each result can be parsed independently with Parse.