
Go: Building and Using a Simple CLI Tool
To create a CLI tool in Go, we will use the built-in flag package for command-line argument parsing and demonstrate how to structure our application effectively. This example will cover a basic calculator that performs addition, subtraction, multiplication, and division.
Setting Up Your Go Environment
Before we begin, ensure you have Go installed on your machine. You can download it from the official Go website. After installation, verify it by running:
go versionCreating the Project Directory
Create a new directory for your CLI tool:
mkdir go-cli-calculator
cd go-cli-calculatorInitialize a new Go module:
go mod init go-cli-calculatorWriting the CLI Application
Create a new file named main.go in your project directory:
touch main.goOpen main.go in your preferred text editor and start writing the code.
Importing Required Packages
At the top of your main.go file, import the necessary packages:
package main
import (
"flag"
"fmt"
"log"
"os"
)Defining Command-Line Flags
Next, we will define the command-line flags for our calculator. We'll allow users to specify the operation and the two numbers to operate on.
func main() {
// Define command-line flags
operation := flag.String("operation", "add", "Operation to perform: add, subtract, multiply, divide")
num1 := flag.Float64("num1", 0, "First number")
num2 := flag.Float64("num2", 0, "Second number")
// Parse the flags
flag.Parse()
// Perform the calculation
result, err := calculate(*operation, *num1, *num2)
if err != nil {
log.Fatalf("Error: %v", err)
}
// Output the result
fmt.Printf("Result: %f\n", result)
}Implementing the Calculation Logic
Now, we will implement the calculate function that performs the requested operation.
func calculate(operation string, num1, num2 float64) (float64, error) {
switch operation {
case "add":
return num1 + num2, nil
case "subtract":
return num1 - num2, nil
case "multiply":
return num1 * num2, nil
case "divide":
if num2 == 0 {
return 0, fmt.Errorf("cannot divide by zero")
}
return num1 / num2, nil
default:
return 0, fmt.Errorf("unknown operation: %s", operation)
}
}Running Your CLI Tool
To test your CLI tool, build the application:
go buildThis command will create an executable named go-cli-calculator. You can run the tool from the command line:
./go-cli-calculator -operation add -num1 10 -num2 5The expected output will be:
Result: 15.000000Handling Errors Gracefully
Error handling is crucial in any application. In the example above, we return errors from the calculate function and log them using log.Fatalf, which will terminate the program if an error occurs. You can enhance this by providing user-friendly messages or suggestions for valid inputs.
Adding Help and Usage Information
The flag package automatically generates help and usage information, which you can display by running:
./go-cli-calculator -hThis will show the available flags and their descriptions:
Usage of ./go-cli-calculator:
-num1 float
First number
-num2 float
Second number
-operation string
Operation to perform: add, subtract, multiply, divide (default "add")Enhancing the CLI Tool
To make your CLI more robust, consider adding features such as:
- Support for more operations: Extend the
calculatefunction to handle operations like modulus or exponentiation. - Input validation: Ensure that the inputs are valid numbers before performing calculations.
- Configuration files: Allow users to specify default values in a configuration file.
Conclusion
In this tutorial, you have learned how to build a simple CLI tool in Go using the flag package for command-line argument parsing. You have also seen how to structure your application and handle errors effectively. Building CLI tools can significantly enhance your productivity and streamline workflows.
Learn more with useful resources:
