Parsing and Validating Command Line Arguments
In the previous section, we explored the basic concepts of working with command-line arguments in Go. However, as your program becomes more complex, you may need to perform more advanced parsing and validation of these arguments. The Go standard library provides several tools and techniques to help you achieve this.
Parsing Command-Line Arguments with the flag
Package
The flag
package in the Go standard library offers a flexible and powerful way to parse command-line arguments. In addition to the basic usage shown earlier, the flag
package provides several features to handle more complex scenarios.
Defining Custom Flag Types
The flag
package allows you to define custom flag types by creating your own Value
implementations. This can be useful when you need to accept arguments of a specific data type, such as a duration or a list of values.
package main
import (
"flag"
"fmt"
"time"
)
type duration struct {
value time.Duration
}
func (d *duration) Set(s string) error {
var err error
d.value, err = time.ParseDuration(s)
return err
}
func (d *duration) String() string {
return d.value.String()
}
func main() {
var timeout duration
flag.Var(&timeout, "timeout", "Timeout duration")
flag.Parse()
fmt.Printf("Timeout: %s\n", timeout.value)
}
In this example, we define a custom duration
type that implements the flag.Value
interface. This allows us to accept a duration argument using the -timeout
flag.
Handling Required Arguments
The flag
package also provides a way to mark certain arguments as required, ensuring that the user provides the necessary information to run your program.
package main
import (
"flag"
"fmt"
)
func main() {
name := flag.String("name", "", "Name to greet (required)")
flag.Parse()
if *name == "" {
flag.Usage()
return
}
fmt.Printf("Hello, %s!\n", *name)
}
In this example, we mark the name
argument as required by not providing a default value. If the user doesn't provide the name
argument, the program will display the usage information and exit.
Validating Command-Line Arguments
Beyond parsing, it's often necessary to validate the provided command-line arguments to ensure they meet your program's requirements. This can involve checking the values, types, or combinations of arguments.
package main
import (
"flag"
"fmt"
"os"
"strconv"
)
func main() {
var age int
flag.IntVar(&age, "age", 0, "Age of the person (must be between 1 and 120)")
flag.Parse()
if age < 1 || age > 120 {
fmt.Fprintf(os.Stderr, "Error: Age must be between 1 and 120\n")
flag.Usage()
os.Exit(1)
}
fmt.Printf("You are %d years old.\n", age)
}
In this example, we define an age
flag and validate that the provided value is between 1 and 120. If the value is outside this range, we display an error message, show the usage information, and exit the program with a non-zero status code.
By combining the parsing capabilities of the flag
package with custom validation logic, you can create robust and user-friendly command-line interfaces for your Go programs.