liveBook · Manning

Command-line parsing

As explained in Go by Example

A command-line parser is software that interprets command-line arguments and flags according to a defined syntax.

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

How Go by Example covers it

How deep it goes
Builds a custom parser through argument separation, typed value parsers, integration, errors, and defaults before deferring to flag.
Examples
Uses the HIT HTTP tool with url, request-count, and concurrency flags, including explicit values, omitted flags, defaults, and usage output.
What it assumes
Assumes basic Go variables and command-line arguments while teaching parsing functions, typed conversion, configuration, and exit status.
What you can do after
Build it from scratch by parsing os.Args, assigning typed configuration values, handling errors, and choosing sensible defaults.
How it connects
Connects command-line interfaces with the os package, configuration structs, the flag package, input validation, and custom types.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.