Documentation
¶
Overview ¶
Package gonfig is a flexible and extensible configuration library designed to simplify working with application settings. It supports loading configurations from environment variables, command-line flags, and various configuration file formats. Additionally, it offers an easy way to extend support for new formats. One of its key features is the ability to replace or customize components, such as using `spf13/pflag` instead of the standard `flag` package from the Go standard library.
This library simplifies configuration management, making it easy to define, override, and merge settings in your applications.
Index ¶
- Constants
- func False() *bool
- func Load(v any, options ...LoaderOption) error
- func LoadEnvs(envs map[string]any, dest any) error
- func PrepareEnvs(envs []string, prefix string) map[string]any
- func PrepareFlags(flagSet *pflag.FlagSet, dest any) error
- func Ptr[E comparable](v E) *E
- func ReflectFieldsOf(in any, options ReflectOptions) iter.Seq2[*ReflectValue, error]
- func SetDefaults(dest any) error
- func True() *bool
- func UsageOfEnvs(dest any, opts ...EnvUsageOption) string
- func ValidateRequiredFields(input any) error
- type Config
- type EnvUsageOption
- type ErrMissingField
- type Error
- type LoaderOption
- func WithConfig(handler func(*Config)) LoaderOption
- func WithCustomExit(exit func(int)) LoaderOption
- func WithCustomParser(p Parser) LoaderOption
- func WithCustomParserInit(fabric ParserInit) LoaderOption
- func WithDefaults(keyTag string, defaults map[string]any) LoaderOption
- func WithJSONLoader(options ...fileLoaderOption) LoaderOption
- func WithOptions(options any) LoaderOption
- func WithTOMLLoader(options ...fileLoaderOption) LoaderOption
- func WithYAMLLoader(options ...fileLoaderOption) LoaderOption
- type Parser
- type ParserConfigSetter
- type ParserInit
- type ParserPreparer
- type ParserType
- type ReflectOptions
- type ReflectValue
- type TagOptions
Constants ¶
const ( // ErrTestExit is an error indicating that a test process should exit. // This error can be used in testing scenarios where an explicit termination // or exit condition needs to be simulated. ErrTestExit = Error("exit code") // ErrPrepareDecoder is returned when the decoder initialization fails. // This error typically occurs when setting up a configuration decoder // encounters an issue, such as invalid decoder settings or unsupported types. ErrPrepareDecoder = Error("could not prepare decoder") // ErrDecode is returned when decoding a configuration fails. // This error indicates that the process of converting configuration data // into the expected structure was unsuccessful, possibly due to type mismatches // or missing required fields. ErrDecode = Error("could not decode") )
const ( // ParserJSON is the identifier for the JSON configuration parser. ParserJSON ParserType = "json-loader" // ParserYAML is the identifier for the YAML configuration parser. ParserYAML ParserType = "yaml-loader" // ParserTOML is the identifier for the TOML configuration parser. ParserTOML ParserType = "toml-loader" // ErrCantOpen is returned when the file cannot be opened. ErrCantOpen Error = "could not open" // ErrCantClose is returned when the file cannot be closed. ErrCantClose Error = "could not close" // ErrCantParse is returned when the file cannot be parsed. ErrCantParse Error = "could not parse" // ErrUnknownFileTypeParser is returned when ParserType is not known. ErrUnknownFileTypeParser Error = "unknown parser" )
const ( // FlagB64 indicating base64 encoding for byte slices. FlagB64 = "b64" // FlagHEX indicating hexadecimal encoding for byte slices. FlagHEX = "hex" // FlagTag is tag used to specify the flag name for a field. FlagTag = "flag" // FlagTagUsage is tag used to specify the usage description for a flag. FlagTagUsage = "usage" // FlagSetName is name of the flag set for the command-line interface. FlagSetName = "flags" )
const ( // ErrExpectStruct is returned when a struct field is expected but the provided value is not a struct. ErrExpectStruct = Error("expect struct field") // ErrExpectPointer is returned when a pointer is expected but the provided value is not a pointer. ErrExpectPointer = Error("expect pointer") )
Error constants for reflection-related operations.
const ErrEnvSetterBreak = Error("break")
ErrEnvSetterBreak is a predefined constant of type Error used to indicate an error or a condition where processing should stop.
const RequiredTag = "required"
RequiredTag defines the struct tag key used to specify if a field is required. When parsing struct tags, this key is used to indicate that a field must be provided (e.g., from an environment variable, configuration, or command-line argument).
If a field is tagged with `required:"true"`, it signifies that the field is mandatory. Example usage: `required:"true"`
This tag is commonly used for validation purposes to ensure necessary fields are populated.
Variables ¶
This section is empty.
Functions ¶
func False ¶ added in v0.3.0
func False() *bool
False returns a pointer to a boolean value set to false. Like True, it uses the Ptr function to generate a pointer to the boolean literal false.
Example usage:
b := False() // Returns *bool pointing to false
func Load ¶ added in v0.4.0
func Load(v any, options ...LoaderOption) error
Load initializes a new Parser with default settings and applies optional LoaderOptions. It then loads the provided target structure using the configured loader service.
This function is a shorthand for creating a new Parser with default Config and calling Load on it.
Parameters: - v: The target structure where the configuration will be loaded. - options: Optional LoaderOptions to customize the behavior of the parser.
Returns: - An error if the loading process fails, otherwise nil.
func LoadEnvs ¶
LoadEnvs decodes the provided environment variables map into the destination object. It uses mapstructure to map the environment variables to the fields of the destination object based on the "env" tag. It returns an error if decoding fails.
func PrepareEnvs ¶
PrepareEnvs prepares a map from the given environment variable slice. It filters and parses the environment variables based on the provided prefix. The resulting map has a nested structure based on the environment variable names, using the specified delimiter for nesting.
func PrepareFlags ¶
PrepareFlags prepares flags for the given flag set based on the fields of the destination struct. It inspects the struct fields and creates corresponding flags in the flag set using the specified tags. Returns an error if the preparation of flags fails.
func Ptr ¶ added in v0.3.0
func Ptr[E comparable](v E) *E
Ptr takes a value of any comparable type and returns a pointer to that value. This function is useful for quickly obtaining a pointer to a literal or value, especially in situations where you need a pointer for use in data structures or APIs.
Example usage:
i := Ptr(42) // Returns a pointer to an integer 42 s := Ptr("hello") // Returns a pointer to the string "hello"
E must be a type that supports the comparable constraint.
func ReflectFieldsOf ¶ added in v0.3.0
func ReflectFieldsOf(in any, options ReflectOptions) iter.Seq2[*ReflectValue, error]
ReflectFieldsOf returns an iterator that reflects over all fields of a given struct (or struct-like type). `in` must be a pointer to a struct, and `options` controls which fields are included in the reflection. The iterator yields `*ReflectValue` for each field, or an error if a problem occurs.
func SetDefaults ¶
SetDefaults sets default values to the fields of the provided struct. It recursively processes struct fields and assigns default values based on the "default" tag. It supports setting values for basic types, slices, arrays, maps, and custom unmarshalling for types implementing encoding.TextUnmarshaler. Returns an error if the destination is not a pointer or if setting a default value fails.
func True ¶ added in v0.3.0
func True() *bool
True returns a pointer to a boolean value set to true. It utilizes the Ptr function to quickly generate a pointer for the boolean literal true.
Example usage:
b := True() // Returns *bool pointing to true
func UsageOfEnvs ¶ added in v0.2.0
func UsageOfEnvs(dest any, opts ...EnvUsageOption) string
UsageOfEnvs generates a human-readable string that describes the environment variables expected by a given structure, based on struct tags (e.g., "env" and "usage").
Parameters:
- dest: A pointer to a struct that defines the expected environment variables. The struct fields must use the "env" tag to define environment variable names and the "usage" tag to describe their purpose.
- opts: Optional EnvUsageOption(s) to configure behavior, such as adding a prefix to environment variable names.
Returns:
- A string describing the environment variables and their usage, or an empty string if the input is not valid.
The function ensures that the input is a pointer to a struct. It traverses the struct fields, generating usage information based on the tags. If a struct field is another struct, it recurses into the nested fields.
nolint:funlen
func ValidateRequiredFields ¶
ValidateRequiredFields checks whether all fields marked with the "required" tag are set. It traverses the provided struct, including nested structs, to identify any missing required fields. It returns detailed error messages for all missing fields.
Types ¶
type Config ¶
type Config struct { SkipDefaults bool // SkipDefaults set to true will not load config from 'default' tag. SkipEnv bool // SkipEnv set to true will not load config from environment variables. SkipFlags bool // SkipFlags set to true will not load config from flag parameters. EnvPrefix string // EnvPrefix for environment variables. // Envs hold the environment variable from which envs will be parsed. // By default, is nil and then os.Environ() will be used. Envs []string // Args hold the command-line arguments from which flags will be parsed. // By default, is nil and then os.Args will be used. // Unless loader.Flags() will be explicitly parsed by the user. Args []string }
Config holds the configuration options for loading settings using various parsers such as defaults, environment variables, and command-line flags.
Fields: - SkipDefaults: If true, the loader will skip loading configurations from the 'default' tags in struct fields. - SkipEnv: If true, the loader will skip loading configurations from environment variables. - SkipFlags: If true, the loader will skip loading configurations from command-line flags.
EnvPrefix: A string that specifies a prefix for filtering environment variables. Only variables starting with this prefix will be considered.
LoaderOrder: Defines the order in which the parsers (defaults, env, flags) will be executed. This allows prioritization of certain parsers over others.
Envs: A slice of environment variables to be used for parsing. If left nil, the loader will default to using `os.Environ()`.
Args: A slice of command-line arguments to be used for parsing. If left nil, the loader will default to using `os.Args`. This can be explicitly parsed by the user if required.
`loader` struct: - Embeds `Config` to inherit its configuration options. - `groups`: A map that holds the different `Parser` implementations, indexed by `ParserType`.
Types: - `LoaderOption`: A function type used to apply custom options to the `loader`. - `ParserType`: Represents the type of parser (e.g., "defaults", "env", "flags").
Constants: - `ParserDefaults`: Represents the default parser that loads configurations based on struct tags. - `ParserFlags`: Represents the parser that loads configurations from command-line flags. - `ParserEnv`: Represents the parser that loads configurations from environment variables.
Example Usage: Custom parsers can be injected using `LoaderOption` functions, such as `WithCustomParser`.
type EnvUsageOption ¶ added in v0.2.0
type EnvUsageOption func(*envUsageOptions)
EnvUsageOption defines a function type used to configure options for environment variable usage.
func EnvUsageWithPrefix ¶ added in v0.2.0
func EnvUsageWithPrefix(prefix string) EnvUsageOption
EnvUsageWithPrefix creates an EnvUsageOption that sets a prefix for environment variables. This prefix is applied to each environment variable name when generating usage information.
Parameters:
- prefix: The string prefix to add to environment variable names.
Returns:
- EnvUsageOption: A function that modifies the prefix in envUsageOptions.
type ErrMissingField ¶
type ErrMissingField struct { Field string // Name of the field. Type string // Type of the field. Path string // Path is full path to the field in the nested structure. }
ErrMissingField represents an error for a missing required field. It contains information about the field's name, its type, and the full path to the field.
func (ErrMissingField) Error ¶
func (e ErrMissingField) Error() string
Error formats the ErrMissingField into a descriptive error message.
type Error ¶ added in v0.5.0
type Error string
Error is a custom error type based on a string. It represents an error that is constant and does not change at runtime.
type LoaderOption ¶
type LoaderOption func(*loader) error
LoaderOption defines a function type used to customize the behavior of the loader. Each `LoaderOption` takes a pointer to a `loader` and returns an error if the customization fails.
The purpose of `LoaderOption` is to allow for flexible configuration of the loader instance. Options can be applied to modify the loader’s behavior, such as adding custom parsers, modifying existing parsers, or changing configuration settings.
Usage: A `LoaderOption` function is passed to the `New` function or similar, allowing for dynamic configuration. Multiple options can be combined, and each one will be applied to the loader sequentially.
Example:
func WithCustomSetting(setting string) LoaderOption { return func(l *loader) error { // modify loader based on custom setting l.Config.SomeSetting = setting return nil } }
func WithConfig ¶ added in v0.4.0
func WithConfig(handler func(*Config)) LoaderOption
WithConfig allows modifying the Config object using a custom handler function. This LoaderOption provides a way to customize configuration settings dynamically before the loading process begins.
The provided handler function receives a pointer to the Config object, allowing modifications to be applied as needed.
Parameters: - handler: A function that takes a *Config and applies custom modifications.
Returns: - A LoaderOption that applies the given handler to modify the loader's Config.
func WithCustomExit ¶ added in v0.2.0
func WithCustomExit(exit func(int)) LoaderOption
WithCustomExit provides an option to override the default exit behavior of the loader. This is useful for testing, where calling `os.Exit` would terminate the test process.
By default, `loader.exit` is set to `os.Exit`, but this function allows replacing it with a custom exit function (e.g., a no-op or mock function).
Parameters:
- exit: A custom function that takes an exit code as an argument. If nil, the default behavior remains unchanged.
Returns:
- A LoaderOption function that applies the custom exit behavior to the loader.
func WithCustomParser ¶
func WithCustomParser(p Parser) LoaderOption
WithCustomParser creates a LoaderOption that adds a custom parser to the loader's group of parsers. This function allows you to inject a parser into the loader, which will be used to handle a specific type of configuration source. The custom parser will be added to the loader's parser group, enabling it to be invoked during the configuration loading process.
Parameters:
- p: The custom parser to be added to the loader. The parser must implement the `Parser` interface. If the provided parser is `nil`, no action is taken and the function returns `nil`.
Returns:
- A `LoaderOption` function that, when applied to a `loader`, will add the custom parser to the loader's group of parsers.
Example usage: If you have a custom parser that implements the `Parser` interface ands you want to include it in the loader's configuration process, you can use this function to add it:
myParser := NewMyCustomParser() // Assume this returns a valid Parser option := WithCustomParser(myParser) loader := NewLoader(config, option)
This will ensure that `myParser` is used by the loader to process configuration data.
func WithCustomParserInit ¶
func WithCustomParserInit(fabric ParserInit) LoaderOption
WithCustomParserInit allows the injection of a custom parser into the loader by using a provided `ParserInit` function. This function is useful for adding custom logic or additional parsers beyond the predefined ones.
The function performs the following tasks:
- Accepts a `ParserInit` function (`fabric`) that takes a `Config` and returns a `Parser` and an error.
- Executes the `fabric` function with the loader's current `Config` to initialize the custom parser.
- If the `fabric` function returns an error, it propagates that error immediately.
- Otherwise, it adds the parser to the loader's group under the parser's type.
Parameters:
- fabric: A `ParserInit` function that returns a custom `Parser` and an error based on the `Config`.
Returns:
- A `LoaderOption` that applies the custom parser to the loader's parser group, or returns an error if parser initialization fails.
func WithDefaults ¶ added in v0.4.0
func WithDefaults(keyTag string, defaults map[string]any) LoaderOption
WithDefaults sets default values for the loader's output structure.
This function takes a tag-key and map of default values and applies them to the target structure using `decodeMapToStruct`. It ensures that any unset fields in the structure receive the specified default values before other parsing mechanisms (such as environment variables or configuration files) are applied.
This function is useful when: - You want to provide fallback values for missing configurations. - You need to ensure a structure is always initialized with meaningful defaults.
For example, you can set `path.to.key=value`, to unmarshal it for struct{Path struct {To struct{Key string}}}
Parameters: - keyTag: allows to use struct-tag to find field names. - defaults: A map where keys are field names (or tagged keys) and values are default values.
Returns: - A `LoaderOption` function that applies the default values to the loader's output.
func WithJSONLoader ¶ added in v0.5.0
func WithJSONLoader(options ...fileLoaderOption) LoaderOption
WithJSONLoader returns a LoaderOption that enables JSON configuration parsing. It registers a JSON parser initializer using WithCustomParserInit.
func WithOptions ¶
func WithOptions(options any) LoaderOption
WithOptions allows dynamic application of loader options by accepting either a slice of LoaderOption or a function that returns a slice of LoaderOption. It ensures flexibility in configuring the loader.
The function performs the following tasks:
- Accepts `options` as an argument of type `any`, which can be either a `[]LoaderOption` or a `func() []LoaderOption`.
- Uses a type switch to determine the type of `options` and converts it into a `[]LoaderOption`.
- Applies each LoaderOption to the provided loader (`l`) by iterating over the result.
- If an invalid type is passed to `options`, it returns an error with the message indicating the unexpected type.
- If applying any option fails, it returns an error that includes the original error.
Parameters: - options: Can either be a slice of `LoaderOption` or a function that returns a slice of `LoaderOption`.
Returns:
- A `LoaderOption` that applies the resolved list of options to a given loader, or an error if the options type is invalid or if any option fails during application.
func WithTOMLLoader ¶ added in v0.5.0
func WithTOMLLoader(options ...fileLoaderOption) LoaderOption
WithTOMLLoader returns a LoaderOption that enables TOML configuration parsing.
func WithYAMLLoader ¶ added in v0.5.0
func WithYAMLLoader(options ...fileLoaderOption) LoaderOption
WithYAMLLoader returns a LoaderOption that enables YAML configuration parsing. It registers a YAML parser initializer using WithCustomParserInit.
type Parser ¶
type Parser interface { // Load loads the configuration into the specified destination object. // The parameter dest should be a pointer to the object where the configuration should be loaded. // This method should handle the process of parsing and populating the destination object with configuration data. // Returns an error if the loading process fails, allowing the caller to handle any issues that occur. Load(dest any) error // Type returns the type of the current Parser. // This method allows you to determine which type of parser is currently being used. // It helps in identifying the source or method of configuration loading (e.g., defaults, flags, environment). Type() ParserType }
Parser interface represents an abstraction for loading configuration. Implementations of this interface are responsible for loading configuration data from various sources into a specified destination object.
func New ¶
func New(config Config, options ...LoaderOption) Parser
New creates a new Parser based on the provided configuration and optional LoaderOptions. The function initializes a loader service (`svc`) with default settings from the provided configuration. Then it applies each LoaderOption to customize the service if any are provided.
The function returns a `parserFunc` that, when called, will: - Apply all the LoaderOptions to the `svc`. - Iterate through the `LoaderOrder` and invoke the corresponding group parsers. If any parser fails or if a group parser is missing, the function returns an error.
Parameters: - config: The Config object used to initialize the default settings for the loader. - options: A variadic number of LoaderOption functions to customize the loader.
Returns: - A Parser that can be used to load and parse values into the provided target structure.
nolint:ireturn
func NewCustomParser ¶
func NewCustomParser(name ParserType, loader func(any) error) Parser
NewCustomParser creates a new custom parser with the specified name and loader function.
Parameters:
- name: A ParserType value representing the name or type of the custom parser.
- Loader: A function that takes Config and an any and returns an error. This function defines how the custom parser should load or parse the configuration data.
Returns:
- A Parser interface which is implemented by the custom parser. This allows the library to use the provided loader function to process configuration data according to the specified ParserType.
Example usage:
customParser := NewCustomParser("myCustomParser", func(Config, any) error { // Custom parsing logic here return nil })
nolint:ireturn
type ParserConfigSetter ¶ added in v0.3.0
type ParserConfigSetter interface { // SetConfigPath sets the path to the configuration file. // The path parameter is expected to be a valid file path as a string. SetConfigPath(path string) }
ParserConfigSetter defines an interface for setting the configuration file path. Implementing types are expected to provide a method to set the path where the configuration file for the parser is located.
type ParserInit ¶
ParserInit is a function type that allows initializing a Parser with the provided loader Config. It takes a Config object as an argument and returns a Parser along with any initialization error. This function is used to create custom parsers based on the configuration settings.
type ParserPreparer ¶ added in v0.4.0
type ParserPreparer interface {
Prepare(Config)
}
ParserPreparer is an interface for preparing a parser before parsing. Implementations of this interface are expected to modify or adjust the provided `Config` object before it is used in the parsing process. This can include tasks such as setting default values, validating settings, or modifying parser behavior based on the given configuration.
This interface is useful when you need a preprocessing step before applying a parser.
Method: - Prepare(Config): Accepts a `Config` object and modifies it as needed before parsing.
type ParserType ¶
type ParserType string
ParserType represents the different types of parsers that can be used in the loader system. It is defined as a string to allow for flexible and extensible parser type definitions.
Each value of `ParserType` corresponds to a specific source or method of configuration parsing. The parser types determine the priority and the sequence in which the parsers are applied.
Constants:
ParserDefaults: Represents the default parser type that handles configuration values set by default values in the code or configuration. This parser is typically used to provide fallback values when other sources do not supply a value.
ParserFlags: Represents the parser type that handles command-line flags. This parser processes the command-line arguments passed to the program to configure various options.
ParserEnv: Represents the parser type that handles environment variables. This parser reads configuration values from environment variables, which can be used to configure the application in different deployment environments.
Example usage: To specify the order in which parsers should be applied, you can set the `LoaderOrder` field in the `Config` structure with these constants, e.g.,
config := Config{ LoaderOrder: []ParserType{ParserDefaults, ParserEnv, ParserFlags}, }
const ( // ParserDefaults Represents the default parser type that handles configuration values // set by default values in the code or configuration. This parser is typically used to // provide fallback values when other sources do not supply a value. ParserDefaults ParserType = "defaults" // ParserFlags Represents the parser type that handles command-line flags. This parser // processes the command-line arguments passed to the program to configure various options. ParserFlags ParserType = "flags" // ParserEnv Represents the parser type that handles environment variables. This parser // reads configuration values from environment variables, which can be used to configure // the application in different deployment environments. ParserEnv ParserType = "env" // ParserConfigSet Represents the parser type that handles command-line flags. This parser // processes the command-line arguments passed to the program to set config path. ParserConfigSet ParserType = "config-setter" )
type ReflectOptions ¶ added in v0.3.0
type ReflectOptions struct { CanAddr *bool // Only include fields that can be addressed (pointer to the field can be taken). CanSet *bool // Only include fields that can be set (modifiable). CanInterface *bool // Only include fields that can be interfaced (exposed as an interface{}). AsField []reflect.Type }
ReflectOptions defines options for reflecting on fields of a struct. These options specify conditions that determine which fields to include in the reflection process.
func (*ReflectOptions) IsField ¶ added in v0.3.0
func (o *ReflectOptions) IsField(v reflect.Value) bool
IsField checks whether the provided reflect.Value represents a valid field for reflection operations based on the ReflectOptions. It compares the value's type against the AsField slice in the ReflectOptions.
The method returns true if the value's type is explicitly listed in the AsField slice or if it is not a struct. If the value is a struct and does not match any type in AsField, the method returns false.
Parameters: - v: A `reflect.Value` to check if it should be treated as a field.
Returns: - true if the value is considered a field, or false if it's a struct that should not be treated as a field.
Example usage:
options := ReflectOptions{AsField: []reflect.Type{reflect.TypeOf(int(0))}} isField := options.IsField(reflect.ValueOf(someField)) // returns true/false based on field type.
func (*ReflectOptions) IsValid ¶ added in v0.3.0
func (o *ReflectOptions) IsValid(v reflect.Value) bool
IsValid checks whether a reflect.Value satisfies the conditions specified in the ReflectOptions. It validates whether the value's CanSet, CanAddr, and CanInterface properties match the corresponding constraints set in the ReflectOptions. If any constraint is not met, the method returns false.
Parameters: - v: A `reflect.Value` representing the field or value to be validated.
Returns: - true if the reflect.Value meets all the conditions specified in the ReflectOptions. - false otherwise.
Example usage:
options := ReflectOptions{CanSet: Ptr(true)} valid := options.IsValid(reflect.ValueOf(someField)) // returns true/false based on validation.
type ReflectValue ¶ added in v0.3.0
type ReflectValue struct { Value reflect.Value // The reflected value of the field. Field reflect.StructField // Metadata about the struct field (name, type, etc.). Owner *ReflectValue // Pointer to the owner (parent) ReflectValue, if applicable. }
ReflectValue represents a structure for working with a field of a struct in reflection. It contains the reflect.Value of the field, its associated struct field metadata, and a reference to its owner (the parent struct field, if applicable).
type TagOptions ¶ added in v0.3.0
type TagOptions struct { FlagEncodeBase string FlagFullName string FlagShortName string FlagConfig bool FieldRequired bool FieldIgnored bool FieldUsage string // contains filtered or unexported fields }
TagOptions represents the configuration options for processing struct tags and flags. It is used to define metadata for struct fields, including encoding details, flag names, and validation rules.
Fields: - FlagEncodeBase: Defines the base encoding format for the field (e.g., base64, base32). - FlagFullName: Specifies the full name of the flag associated with the field. - FlagShortName: Specifies the short or abbreviated name of the flag. - FlagConfig: Indicates whether the field should be loaded from a configuration file or environment variable. - FieldRequired: Specifies if the field is mandatory and should not be left empty. - FieldIgnored: Indicates whether the field should be ignored during flag processing and configuration loading. - FieldUsage: Provides a description of the field’s purpose, typically used for generating usage/help information. - tag: Internal representation of the field's struct tag, used for reflection operations.
This struct is typically used for flag parsing, configuration, and validation purposes in applications.
func ParseTagOptions ¶ added in v0.3.0
func ParseTagOptions(tag reflect.StructTag) TagOptions
ParseTagOptions parses a reflect.StructTag and extracts relevant options into a TagOptions struct. It processes the tag string to identify various flag configurations such as the full name, short name, encoding base, and whether the field is required or configurable via a config file.
The function expects certain tag formats, such as: - Full flag name as the first element in the tag, separated by a comma. - Optional "base:" prefix to define the encoding format (e.g., base64, base32). - Optional "short:" prefix to define a short flag name. - "config:true" to indicate that the flag can be loaded from a configuration file. - Required status is determined by the "RequiredTag" with the value "true".
Parameters: - tag: A `reflect.StructTag` representing the field's tag in the struct.
Returns: - A TagOptions struct populated with the parsed information.
Example tag format: `flag:"flagName,base:base64,short:f,config:true" usage:"field usage" required:"true"`