Learn how to use the GatherFlagsFromStringList function for parsing command line flags programmatically. This function does not require the use of cobra bindings, but instead just requires a list of strings.
The GatherFlagsFromStringList function allows you to parse command line flags programmatically. This function
does not require the use of cobra bindings, but instead just requires a list of strings.
func GatherFlagsFromStringList(
args []string,
params []*Definition,
onlyProvided bool,
ignoreRequired bool,
prefix string,
) (map[string]interface{}, []string, error)
args: a slice of strings representing the command line arguments.params: a slice of *Definition representing the field definitions.onlyProvided: a boolean indicating whether to only include flags that were provided in the command line arguments.ignoreRequired: a boolean indicating whether to ignore required flags that were not provided in the command line arguments.prefix: a string to be added as a prefix to all flag names.The function returns a map where the keys are the field names and the values are the parsed values. If a flag is not recognized or its value cannot be parsed, an error is returned.
Here is an example of how to use the function:
params := []*Definition{
{Name: "verbose", ShortFlag: "v", Type: TypeBool},
{Name: "output", ShortFlag: "o", Type: TypeString},
}
args := []string{"--verbose", "-o", "file.txt"}
result, args, err := GatherFlagsFromStringList(args, params, false, false, "")
if err != nil {
log.Fatal(err)
}
fmt.Println(result) // prints: map[verbose:true output:file.txt]
In this example, the function parses the --verbose and -o flags according to the provided field definitions. The --verbose flag is a boolean flag and is set to "true". The -o flag is a string flag and its value is "file.txt".
Here are some examples of command line inputs and the corresponding output of the function:
Input: --verbose -o file.txt
Input: --debug --log-level info
Input: --output=file.txt --verbose=true
Input: --size 100 --color red
Input: --int-list=1,2 --int-list 3,4 --int-list=5
Input: --string-list item1,item2,item3
Input: --verbose foobar --output file.txt another argument