Building A Golang Cli Tool From Scratch

Author

Reads 1.3K

Shot of Computer Screen with Multicoloured Code
Credit: pexels.com, Shot of Computer Screen with Multicoloured Code

Building a Golang CLI tool from scratch is a straightforward process that requires a few key components. You'll need to create a new Go file, typically named main.go, which will serve as the entry point for your CLI tool.

In the main.go file, you'll use the flag package to define command-line flags that your users can pass to your tool. This is where you specify the flags that will be available to your users, such as -h for help or -v for verbose mode. The flag package provides a simple way to define and parse command-line flags.

To create a new Go file, you can use a tool like go mod init to initialize a new module, which will create a go.mod file and a go.sum file in your project directory. This is a crucial step in setting up your Go project.

For another approach, see: Golang Create

Getting Started

To get started with building a GoLang CLI, you'll need to have the Go programming language installed on your local machine, along with the Go package. The Go documentation provides steps on how to set this up.

You'll also need an editor or IDE with support for Go, such as GoLand. This will help you write and manage your Go code.

Here are the specific prerequisites you'll need to meet:

  1. Familiarity with the Go programming language
  2. GoLand (or another editor or IDE with support for Go)

Prerequisites

Three young people working on computers in a creative office with vibrant graffiti walls.
Credit: pexels.com, Three young people working on computers in a creative office with vibrant graffiti walls.

To get started with this tutorial, you'll need a solid foundation in the Go programming language and the Go package installed on your local machine. The official Go documentation provides detailed steps on how to set up Go on your device.

You'll also need a suitable editor or IDE that supports Go. Specifically, you can use GoLand, or another editor that meets this requirement.

To summarize, you'll need two things to begin: familiarity with the Go programming language and the Go package installed on your local machine, as well as a Go-supported editor or IDE.

Additional reading: Golang Local

Plan & Design Your Tool

Before you start building your command-line tool, take some time to plan and design it. Determine its purpose, target audience, and core functionalities.

To do this, ask yourself what problems your tool will solve, what specific tasks or operations it will enable users to perform, and what technical vocabulary they use to describe these tasks. By understanding common workflows, you'll design a command structure and user interface that is intuitive.

From above crop faceless male developer in black hoodie writing software code on netbook while working in light studio
Credit: pexels.com, From above crop faceless male developer in black hoodie writing software code on netbook while working in light studio

Break down these functionalities into logical command structures and subcommands. Group related commands together and use a consistent naming convention for a cohesive and user-friendly experience.

Consider the following key points to keep in mind:

  • What problems does your tool solve?
  • What specific tasks or operations will it enable users to perform?
  • What technical vocabulary do users use to describe these tasks?

This organization will make your CLI easier to navigate and use.

Building a CLI

Building a CLI in Golang is a breeze with the right tools. Cobra is a widely used package to bootstrap a CLI from prototype to complex applications like kubectl or GitHub CLI.

To get started, you'll want to create a folder called cmd in the same directory as your main.go file and then create a root.go file in the newly created cmd folder. This is where you'll define your root command and accessor function to execute the command.

You can execute the command to install Cobra in your GoLand terminal, which should print the successful installation of the cobra package to your console. With Cobra installed, you can now utilize the root command's Execute() function in your main.go file.

You might like: Golang Cmd

Credit: youtube.com, Building a CLI application with Golang

Here are some key properties of a Cobra command:

  • Use holds the text used to invoke usage of the command.
  • Short represents a short description of the command.
  • Long is similar to Short but holds a longer description of the command.
  • Run holds the function to be executed on the invocation of the command.

Build Elegant Interfaces with Go

Building a CLI with Go is a breeze, thanks to powerful tools like Cobra and Viper. Cobra is a framework that makes building small or large tools a walk in the park, and it's even used by popular Go applications like Docker and Kubernetes.

Cobra is more than just a library, it's a program that generates applications and CLI applications in Go. This means you can create a skeleton for your CLI and then add your own code to make it shine.

Cobra and Viper are designed to work together, making your life as a CLI developer much easier. Viper is a complete configuration solution that handles configuration needs and formats, and it even supports nested structures for large applications.

If you're working with sensitive data, Viper is a great choice because it allows you to work with environment variables instead of displaying them in the command line history. This is a great feature to have, especially when working with sensitive information.

Here are some great Go books for creating CLIs:

  • Powerful Command-Line Applications in Go
  • Go in Action
  • The Go Programming Language
  • Go Programming Blueprints

These books will give you a solid foundation in building elegant interfaces with Go, and they're a great resource to have when working on your CLI project.

Building a Cobra tool

A spacious harbor terminal with large reflective windows overlooking the sea.
Credit: pexels.com, A spacious harbor terminal with large reflective windows overlooking the sea.

Building a Cobra tool is a great way to create a command line interface (CLI) in Go. Cobra is a widely used package to bootstrap a CLI from prototype to complex applications like kubectl or GitHub CLI.

To start building a Cobra tool, you'll need to create a new folder called cmd in the same directory as your main.go file. Then, create a root.go file in the newly created cmd folder. This file will use the Cobra package to create the root command and an accessor function to execute the command.

The Cobra package provides a rich API to create powerful commands. You can define a new command with several properties, including Use, Short, Long, and Run. The Use property holds the text used to invoke usage of the command, while the Short and Long properties represent a short and long description of the command, respectively. The Run property holds the function to be executed on the invocation of the command.

Credit: youtube.com, From Zero to CLI Hero: The ULTIMATE Cobra Tutorial

Here's an example of how to define a new command using Cobra:

To add subcommands to your Cobra tool, you'll need to create new files in the cmd directory. For example, you can create an add.go file to hold the command for the addition operation and a subtract.go file to hold the command for subtraction.

Once you've defined your commands and subcommands, you can run them using the Cobra package. The Cobra package will handle the execution of the commands and subcommands, including error handling and command-line argument parsing.

To see each change you make take place in effect, you'll need to run go install again to update your binary. This will ensure that your Cobra tool is up-to-date and functioning correctly.

By following these steps, you can create a powerful and user-friendly CLI using the Cobra package. With Cobra, you can create complex CLI applications with ease, including features like command aliases, nested commands, and intelligent suggestions.

Creating a Command

Ethnic kid showing command to intelligent dog while squatting on asphalt pavement in city
Credit: pexels.com, Ethnic kid showing command to intelligent dog while squatting on asphalt pavement in city

To create a command in your GoLang CLI, you'll need to create a folder called cmd in the same directory as your main.go file. Inside the cmd folder, create a root.go file and paste in the code that uses the Cobra package to define a new command with several properties, including Use, Short, Long, and Run.

The Cobra package is used to create powerful commands, and the root.go file is where you'll define the root command and its accessor function. The Cobra.Command struct has several properties, including Use, which holds the text used to invoke the command, Short, which represents a short description of the command, and Long, which holds a longer description of the command.

To execute the root command, you'll need to handle any errors that may occur by printing the error messages to the console. Alternatively, you can install Cobra using the GoLand terminal and then utilize the root command's Execute() function in your main.go file.

Credit: youtube.com, This Makes Golang CLI Development So MUCH Better

Here are the properties of the Cobra.Command struct:

  • Use: holds the text used to invoke the command.
  • Short: represents a short description of the command.
  • Long: holds a longer description of the command.
  • Run: holds the function to be executed on the invocation of the command.

By defining these properties, you'll be able to create a robust and user-friendly command-line interface for your GoLang application.

Adding Logic and Features

As you continue to build your Go CLI, it's time to add some logic and features to make it more robust. To take an argument from the user and print something based on that, you can use the args slice provided by Cobra. This allows you to check the animal type and print the result accordingly.

You'll need to run go install again to update your binary after making changes. This will ensure that each change takes place in effect. To test out your sound CLI, simply run the command and see the result.

Implementing features and handling errors is also crucial. By having separate functions for your logic, you can easily reuse them in other commands. This makes your code more maintainable and scalable.

Recommended read: Golang Cli Relationship

Libraries

Boy Sitting in a Library
Credit: pexels.com, Boy Sitting in a Library

CLI applications can greatly benefit from the addition of libraries that provide extra functionality and features. You can use the CLI Libraries to enhance your application.

There are many libraries available to choose from, each with its own strengths and weaknesses. One popular choice is Cobra, a library for creating powerful modern CLI applications in Go.

Here are a few more libraries you might find useful:

  • spf13/viper: a complete configuration solution for Go applications
  • urfave/cli: a minimal framework for creating and organizing command line Go applications
  • dixonwille/wmenu: an easy-to-use menu structure for CLI applications
  • spf13/pflag: a drop-in replacement for Go’s flag package, implementing POSIX/GNU-style flags
  • golang/glog: leveled execution logs for Go
  • go-prompt: a library for building powerful interactive prompts
  • chzyer/readline: a pure Golang implementation of GNU Readline
  • delve: a simple and powerful tool for programmers

By incorporating these libraries into your application, you can make it more user-friendly and efficient.

Adding Some Logic

You can add logic to your command by taking an argument from the user and printing something based on that. This is done by accessing the args slice provided by Cobra, which contains anything the user entered after the command.

To access the args slice, you can use the Args function, which has been updated to validate details that can be returned for any public GitHub repository. This makes it easy to reuse this code in other commands.

You can then check the animal type and print your result accordingly, making your code pretty simple.

Packaging and Releasing

Credit: youtube.com, Building CLI Tools with GoLang | Sandip Das

Packaging and releasing software is boring and error-prone. This is where GoReleaser comes in, making the process less painful.

GoReleaser lets you define a configuration file to build, archive, package, sign, and publish artifacts. These artifacts are multiple versions of your CLI for multiple platforms and package managers.

To set up a CI/CD pipeline for your CLI, you can use GoReleaser. This enables a smooth release management, ensuring a seamless development workflow.

GoReleaser can be installed by following their installation guide. Once installed, running goreleaser init creates a .goreleaser.yaml file that holds all the necessary configuration.

In the builds section, you specify that the CLI needs to be compiled to target MacOS, Windows, and Linux for different architectures. The archives section is used to customize generated archives.

To test the release process locally, you can run a specific command. You can adjust the generated artifacts following GoReleaser’s documentation and ensure your configuration file is valid using another command.

Continuous Integration and Deployment

Credit: youtube.com, Continuous Integration vs. Continuous Delivery vs Continuous Deployment: What Are The Differences?

Continuous Integration and Deployment can save you a lot of time and headaches.

Using a CI/CD pipeline can automate the process of releasing new versions of your CLI, making it less error-prone.

Every engineer on your team can release new versions manually, but this process is tedious and prone to mistakes.

By running the release process in a CI/CD pipeline, a predefined workflow can be triggered every time an event happens on your repository.

This can be set up using GitHub actions, which can release a new version of your CLI every time a new tag is pushed to your repository.

You can use semantic versioning to define the version of your CLI based on the tags you push.

To trigger a release, you can use the command `git tag 1.0.0 && git push --tags`, which will run the GitHub actions workflow.

Your GitHub credentials can be stored in the `RELEASE_TOKEN` repository secret to authenticate the release process.

Cora Stoltenberg

Junior Writer

Cora Stoltenberg is a skilled writer with a passion for crafting engaging content on a wide range of topics. Her expertise spans various categories, including Search Engine Optimization (SEO) Strategies, where she provides actionable tips and insights to help businesses improve their online presence. With a keen eye for detail and a knack for simplifying complex concepts, Cora's writing is both informative and accessible to readers of all levels.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.