Exiting an application in Go happens anyway when the
main() function is complete, but the purpose of this post is to show you how to force that to happen. Perhaps at an earlier stage than the end of your code, perhaps with an error code too. This is a well established method in POSIX systems, whereby a program can return a 0-255 integer to indicate if the program ran successfully, and if not, why not.
We’ll be using the
os package in stdlib to exit for us. First we’ll look at exiting the application successfully (just below), then we’ll look at exiting with an error code.
Exit with Error (Status 1+)
Specifying an exit code above zero usually means an error has occurred. There is a list of common/reserved exit codes for bash to keep an eye on, but in our example below we will just be using our generic error code of 1.
Some common codes:
|2||Misuse of shell builtins|
|127||Command not found|
|128||Fatal error signal|