Go for Infrastructure Engineers›Part 2 · Cheat sheet & self-check

Part 2 — Tools that talk to systems · wrap-up

Cheat sheet & self-check

Every command from this section on one page.

04 · Building command-line tools

Building blocks

flag.String("cluster", "", "cluster name")Standard-library flag
go get github.com/spf13/cobra@latestAdd cobra for subcommands
slog.New(slog.NewJSONHandler(os.Stderr, nil))Structured JSON logs to stderr
signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)A context cancelled on Ctrl-C or SIGTERM
os.Exit(2)Exit with a specific code (deferred calls don't run!)

05 · HTTP, JSON and APIs

Patterns

client := &http.Client{Timeout: 10 * time.Second}Never use a client without a timeout
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)Request that stops when ctx is cancelled
defer resp.Body.Close()Always close bodies (connection reuse)
json.NewDecoder(resp.Body).Decode(&out)Decode JSON straight from the response
if resp.StatusCode >= 300 { }Errors from the server are not Go errors: check the status

06 · Concurrency you'll actually use

Patterns

var wg sync.WaitGroup; wg.Add(1); go func() { defer wg.Done() }()Start work and wait for it
g, ctx := errgroup.WithContext(ctx); g.SetLimit(10)Run tasks, at most 10 at once, cancel all on first error
select { case v := <-ch: case <-ctx.Done(): }Wait for whichever happens first
var mu sync.Mutex; mu.Lock(); defer mu.Unlock()Protect shared state
go test -race ./... / go run -race .Detect data races