4

Easily creating a golang command line tool

 1 year ago
source link: https://carlosvin.github.io/langs/en/posts/create-cmd-tool-golang/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Easily creating a golang command line tool

Let's see how to easily and quickly create a command line tool in golang

Golang is the one of the most useful technologies I’ve recently learned. Golang has a pretty nice support for networking, command line or logging out of the box, you don’t need any dependency. But there are libraries making developers' life even easier.

I’ve already talked about creating REST service in go, today I’d like to focus on creating a command line tool.

Flags

Command line tool to read number of lines as an input integer parameter Golang

With previous simple code we have already some useful capabilities

Print help menu
Use default value
Pass a value to the command tool
Pass an invalid value

For a simple command line tool, in most of the cases, we will have enough with the default language support. But if we want to bring more features to the combo like reading configuration from environment variables or from files, then a library like the awesome Viper will come really handy.

Viper

Viper is very powerful and well documented library widely used from many projects, I will not get into the details or how to use it, because I’ve created an abstraction to simplify its usage, I named it Meta-Viper.

Meta-Viper

Meta-Viper abstracts you of the details of reading configuration from files, environment or flags. This extra simplicity comes with a tradeoff, we are missing some flexibility.

Let’s see some features with an example.

Firstly we have to create a go modules project with the meta-viper dependency
  1. Create a go modules project

  2. Install the meta-viper dependency

Now let’s create a program that is configurable from files, command line params and environment variables.

main.go

Now let’s see some examples how this command line tool is able to load configuration.

Print usage (help)
Run with default values
Read the port from environment variable and host from input param

The last example will aggregate all the possible sources of configuration, it will extend the previous one adding configuration from a file. So let’s create a configuration file:

the-config.json
Read configuration from the-config.json file, from environment and from input params
Here you can find a multi-environment example a little bit more complete.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK