Introducing the go-arg Project
Overview
The go-arg library is a powerful tool for handling command-line arguments in Go applications using a structured, intuitive approach. This project provides a more seamless and efficient way to parse command-line inputs by leveraging Go structs, making the argument-handling process straightforward and reducing code complexity.
Getting Started
To begin using go-arg, you can simply include it in your Go project with the following line:
go get github.com/alexflint/go-arg
Basic Usage
Define a struct in your Go program to represent the command-line arguments your application will use. Let's consider a simple example:
var args struct {
Foo string
Bar bool
}
arg.MustParse(&args)
fmt.Println(args.Foo, args.Bar)
Running the application with command-line arguments such as --foo=hello --bar
will produce output as follows:
$ ./example --foo=hello --bar
hello true
Advanced Features
Required Arguments
To specify mandatory arguments, use the arg:"required"
tag. If the argument isn't provided, the program will display an error:
var args struct {
ID int `arg:"required"`
Timeout time.Duration
}
arg.MustParse(&args)
Positional Arguments
go-arg also supports positional arguments, which can be specified without option flags:
var args struct {
Input string `arg:"positional"`
Output []string `arg:"positional"`
}
arg.MustParse(&args)
Usage:
$ ./example src.txt x.out y.out z.out
Environment Variables
You can map command-line arguments to environment variables using the arg:"env"
tag:
var args struct {
Workers int `arg:"env"`
}
arg.MustParse(&args)
Environment variables can be overridden by command-line inputs, and you can also specify custom names for them.
Default Values and Help Strings
Default values for arguments can be set with the default
tag. For better user interaction, custom usage strings and help messages are easily defined through help
tags.
Complex Data Types
go-arg supports a variety of data types, including custom types that implement the encoding.TextUnmarshaler
interface. This flexibility allows for comprehensive parsing and validation of complex data.
Structuring Commands
For applications with multiple commands, go-arg supports subcommands. This feature allows developers to build versatile command-line interfaces similar to Git:
type CheckoutCmd struct {
Branch string `arg:"positional"`
Track bool `arg:"-t"`
}
Versioning and Custom Parsing
You can include version flags directly within your application's command structure and handle custom parsing logic, accommodating a wide range of application needs.
Conclusion
The go-arg library offers a robust and elegant approach to argument parsing in Go applications. By using familiar struct definitions, developers can simplify command-line parsing and enhance code maintainability, enabling cleaner and more comprehensible applications. For more information on specific API components and use cases, explore the comprehensive documentation on pkg.go.dev.