Documentation ¶
Overview ¶
Package configtypes provides types that may be useful in configuration parsing and validation, or for other purposes where primitive types do not enforce the desired semantics.
Opt types ¶
The types beginning with "Opt" follow a general contract as described below; there are only a few special cases that are documented for the specific types.
Defined versus empty ¶
The "Opt" types represent optional values of some wrapped type. Some of them allow any such value. Others have additional validation, indicated by extra words after the name of the type: for instance, OptIntGreaterThanZero is like OptInt except the value must be greater than zero.
Any instance can be in either a "defined" or an "empty" state. Defined means that it contains a value of the wrapped type. Empty means no value was specified. The IsDefined() method tests this state.
Instances have a GetOrElse() method that returns the wrapped value if defined, or the specified alternative value if empty. The only exception to this is if there is already a natural way for a value of the wrapped type to be undefined (for instance, if it is a pointer), in which case the method is just Get().
If the wrapped type has mutable state (a slice, pointer, or map), it is always copied when accessed.
Opt type constructors ¶
The zero value of these types is the empty state, so the way to declare a value in that state is simply as an empty struct, OptFoo{} (all of these types are structs).
For types without validation, the NewOptFoo(valueType) constructor returns a defined OptFoo for any given value.
opt := OptBool{} // opt is empty opt := NewOptBool(false) // opt contains the value false opt := NewOptBool(true) // opt contains the value true
For types with validationk the NewOptFoo constructor instead returns (optType, error). It will never return an instance that wraps an illegal value, and there is no way for code outside of this package to construct such an instance (without using tricks like reflection).
opt, err := NewOptIntGreaterThanZero(3) // err is nil, opt contains 3 opt, err := NewOptIntGreaterThanZero(-3) // err is non-nil, opt is empty
Converting Opt types to or from strings ¶
If the wrapped type is not string, there is also a NewOptFooFromString(string) constructor to convert a string to this type. Again, if it is impossible for this conversion to fail, the constructor returns just an instance; if it can fail, it returns (optType, error). Since Opt types can always be empty, an empty string is always valid.
opt, err := NewOptBoolFromString("") // err is nil, opt is empty opt, err := NewOptBoolFromString("true") // err is nil, opt contains the value true opt, err := NewOptBoolFromString("bad") // err is non-nil, opt is empty
The UnmarshalText method (encoding.TextUnmarshaler) behaves identically to the ...FromString constructor. The encoding.TextUnmarshaler interface is recognized by many packages that do file parsing (such as gcfg), so all such packages will automatically implement the appropriate behavior for these types.
var opt OptBool err := opt.UnmarshalText([]byte("true")) // err is nil, opt contains the value true
The String and MarshalText methods do the reverse, returning an empty string if empty or else a string that is in the same format used by the parsing methods.
Converting Opt types to or from JSON ¶
These types also implement the json.Marshaler and json.Unmarshaler interfaces. An empty value always corresponds to a JSON null; otherwise, the JSON mapping depends on the type, so for instance a non-empty OptBool is always a JSON boolean.
Opt types with multiple values ¶
Some types, such as OptStringList, represent a collection of values. How this translates to a text format depends on the type. The standard behavior is that if a parsing framework uses encoding.TextUnmarshaler, it assumes that it will call UnmarshalText repeatedly for each value with the same name (as gcfg does). In a context where it is not possible to have more than one value with the same name (such as environment variables), the type may implement the optional SingleValueTextUnmarshaler interface to indicate that an alternate format should be used, such as a comma-delimited list.
Reading from files or variables ¶
Two common use cases are parsing a configuration file and reading values from environment variables.
The former can be done with any package that can interact with types via the encoding.TextUnmarshaler interface, such as https://github.com/launchdarkly/gcfg. Attempting to set a field's string value with this interface causes parsing to fail if the string format is not valid for the field's type, for example if a string that is not an absolute URL is specified for a field of type OptURLAbsolute.
The VarReader type adapts the same functionality, but reads values from environment variables (or from a name-value map). You can read values one at a time, specifying each variable name, or you can use field tags to specify the variable names directly within the struct.
Since field names that do not appear in the parsed file or in the environment variables are not modified, you can use both of these methods together: that is, read a configuration file that sets some fields in a struct, and then allow environment variables to override other fields.
There is a limited ability to enforce that a field must have a value. Go has no way to prevent a field or variable from being declared with a zero value for its type, so a struct with a required field could always exist in an invalid state, but the Validate() function and VarReader will both raise errors if a field that has a ",required" field tag was not set.
Index ¶
- func StringOrElse(value SingleValue, orElseString string) string
- type Error
- type OptBool
- func (o OptBool) GetOrElse(orElseValue bool) bool
- func (o OptBool) IsDefined() bool
- func (o OptBool) MarshalJSON() ([]byte, error)
- func (o OptBool) MarshalText() ([]byte, error)
- func (o OptBool) String() string
- func (o *OptBool) UnmarshalJSON(data []byte) error
- func (o *OptBool) UnmarshalText(data []byte) error
- type OptDuration
- func (o OptDuration) GetOrElse(orElseValue time.Duration) time.Duration
- func (o OptDuration) IsDefined() bool
- func (o OptDuration) MarshalJSON() ([]byte, error)
- func (o OptDuration) MarshalText() ([]byte, error)
- func (o OptDuration) String() string
- func (o *OptDuration) UnmarshalJSON(data []byte) error
- func (o *OptDuration) UnmarshalText(data []byte) error
- type OptDurationNonNegative
- func (o OptDurationNonNegative) GetOrElse(orElseValue time.Duration) time.Duration
- func (o OptDurationNonNegative) IsDefined() bool
- func (o OptDurationNonNegative) MarshalJSON() ([]byte, error)
- func (o OptDurationNonNegative) MarshalText() ([]byte, error)
- func (o OptDurationNonNegative) String() string
- func (o *OptDurationNonNegative) UnmarshalJSON(data []byte) error
- func (o *OptDurationNonNegative) UnmarshalText(data []byte) error
- type OptFloat64
- func (o OptFloat64) GetOrElse(orElseValue float64) float64
- func (o OptFloat64) IsDefined() bool
- func (o OptFloat64) MarshalJSON() ([]byte, error)
- func (o OptFloat64) MarshalText() ([]byte, error)
- func (o OptFloat64) String() string
- func (o *OptFloat64) UnmarshalJSON(data []byte) error
- func (o *OptFloat64) UnmarshalText(data []byte) error
- type OptInt
- func (o OptInt) GetOrElse(orElseValue int) int
- func (o OptInt) IsDefined() bool
- func (o OptInt) MarshalJSON() ([]byte, error)
- func (o OptInt) MarshalText() ([]byte, error)
- func (o OptInt) String() string
- func (o *OptInt) UnmarshalJSON(data []byte) error
- func (o *OptInt) UnmarshalText(data []byte) error
- type OptIntGreaterThanZero
- func (o OptIntGreaterThanZero) GetOrElse(orElseValue int) int
- func (o OptIntGreaterThanZero) IsDefined() bool
- func (o OptIntGreaterThanZero) MarshalJSON() ([]byte, error)
- func (o OptIntGreaterThanZero) MarshalText() ([]byte, error)
- func (o OptIntGreaterThanZero) String() string
- func (o *OptIntGreaterThanZero) UnmarshalJSON(data []byte) error
- func (o *OptIntGreaterThanZero) UnmarshalText(data []byte) error
- type OptString
- func (o OptString) GetOrElse(orElseValue string) string
- func (o OptString) IsDefined() bool
- func (o OptString) MarshalJSON() ([]byte, error)
- func (o OptString) MarshalText() ([]byte, error)
- func (o OptString) String() string
- func (o *OptString) UnmarshalJSON(data []byte) error
- func (o *OptString) UnmarshalText(data []byte) error
- type OptStringList
- func (o OptStringList) IsDefined() bool
- func (o OptStringList) MarshalJSON() ([]byte, error)
- func (o OptStringList) MarshalText() ([]byte, error)
- func (o OptStringList) String() string
- func (o *OptStringList) UnmarshalJSON(data []byte) error
- func (o *OptStringList) UnmarshalText(data []byte) error
- func (o OptStringList) Values() []string
- type OptStringNonEmpty
- func (o OptStringNonEmpty) GetOrElse(orElseValue string) string
- func (o OptStringNonEmpty) IsDefined() bool
- func (o OptStringNonEmpty) MarshalJSON() ([]byte, error)
- func (o OptStringNonEmpty) MarshalText() ([]byte, error)
- func (o OptStringNonEmpty) String() string
- func (o *OptStringNonEmpty) UnmarshalJSON(data []byte) error
- func (o *OptStringNonEmpty) UnmarshalText(data []byte) error
- type OptURL
- type OptURLAbsolute
- func (o OptURLAbsolute) Get() *url.URL
- func (o OptURLAbsolute) IsDefined() bool
- func (o OptURLAbsolute) MarshalJSON() ([]byte, error)
- func (o OptURLAbsolute) MarshalText() ([]byte, error)
- func (o OptURLAbsolute) String() string
- func (o *OptURLAbsolute) UnmarshalJSON(data []byte) error
- func (o *OptURLAbsolute) UnmarshalText(data []byte) error
- type SingleValue
- type Validation
- type ValidationAggregateError
- type ValidationError
- type ValidationPath
- type ValidationResult
- type VarReader
- func (r *VarReader) AddError(path ValidationPath, e error)
- func (r *VarReader) FindPrefixedValues(prefix string) map[string]string
- func (r *VarReader) Read(varName string, target interface{}) bool
- func (r *VarReader) ReadRequired(varName string, target interface{}) bool
- func (r *VarReader) ReadStruct(target interface{}, recursive bool)
- func (r VarReader) Result() ValidationResult
- func (r *VarReader) WithVarNamePrefix(prefix string) *VarReader
- func (r *VarReader) WithVarNameSuffix(suffix string) *VarReader
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func StringOrElse ¶
func StringOrElse(value SingleValue, orElseString string) string
StringOrElse is a shortcut for calling String() on a value if it is defined, or returning an alternative string if it is empty.
StringOrElse(NewOptBool(true), "undefined") // == "true" StringOrElse(OptBool{}, "undefined") // == "undefined"
Types ¶
type OptBool ¶
type OptBool struct {
// contains filtered or unexported fields
}
OptBool represents an optional boolean parameter.
In Go, an unset boolean normally defaults to false. This type allows application code to distinguish between false and the absence of a value, in case some other default behavior is desired.
When setting this value from a string representation, the following case-insensitive string values are allowed for true/false: "true"/"false", "0"/"1", "yes"/"no". An empty string value is converted to an empty OptBool{}.
Converting to a string always produces "true", "false", or "".
When converting to or from JSON, the value must be either a JSON null or a JSON boolean.
See the package documentation for the general contract for methods that have no specific documentation here.
func NewOptBool ¶
func NewOptBoolFromString ¶
func (OptBool) MarshalJSON ¶
func (OptBool) MarshalText ¶
func (*OptBool) UnmarshalJSON ¶
func (*OptBool) UnmarshalText ¶
type OptDuration ¶
type OptDuration struct {
// contains filtered or unexported fields
}
OptDuration represents an optional time.Duration parameter. Any time.Duration value is allowed; if you want to allow only positive values (which is usually desirable), use OptDurationNonNegative.
When setting this value from a string representation, it uses time.ParseDuration, so the allowed formats include "9ms" (milliseconds), "9s" (seconds), "9m" (minutes), or combinations such as "1m30s". Converting to a string uses similar rules, as implemented by Duration.String().
When converting to or from JSON, an empty value is null, and all other values are strings.
See the package documentation for the general contract for methods that have no specific documentation here.
func NewOptDuration ¶
func NewOptDuration(value time.Duration) OptDuration
func NewOptDurationFromString ¶
func NewOptDurationFromString(s string) (OptDuration, error)
func (OptDuration) GetOrElse ¶
func (o OptDuration) GetOrElse(orElseValue time.Duration) time.Duration
func (OptDuration) IsDefined ¶
func (o OptDuration) IsDefined() bool
func (OptDuration) MarshalJSON ¶
func (o OptDuration) MarshalJSON() ([]byte, error)
func (OptDuration) MarshalText ¶
func (o OptDuration) MarshalText() ([]byte, error)
func (OptDuration) String ¶
func (o OptDuration) String() string
func (*OptDuration) UnmarshalJSON ¶
func (o *OptDuration) UnmarshalJSON(data []byte) error
func (*OptDuration) UnmarshalText ¶
func (o *OptDuration) UnmarshalText(data []byte) error
type OptDurationNonNegative ¶
type OptDurationNonNegative struct {
// contains filtered or unexported fields
}
OptDurationNonNegative represents an optional time.Duration parameter which, if defined, must be greater than or equal to zero.
This is the same as OptDuration, but with additional validation for the constructor and unmarshalers. It is impossible (except with reflection) for code outside this package to construct an instance of this type with a defined value that is negative.
See the package documentation for the general contract for methods that have no specific documentation here.
func NewOptDurationNonNegative ¶
func NewOptDurationNonNegative(value time.Duration) (OptDurationNonNegative, error)
func NewOptDurationNonNegativeFromString ¶
func NewOptDurationNonNegativeFromString(s string) (OptDurationNonNegative, error)
func (OptDurationNonNegative) GetOrElse ¶
func (o OptDurationNonNegative) GetOrElse(orElseValue time.Duration) time.Duration
func (OptDurationNonNegative) IsDefined ¶
func (o OptDurationNonNegative) IsDefined() bool
func (OptDurationNonNegative) MarshalJSON ¶
func (o OptDurationNonNegative) MarshalJSON() ([]byte, error)
func (OptDurationNonNegative) MarshalText ¶
func (o OptDurationNonNegative) MarshalText() ([]byte, error)
func (OptDurationNonNegative) String ¶
func (o OptDurationNonNegative) String() string
func (*OptDurationNonNegative) UnmarshalJSON ¶
func (o *OptDurationNonNegative) UnmarshalJSON(data []byte) error
func (*OptDurationNonNegative) UnmarshalText ¶
func (o *OptDurationNonNegative) UnmarshalText(data []byte) error
type OptFloat64 ¶ added in v1.1.0
type OptFloat64 struct {
// contains filtered or unexported fields
}
OptFloat64 represents an optional float64 parameter.
In Go, an unset float64 normally defaults to zero. This type allows application code to distinguish between zero and the absence of a value, in case some other default behavior is desired.
When converting to or from JSON, the value must be either a JSON null or a JSON number.
See the package documentation for the general contract for methods that have no specific documentation here.
func NewOptFloat64 ¶ added in v1.1.0
func NewOptFloat64(value float64) OptFloat64
func NewOptFloat64FromString ¶ added in v1.1.0
func NewOptFloat64FromString(s string) (OptFloat64, error)
func (OptFloat64) GetOrElse ¶ added in v1.1.0
func (o OptFloat64) GetOrElse(orElseValue float64) float64
func (OptFloat64) IsDefined ¶ added in v1.1.0
func (o OptFloat64) IsDefined() bool
func (OptFloat64) MarshalJSON ¶ added in v1.1.0
func (o OptFloat64) MarshalJSON() ([]byte, error)
func (OptFloat64) MarshalText ¶ added in v1.1.0
func (o OptFloat64) MarshalText() ([]byte, error)
func (OptFloat64) String ¶ added in v1.1.0
func (o OptFloat64) String() string
func (*OptFloat64) UnmarshalJSON ¶ added in v1.1.0
func (o *OptFloat64) UnmarshalJSON(data []byte) error
func (*OptFloat64) UnmarshalText ¶ added in v1.1.0
func (o *OptFloat64) UnmarshalText(data []byte) error
type OptInt ¶
type OptInt struct {
// contains filtered or unexported fields
}
OptInt represents an optional int parameter.
In Go, an unset int normally defaults to zero. This type allows application code to distinguish between zero and the absence of a value, in case some other default behavior is desired.
When converting to or from JSON, the value must be either a JSON null or a JSON number that is an integer.
See the package documentation for the general contract for methods that have no specific documentation here.
func NewOptIntFromString ¶
func (OptInt) MarshalJSON ¶
func (OptInt) MarshalText ¶
func (*OptInt) UnmarshalJSON ¶
func (*OptInt) UnmarshalText ¶
type OptIntGreaterThanZero ¶
type OptIntGreaterThanZero struct {
// contains filtered or unexported fields
}
OptIntGreaterThanZero represents an optional int parameter which, if defined, must be greater than zero.
This is the same as OptInt, but with additional validation for the constructor and unmarshalers. It is impossible (except with reflection) for code outside this package to construct an instance of this type with a defined value that is zero or negative.
See the package documentation for the general contract for methods that have no specific documentation here.
func NewOptIntGreaterThanZero ¶
func NewOptIntGreaterThanZero(value int) (OptIntGreaterThanZero, error)
func NewOptIntGreaterThanZeroFromString ¶
func NewOptIntGreaterThanZeroFromString(s string) (OptIntGreaterThanZero, error)
func (OptIntGreaterThanZero) GetOrElse ¶
func (o OptIntGreaterThanZero) GetOrElse(orElseValue int) int
func (OptIntGreaterThanZero) IsDefined ¶
func (o OptIntGreaterThanZero) IsDefined() bool
func (OptIntGreaterThanZero) MarshalJSON ¶
func (o OptIntGreaterThanZero) MarshalJSON() ([]byte, error)
func (OptIntGreaterThanZero) MarshalText ¶
func (o OptIntGreaterThanZero) MarshalText() ([]byte, error)
func (OptIntGreaterThanZero) String ¶
func (o OptIntGreaterThanZero) String() string
func (*OptIntGreaterThanZero) UnmarshalJSON ¶
func (o *OptIntGreaterThanZero) UnmarshalJSON(data []byte) error
func (*OptIntGreaterThanZero) UnmarshalText ¶
func (o *OptIntGreaterThanZero) UnmarshalText(data []byte) error
type OptString ¶
type OptString struct {
// contains filtered or unexported fields
}
OptString represents an optional string parameter.
In Go, an unset string normally defaults to "". This type allows application code to distinguish between "" and the absence of a value, in case some other default behavior is desired.
When converting to a string, an undefined value becomes "". When converting from a string, any string becomes a defined value even if it is "". If you want to treat "" as an undefined value, use OptStringNonEmpty.
When converting to or from JSON, the value must be either a JSON null or a JSON string.
See the package documentation for the general contract for methods that have no specific documentation here.
func NewOptString ¶
func (OptString) MarshalJSON ¶
func (OptString) MarshalText ¶
func (*OptString) UnmarshalJSON ¶
func (*OptString) UnmarshalText ¶
type OptStringList ¶
type OptStringList struct {
// contains filtered or unexported fields
}
OptStringList represents an optional parameter that is a slice of string values. A nil slice is equivalent to an empty OptStringList{}, and is not the same as a zero-length slice.
In a configuration file, this can be represented either as a single comma-delimited string or as multiple parameters with the same name. In environment variables, it is always represented as a single comma-delimited string since there can be only one value for each variable name.
When converting from JSON, the value can be null, a single string, or an array of strings. When converting to JSON, the value will be null or an array of strings.
String slices are always copied when getting or setting this type, to ensure that configuration structs do not expose mutable data.
See the package documentation for the general contract for methods that have no specific documentation here.
func NewOptStringList ¶
func NewOptStringList(values []string) OptStringList
func NewOptStringListFromString ¶
func NewOptStringListFromString(s string) OptStringList
func (OptStringList) IsDefined ¶
func (o OptStringList) IsDefined() bool
func (OptStringList) MarshalJSON ¶
func (o OptStringList) MarshalJSON() ([]byte, error)
func (OptStringList) MarshalText ¶
func (o OptStringList) MarshalText() ([]byte, error)
func (OptStringList) String ¶
func (o OptStringList) String() string
func (*OptStringList) UnmarshalJSON ¶
func (o *OptStringList) UnmarshalJSON(data []byte) error
func (*OptStringList) UnmarshalText ¶
func (o *OptStringList) UnmarshalText(data []byte) error
func (OptStringList) Values ¶
func (o OptStringList) Values() []string
type OptStringNonEmpty ¶
type OptStringNonEmpty struct {
// contains filtered or unexported fields
}
OptStringNonEmpty represents an optional string parameter which, if defined, must be non-empty.
This is the same as OptString, but with additional validation for the constructor and unmarshalers. It is impossible (except with reflection) for code outside this package to construct an instance of this type with a defined value that is an empty string.
Since an empty string is already the standard way to indicate an empty value for Opt types in this package, NewOptStringNonEmpty("") and UnmarshalText([]byte("")) cannot fail; they simply produce an empty value. However, JSON conversion is different: an empty value is a JSON null, not a JSON "".
The semantics of this type are mostly the same as a regular Go string, since there is no need to distinguish between an empty string value and the absence of a value. It only exists for feature parity, so you can use helper methods like StringOrElse. ReqStringNonEmpty may be more useful.
See the package documentation for the general contract for methods that have no specific documentation here.
func NewOptStringNonEmpty ¶
func NewOptStringNonEmpty(value string) OptStringNonEmpty
func (OptStringNonEmpty) GetOrElse ¶
func (o OptStringNonEmpty) GetOrElse(orElseValue string) string
func (OptStringNonEmpty) IsDefined ¶
func (o OptStringNonEmpty) IsDefined() bool
func (OptStringNonEmpty) MarshalJSON ¶
func (o OptStringNonEmpty) MarshalJSON() ([]byte, error)
func (OptStringNonEmpty) MarshalText ¶
func (o OptStringNonEmpty) MarshalText() ([]byte, error)
func (OptStringNonEmpty) String ¶
func (o OptStringNonEmpty) String() string
func (*OptStringNonEmpty) UnmarshalJSON ¶
func (o *OptStringNonEmpty) UnmarshalJSON(data []byte) error
func (*OptStringNonEmpty) UnmarshalText ¶
func (o *OptStringNonEmpty) UnmarshalText(data []byte) error
type OptURL ¶
type OptURL struct {
// contains filtered or unexported fields
}
OptURL represents an optional parameter which, if present, must be a valid URL.
There is no additional validation, so the URL could be absolute or relative; see OptURL. The value is stored as a *URL pointer, whose value is always copied when accessed; a nil pointer indicates the lack of a value (the same as OptURL{}).
Converting to or from a string uses the standard behavior for URL.String() and url.Parse().
When converting to or from JSON, the value must be either a JSON null or a JSON string.
See the package documentation for the general contract for methods that have no specific documentation here.
func NewOptURLFromString ¶
func (OptURL) MarshalJSON ¶
func (OptURL) MarshalText ¶
func (*OptURL) UnmarshalJSON ¶
func (*OptURL) UnmarshalText ¶
type OptURLAbsolute ¶
type OptURLAbsolute struct {
// contains filtered or unexported fields
}
OptURLAbsolute represents an optional URL parameter which, if defined, must be an absolute URL.
This is the same as OptURL, but with additional validation for the constructor and unmarshalers. It is impossible (except with reflection) for code outside this package to construct an instance of this type with a defined value that is not a valid absolute URL.
See the package documentation for the general contract for methods that have no specific documentation here.
func NewOptURLAbsolute ¶
func NewOptURLAbsolute(url *url.URL) (OptURLAbsolute, error)
func NewOptURLAbsoluteFromString ¶
func NewOptURLAbsoluteFromString(urlString string) (OptURLAbsolute, error)
func (OptURLAbsolute) Get ¶
func (o OptURLAbsolute) Get() *url.URL
func (OptURLAbsolute) IsDefined ¶
func (o OptURLAbsolute) IsDefined() bool
func (OptURLAbsolute) MarshalJSON ¶
func (o OptURLAbsolute) MarshalJSON() ([]byte, error)
func (OptURLAbsolute) MarshalText ¶
func (o OptURLAbsolute) MarshalText() ([]byte, error)
func (OptURLAbsolute) String ¶
func (o OptURLAbsolute) String() string
func (*OptURLAbsolute) UnmarshalJSON ¶
func (o *OptURLAbsolute) UnmarshalJSON(data []byte) error
func (*OptURLAbsolute) UnmarshalText ¶
func (o *OptURLAbsolute) UnmarshalText(data []byte) error
type SingleValue ¶
type SingleValue interface { fmt.Stringer encoding.TextMarshaler json.Marshaler // IsDefined returns true if the value is defined, or false if it is empty. IsDefined() bool }
SingleValue is the common interface for all types in this package that represent a single optional or required value.
All such types can be in a defined or an empty state, and can be converted to text or JSON.
type Validation ¶
type Validation interface { // Validate is called by the validation logic to check the validity of this value. Validate() ValidationResult }
Validation is an optional interface for any type that you wish to have custom validation behavior when calling Validate(interface{}) or ValidateFields(interface{}).
type ValidationAggregateError ¶
type ValidationAggregateError []ValidationError
ValidationAggregateError is the type returned by ValidationResult.GetError() if there were multiple errors.
func (ValidationAggregateError) Error ¶
func (v ValidationAggregateError) Error() string
Error for ValidationAggregateError returns a comma-delimited list of error descriptions.
func (ValidationAggregateError) String ¶
func (v ValidationAggregateError) String() string
String is equivalent to Error.
type ValidationError ¶
type ValidationError struct { Path ValidationPath Err error }
ValidationError represents an invalid value condition for a parsed value or a struct field.
func (ValidationError) Error ¶
func (v ValidationError) Error() string
Error returns the error description, including the path if specified.
func (ValidationError) String ¶
func (v ValidationError) String() string
String is equivalent to Error.
type ValidationPath ¶
type ValidationPath []string
ValidationPath represents a field name or nested series of field names for a ValidationError.
For instance, if you call Validate on a struct whose field A is a struct that has an invalid field B, the path for the error would be ValidationPath{"A", "B"}.
func (ValidationPath) String ¶
func (p ValidationPath) String() string
String converts the path to a dot-delimited string.
type ValidationResult ¶
type ValidationResult struct {
// contains filtered or unexported fields
}
ValidationResult accumulates errors from field validation.
func ValidateStruct ¶
func ValidateStruct(value interface{}, recursive bool) ValidationResult
ValidateStruct checks whether all of a struct's exported fields are valid according to the tag-based required field rule. If the recursive parameter is true, then ValidateStruct will be called recursively on any embedded structs in exported fields.
The required field rule is that if any field has a "conf:" field tag that includes ",required", it must have a value that is not the zero value for that type. Therefore, any required field that uses an Opt type must be in the "defined" state (since its zero value is the "empty" state); a required int field must be non-zero; a required string field must not be ""; etc.
The returned ValidationResult can contain any number of errors.
Calling ValidateStruct with a parameter that is not a struct or struct pointer returns an error result.
func (*ValidationResult) AddAll ¶
func (r *ValidationResult) AddAll(prefixPath ValidationPath, other ValidationResult)
AddAll adds all errors from another result, optionally adding a prefix to each path.
func (*ValidationResult) AddError ¶
func (r *ValidationResult) AddError(path ValidationPath, e error)
AddError adds a ValidationError to the result.
func (ValidationResult) Errors ¶
func (r ValidationResult) Errors() []ValidationError
Errors returns a copied slice of all errors in this result.
func (ValidationResult) GetError ¶
func (r ValidationResult) GetError() error
GetError returns a single error representing all errors in the result, or nil if there were none.
If not nil, the return value will be either a ValidationError or a ValidationAggregateError.
func (ValidationResult) OK ¶
func (r ValidationResult) OK() bool
OK returns true if there are no errors.
type VarReader ¶
type VarReader struct {
// contains filtered or unexported fields
}
VarReader reads string values from named variables, such as environment variables, and translates them into values of any supported type. It accumulates errors as it goes.
The supported types are any type that implements TextUnmarshaler (which includes all of the Opt and Req types defined in this package), and also the primitive types bool, int, float64, and string.
You may specify the variable name for each target value programmatically, or use struct field tags as described in ReadStruct(), or both.
func NewVarReaderFromEnvironment ¶
func NewVarReaderFromEnvironment() *VarReader
NewVarReaderFromEnvironment creates a VarReader that reads from environment variables.
func NewVarReaderFromValues ¶
NewVarReaderFromValues creates a VarReader that reads from the specified name-value map.
func (*VarReader) AddError ¶
func (r *VarReader) AddError(path ValidationPath, e error)
AddError records an error in the VarReader's result.
func (*VarReader) FindPrefixedValues ¶
FindPrefixedValues finds all named values in the VarReader that have the specified name prefix, and returns a name-value map of only those, with the prefixes removed.
r := NewVarReaderFromValues(map[string]string{"a": "1", "b_x": "2", "b_y": "3"}) values := r.FindPrefixedValues("b_") // values == { "x": "2", "y": "3" }
func (*VarReader) Read ¶
Read attempts to read an environment variable into a target value.
The varName may be modified by any previous calls to WithVarNamePrefix or WithVarNameSuffix.
If the variable exists, Read attempts to set the target value as follows: through the TextMarshaler interface, if that is implemented; otherwise, if it is a supported built-in type, it uses the corresponding Opt type (such as OptBool) to parse the value. If the type is not supported, it records an error.
If the variable does not exist, the method does nothing; it does not modify the target value. Use ReadRequired or ReadStruct, or call Validate afterward, if you want missing values to be treated as errors.
The method returns true if the variable was found (regardless of whether unmarshaling succeeded) or false if it was not found.
func (*VarReader) ReadRequired ¶
ReadRequired is the same as Read, except that if the variable was not found, it records an error for that variable name.
func (*VarReader) ReadStruct ¶
ReadStruct uses reflection to populate any exported fields of the target struct that have a tag of `conf:"VAR_NAME"`. The behavior for each of these fields is the same as for Read(), unless you specify `conf:"VAR_NAME,required"` in which case it behaves like ReadRequired(). If the recursive parameter is true, then ReadStruct will be called recursively on any embedded structs.
type myStruct struct { MyOptBool OptBool `conf:"VAR1"` MyPrimitiveBool bool `conf:"VAR2"` MyRequiredBool bool `conf:"VAR3,required"` } s := myStruct{} r := NewVarReaderFromEnvironment() r.ReadStruct(&myStruct)
In the above example, each field behaves slightly differently. MyOptBool can have three states: undefined (VAR1 was not set), true, or false. MyPrimitiveBool is a simple bool so there is no way to distinguish between its default value and "not set". MyRequiredBool is a simple bool but will cause VarReader to log an error if the variable is not set.
func (VarReader) Result ¶
func (r VarReader) Result() ValidationResult
Result returns a ValidationResult containing all of the errors encountered so far.
func (*VarReader) WithVarNamePrefix ¶
WithVarNamePrefix returns a new VarReader based on the current one, which accumulates errors in the same ValidationResult, but with the given prefix added to all variable names.
r0 := NewVarReaderFromValues(map[string]string{"b_x": "2", "b_y": "3"}) r1 := r.WithVarNamePrefix("b_") r1.Read(&x, "x") // x is set to "2"
func (*VarReader) WithVarNameSuffix ¶
WithVarNameSuffix returns a new VarReader based on the current one, which accumulates errors in the same ValidationResult, but with the given suffix added to all variable names.
r0 := NewVarReaderFromValues(map[string]string{"a_x": "2", "b_x": "3"}) r1 := r.WithVarNameSuffix("_x") r1.Read(&b, "b") // b is set to "3"
Source Files ¶
- errors.go
- functions.go
- interfaces.go
- opt_bool.go
- opt_duration.go
- opt_duration_non_negative.go
- opt_float64.go
- opt_int.go
- opt_int_greater_than_zero.go
- opt_string.go
- opt_string_list.go
- opt_string_nonempty.go
- opt_url.go
- opt_url_absolute.go
- package_info.go
- reflection.go
- validate.go
- validation_result.go
- var_reader.go