Exit
Keep cleanup in a run function; report errors from main and exit nonzero after cleanup completes.
os.Exit immediately stops a running program and returns a status code, a number the terminal can use to tell whether the program succeeded. Deferred functions do not run, so call it only after cleanup is complete.
A run function can return errors while its deferred cleanup still runs. main reports the error and chooses the process exit code.
package main
import (
"errors"
"fmt"
"os"
)
func run() error {
if len(os.Args) < 2 {
return errors.New("usage: program <name>")
}
fmt.Println("hello,", os.Args[1])
return nil
}
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}In production
Use status code zero for success and another number for failure so the terminal or an automated build can detect problems. Avoid log.Fatal in a running service because it stops the whole program without running deferred cleanup. Keep exit decisions in main or another top-level command function.
Enjoyed this? Get more software craft delivered to your inbox.