Documentation
¶
Overview ¶
Package flag provides a simple API for defining and parsing command-line flags in Go applications.
It is built on top of the pflag library and includes support for a set of common default flags.
Default flags:
- `--path` (string): Sets the application’s default path (default: "./data")
- `--help` (bool): Displays the help message
- `--version` (bool): Prints the application version
- `--debug` (bool): Enables debug mode
The `Init` function parses all registered flags and should be called early, typically in the `main` function of the application. If the `--help` flag is set, it prints usage information and exits.
Additional flags can be registered using `Register`, which accepts the flag name, a pointer to the variable to populate, and a usage description. Existing flags can be overridden using `Override`, which allows changing the variable, default value, and description of an already registered flag. Flags can be removed using `Unregister`, which removes a previously registered flag from the command line. Supported types include strings, booleans, integers, unsigned integers, and floats.
Example:
package main
import (
"fmt"
"github.com/valentin-kaiser/go-core/flag"
)
var CustomFlag string
func main() {
flag.Register("custom", &CustomFlag, "A custom flag for demonstration")
// Override the default path flag
flag.Path = "/new/default/path"
flag.Override("path", &flag.Path, "Updated application working directory")
// Unregister a flag if no longer needed
flag.Unregister("custom")
flag.Init()
fmt.Println("Custom Flag Value:", CustomFlag)
fmt.Println("Path:", flag.Path)
}
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // Path is the default path for the application data Path string // Help indicates whether the help message should be printed Help bool // Version indicates whether the version information should be printed Version bool // Debug indicates whether debug mode is enabled Debug bool )
Functions ¶
func Init ¶
func Init()
Init initializes the flags and parses them It should be called in the main package of the application
func Override ¶
Override allows changing an existing flag's variable, default value and description It panics if the flag is not already registered or if the value is not a pointer Note: The flag must not have been parsed yet for this to work properly
func Register ¶ added in v1.5.1
Register registers a new flag with the given name, value and usage It panics if the flag is already registered or if the value is not a pointer
func Unregister ¶ added in v1.5.1
func Unregister(name string)
Unregister removes a previously registered flag It panics if the flag is not registered or if flags have already been parsed
Types ¶
This section is empty.