Basics for writing a command-line tool in Go

Go provides a built-in library called flag for writing CLI tools. It refers to the command-line flags. Since it is already packed with the Go distribution, there is no need to install anything externally. The flag package has multiple functions, such as Int and String, to handle the respective type input that's supplied as a command-line flag. Let's suppose that we collect a name from the user and print it back to the console.

To do this, we can use the flag.String method, as shown in the following code snippet:

import "flag"var name = flag.String("name", "stranger", "your wonderful name")

Let's write a short program to illustrate the flag API in more detail:

  1. Create a file called flagExample.go ...

Get Hands-On RESTful Web Services with Go - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.