Easily creating a golang command line tool
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
With previous simple code we have already some useful capabilities
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.
-
Create a go modules project
-
Install the meta-viper dependency
Now let’s create a program that is configurable from files, command line params and environment variables.
Now let’s see some examples how this command line tool is able to load configuration.
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:
Here you can find a multi-environment example a little bit more complete. |
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK