Separate stdout, stderr and exit status
Separate stdout, stderr and exit status
A CLI has standard output for results, standard error for diagnostics, and an exit status for success or failure. A pipeline consumes stdout, so avoid mixing progress text into machine-readable results. A reusable run function returns a status; a thin main calls os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)).
package main
import ( "bytes" "fmt" "io" "strconv")
func divide(args []string, out, diag io.Writer) int { if len(args) != 2 { fmt.Fprintln(diag, "usage: divide A B") return 2 } a, e := strconv.Atoi(args[0]) b, f := strconv.Atoi(args[1]) if e != nil || f != nil { fmt.Fprintln(diag, "expected integers") return 2 } if b == 0 { fmt.Fprintln(diag, "zero divisor") return 1 } if _, err := fmt.Fprintln(out, a/b); err != nil { fmt.Fprintln(diag, "write failed") return 1 } return 0}func main() { var out, diag bytes.Buffer code := divide([]string{"8", "2"}, &out, &diag) fmt.Print(out.String()) fmt.Println(code, diag.Len() == 0)}Zero means success by convention. This CLI uses 2 for invalid usage and 1 for an operation failure. These nonzero meanings are documented choices, not universal Go rules. Use io.Writer parameters so tests can capture the two streams independently. The main wrapper should exit only after run has returned and its deferred cleanup has finished.
Expected output:
40 trueErrors stay outside the data stream
package main
import ( "bytes" "fmt" "io" "strconv")
func divide(args []string, out, diag io.Writer) int { if len(args) != 2 { fmt.Fprintln(diag, "usage: divide A B") return 2 } a, e := strconv.Atoi(args[0]) b, f := strconv.Atoi(args[1]) if e != nil || f != nil { fmt.Fprintln(diag, "expected integers") return 2 } if b == 0 { fmt.Fprintln(diag, "zero divisor") return 1 } if _, err := fmt.Fprintln(out, a/b); err != nil { fmt.Fprintln(diag, "write failed") return 1 } return 0}func main() { var out, diag bytes.Buffer code := divide([]string{"8", "0"}, &out, &diag) fmt.Println(code, out.Len() == 0) fmt.Print(diag.String())}os.Exit terminates immediately and does not execute deferred functions, including defers in main. Return through helper functions before exiting. Check writes to stdout; a broken pipe or other writer failure may mean a result was not delivered. Diagnostic writes may also fail, so never rely on diagnostics alone to communicate failure.
Expected output:
1 truezero divisorTry it locally
Test invalid numeric input with separate buffers. Print status and confirm stdout is empty.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CLI 03: Separate stdout, stderr and exit status
Check the lesson objective before moving on.
Where should progress messages go for a machine-readable CLI?
Why put cleanup in run instead of deferring it before os.Exit in main?