/

How to Build a CLI Command with Go: Cowsay

How to Build a CLI Command with Go: Cowsay

Tags: Go, CLI, Cowsay, ASCII Pictures, Command-Line Tool

Are you a fan of CLI apps? If so, you’ve probably heard of Cowsay. Cowsay is a popular command-line application that generates ASCII pictures of a cow with any message you pass to it. But it’s not limited to cows – it can also print penguins, mooses, and many other animals. In this tutorial, we’ll show you how to build your own version of Cowsay from scratch using the Go programming language.

To get started, let’s define the problem. We want to accept input through a pipe and have our cow say it. In the first iteration of our program, we’ll simply read the user input from the pipe and print it back. Here’s the code for the first iteration:

1
2
3
// Code for the first iteration

...

In this code, we check if the input is coming from a pipe or a character device. If it’s a pipe, we read the input from the pipe and print it back. If it’s a character device, we display a usage message.

However, our program is missing the cow itself and the balloon that wraps around the message. To add these features, we need to implement the buildBalloon function and the printFigure function. Here’s the code for the improved version of our program:

1
2
3
// Code for the improved version

...

In this code, we’ve added the buildBalloon function, which takes a slice of strings representing the lines of the message and builds a string with the contents of the balloon. We’ve also added the printFigure function, which prints the specified figure (either a cow or a stegosaurus).

Once you’ve implemented these changes, you can run the program and see the cow saying your message. You can also customize the figure by using the -f flag followed by the figure name. For example, if you want the stegosaurus to say your message, you can run the program with the command go run main.go -f stegosaurus.

To make the program more convenient to use, you can build and install it system-wide by running the commands go build and go install. This way, you can simply type gocowsay in your terminal to use the command.

Now you can have fun generating ASCII pictures with your own version of Cowsay. Happy coding!

Like CLI apps? Don’t miss the lolcat tutorial as well!