Cobra/pflag Library for Go: Powerful Command-Line Flags
In Go development, creating user-friendly and flexible command-line interfaces (CLI) is a core task. The standard flag library provides basic flag parsing, but its functionality is limited. Enter cobra/pflag — a powerful library that extends the standard package and is an essential part of the Cobra ecosystem (the popular framework for building CLI applications).
The main advantage of pflag over the standard flag is its support for both POSIX/GNU flag styles (long flags with double dashes, e.g., --verbose) and BSD style (short flags with a single dash, e.g., -v). The library also supports combining short flags (-abc instead of -a -b -c), flags with mandatory arguments, counter flags, and much more. pflag is fully compatible with the flag.Value interface, making it easy to migrate existing code.
This library is actively used in well-known projects like Kubernetes, Helm, Hugo, and many others. If you're planning to build a serious CLI application in Go, pflag will be an indispensable tool, offering flexibility, performance, and compliance with modern command-line standards.
Installation
Install the library using the standard Go package manager go get:
go get github.com/spf13/pflag
After running this command, the library will be added to your Go module (go.mod file). You can now import it into your code:
import "github.com/spf13/pflag"
Quick Start
Let's create a simple app that accepts a username and a verbose flag:
package main
import (
"fmt"
"github.com/spf13/pflag"
)
func main() {
// Define flags
name := pflag.String("name", "World", "name to greet")
verbose := pflag.BoolP("verbose", "v", false, "enable verbose output")
// Parse flags
pflag.Parse()
// Use values
if *verbose {
fmt.Printf("Mode: verbose\n")
fmt.Printf("Name: %s\n", *name)
}
fmt.Printf("Hello, %s!\n", *name)
}
Run the program with different flags:
go run main.go
go run main.go --name=Go
go run main.go -n Go -v
go run main.go --verbose --name "Go Developer"
Key Methods and Functions
1. pflag.String(name, shorthand, value, usage)
Signature: func String(name string, shorthand string, value string, usage string) *string
Creates a string-type flag with the specified name, short form, default value, and description. Returns a pointer to a string.
host := pflag.StringP("host", "H", "localhost", "server address")
pflag.Parse()
fmt.Printf("Connecting to %s\n", *host)
2. pflag.Int(name, shorthand, value, usage)
Signature: func Int(name string, shorthand string, value int, usage string) *int
Creates an integer-type flag. Useful for specifying ports, limits, and other numeric parameters.
port := pflag.IntP("port", "p", 8080, "port to listen on")
pflag.Parse()
fmt.Printf("Server running on port %d\n", *port)
3. pflag.Bool(name, shorthand, value, usage)
Signature: func Bool(name string, shorthand string, value bool, usage string) *bool
Creates a boolean-type flag. These are toggle flags that don't require a value (just their presence