Saturday, December 30, 2017

How to get consistent exit codes from golang

Greetings Programs!

I've been working on a command line tool named convey for quite some time now and it needs to return an exit code.  In most programming languages this is pretty straight forward... You just return the exit code from your main function.  But in golang it's not quite that simple.

In golang os.Exit returns immediately and doesn't call any deferred function calls.  This makes it impossible to cleanup with a deferred function.  As many gophers will tell you, deferred cleanup functions are amazing, so this is quite the bummer.

I've experimented with this for a while, but never got it fully sorted out until tonight.  My previous attempts swallowed panics and just weren't very good.  But today I built a proof of concept, tested it, and documented the crap out of it.  And well, it works great!  No longer will I find myself scratching my head on why I have an exit code of 0 but the program aborted too early.

This works by renaming your main function to gomain and making it return an int.  Then we write a main function that does all of the magic including handling panics.

You can find the fully documented source code (released to the public domain) at bitbucket.org/rw_grim/gomain.

Happy Hacking!