Creating console applications in Golang

21 March 2016

Creating a few console applications in the past I worked near to the ideal (for me at least) setup to created console applications. The following article I'll show you how I'm implementing new console appications and the reasons behind it.

My latest console application is Elastico, an application to work with Elasticsearch. It is very much a work on progress, but I think the structure is very flexible and works quite well.

Within the main function I'll define the application, the sections and (global) flags. The before handler is being created here as well, taking care of the global setup. Where it is of any using I'm using environment variables as well. In this case the ELASTICO_HOST is being used as the host flag, for easy implementation within scripts.

This function will handle required flags (which I'll talk later about), showing the error template on errors to StdErr, writing output templated or in json format to StdOut. If functions are returning errors, the application will return with an (error) Exit code as well. This is very important for embedding in scripts.

New function templates are being registered using this function. It will register the template and will also check the local filesystem if there are existing templates in the ~/.elastico folder, these are prioritised. This allows users to customize their output templates like there preferences, just using GO templating.

Templates are being defined for each command, together with the flags and required flags. The templates are using a common funcmap, for colorizing or formatting objects. When flags are being re-used multiple times, I'm creating a separate variable for them. This allows unity and consistency.