Around Go: DevOps and reliability · 3 MIN READ

Build a small operational CLI with explicit boundaries

Design a Go command with bounded input, machine-readable output, explicit exit status and cancellation ownership.

A script becomes infrastructure when other programs rely on it. Define its input, output, exit codes and side effects before adding concurrency or cloud APIs. A read-only inventory tool is a useful first project because failure can be tested without changing a real system.

Go for DevOps and reliability · A MAP OF THE IDEA

  1. Parse bounded input
  2. Build a read-only plan
  3. Run owned bounded work
  4. Report an explicit outcome

Useful when

  • Design a Go command with bounded input, machine-readable output, explicit exit status and cancellation ownership.
  • Make changes reviewable and verify the result against the original contract.

Watch out

  • Reject unknown input and apply independent byte, target, concurrency and time budgets. Validate and test a dry run before introducing writes.

Implementation & operation cost: Automation needs explicit ownership, bounded privileges, tests and recovery evidence; a shorter command is not sufficient.

01

Specify what callers can depend on

Keep machine-readable results on stdout and diagnostic messages on stderr. Return a nonzero exit code for an unsuccessful operation; an empty result is different from a failed request. Reject unknown flags and configuration fields so a misspelled safety option cannot silently do nothing. Limit input bytes, target count, response bytes, concurrency and total elapsed time independently. A timeout does not limit how much input is read, and a worker limit does not bound a queue.

02

A bounded, deterministic inventory model

This complete program validates a small JSON inventory and emits one JSON report. It performs no network calls or writes. The fixed input makes it runnable in the app/browser as a teaching model. Unknown fields, trailing documents, excessive bytes, duplicate targets and empty inventories fail before producing a success report.

go
package main

import (
 "encoding/json"
 "errors"
 "fmt"
 "io"
 "strings"
)

type Input struct { Targets []string `json:"targets"` }
type Report struct { Mode string `json:"mode"`; Count int `json:"count"` }
func inspect(r io.Reader, w io.Writer) error {
 data, err := io.ReadAll(io.LimitReader(r, 4097))
 if err != nil { return err }
 if len(data) > 4096 { return errors.New("input exceeds 4096 bytes") }
 dec := json.NewDecoder(strings.NewReader(string(data)))
 dec.DisallowUnknownFields()
 var input Input
 if err := dec.Decode(&input); err != nil { return err }
 var extra any
 if err := dec.Decode(&extra); err != io.EOF { return errors.New("expected one JSON document") }
 if len(input.Targets) == 0 || len(input.Targets) > 20 { return errors.New("use 1-20 targets") }
 seen := map[string]bool{}
 for _, target := range input.Targets {
  if target == "" || strings.ContainsAny(target, " \t\r\n") || seen[target] { return errors.New("invalid or repeated target") }
  seen[target] = true
 }
 return json.NewEncoder(w).Encode(Report{Mode: "dry-run", Count: len(input.Targets)})
}
func main() {
 err := inspect(strings.NewReader(`{"targets":["api-a","api-b"]}`), writer{})
 if err != nil { fmt.Println("error:", err) }
}
type writer struct{}
func (writer) Write(p []byte) (int, error) { return fmt.Print(string(p)) }
Read the code

Expected output: {"mode":"dry-run","count":2}. The writer deliberately demonstrates io.Writer injection. Tests can supply bytes.Buffer and a reader that returns an error, without redirecting process-global stdout.

03

Add native process behavior at the edge

In a real native CLI, parse flags with a dedicated flag.FlagSet, pass os.Stdin and injected stdout/stderr into a run function, and call os.Exit only in main after owned resources have been closed. Use signal.NotifyContext for the top-level interrupt, derive operation deadlines, and join workers before returning. Keep this process/signal layer outside the reusable planning package. It is not available as an arbitrary OS shell in the app’s WASI sandbox.

04

Treat shell execution as a separate capability

When a reviewed native task truly needs a subprocess, pass an executable and an argument slice to exec.CommandContext. Never concatenate inventory values into sh -c. Use an allowlisted executable, a known working directory, a controlled environment and bounded output. Command cancellation alone may not end every descendant process: process-group cleanup and platform-specific behavior require explicit tests. A redacted log should identify the operation and result without exposing access tokens or user-controlled terminal escapes.

05

Exercise failure as part of the interface

Test valid input, an unknown field, two JSON documents, an over-budget reader, a duplicate target and a failing output writer. Assert both exit behavior and whether a success record was written. Next add a fake client that blocks until context cancellation; verify that the command returns and all workers exit. Run an actual local smoke test against a disposable target before adding any apply mode. A dry-run flag is credible only when tests prove it cannot reach mutation methods.

TAKE THIS WITH YOU

Design a Go command with bounded input, machine-readable output, explicit exit status and cancellation ownership.

Check your understanding

What should happen before a misspelled safety field reaches the operational client?

Go to the source

Progress stays in this browser. No account needed.