Command-line parsing interprets arguments and flags, separates names from values, and assigns those values to typed program variables. A custom parser can map each flag name to a value-parser function sharing the signature func(string) error. section 4.2.1
A practical parser follows this flow:
- Skip the program name in os.Args and pass the remaining arguments to a parsing function. section 4.2.4
- Separate each argument into a flag name and string value, such as -n=100 becoming n and 100. section 4.2.1
- Dispatch the string value to the matching parser, convert it to the required type, and update the destination variable. section 4.2.1
- Store results in a configuration struct, report parsing errors, and exit with status 1 when parsing fails. section 4.2.4
- Initialize useful defaults so omitted options remain practical while explicit flags can override them. section 4.2.4
Parsing options for an HTTP request tool
A HIT command accepts -url, -n, and -c options. Running it with -url="https://github.com/inancgumus" -n=250 -c=25 produces a configuration for 250 requests with concurrency 25. Omitting -n and -c uses defaults of 100 requests and concurrency 1, while url remains empty until validation is added. section 4.2.4
Listing 4.4 Flag parser integration (hit/cmd/hit/hit.go)
package main
import (
"os"
. . .
)
. . .
func main() {
var c config
if err := parseArgs(
&c, os.Args[1:], #1
); err != nil {
fmt.Printf("%s\n%s", err, usage)
os.Exit(1) #2
}
fmt.Printf(
"%s\n\nSending %d requests to %q (concurrency: %d)\n",
logo, c.n, c.url, c.c,
)
}
Trace the integration point where parsed arguments populate configuration, errors print usage information, and failure terminates the process. section 4.2.4
