
Go: Building and Using a Simple Command-Line Application with Flags
Prerequisites
Before you begin, ensure you have the following:
- Go installed on your machine (version 1.16 or higher).
- A text editor or IDE of your choice (e.g., Visual Studio Code, GoLand).
- Basic understanding of Go syntax and structure.
Setting Up Your Go Environment
- Create a New Directory: Start by creating a directory for your project.
mkdir go-cli-app
cd go-cli-app- Initialize a Go Module: Run the following command to initialize a new Go module.
go mod init go-cli-appCreating the Command-Line Application
Now, let's create a simple command-line application that takes two numbers as input and performs addition.
- Create a New File: Create a file named
main.go.
touch main.go- Write the Code: Open
main.goand add the following code:
package main
import (
"flag"
"fmt"
"os"
)
func main() {
// Define command-line flags
var num1 float64
var num2 float64
flag.Float64Var(&num1, "num1", 0, "First number")
flag.Float64Var(&num2, "num2", 0, "Second number")
// Parse the flags
flag.Parse()
// Check if the flags were provided
if num1 == 0 && num2 == 0 {
fmt.Println("Please provide two numbers using the -num1 and -num2 flags.")
os.Exit(1)
}
// Perform addition
result := num1 + num2
fmt.Printf("The sum of %.2f and %.2f is %.2f\n", num1, num2, result)
}Explanation of the Code
- Package Declaration: The
package mainindicates that this is an executable program. - Imports: We import the
flag,fmt, andospackages. Theflagpackage is used for command-line flag parsing,fmtfor formatted I/O, andosfor handling OS-level operations. - Flag Definitions: We define two flags,
num1andnum2, which are of typefloat64. TheFloat64Varfunction binds the flags to the variables. - Parsing Flags: The
flag.Parse()function processes the command-line arguments. - Validation: We check if both numbers are zero and prompt the user if they are not provided.
- Calculation and Output: Finally, we calculate the sum and print the result.
Running the Application
To run your application, use the following command in your terminal:
go run main.go -num1 5.5 -num2 4.5Expected Output
The output should display the sum of the two numbers:
The sum of 5.50 and 4.50 is 10.00Handling Errors
It’s essential to handle potential errors gracefully. For instance, if a user provides non-numeric input, the application should inform the user without crashing. You can enhance error handling using the flag package's built-in error reporting.
Advanced Features: Adding More Flags
You can expand your command-line application by adding more flags. For example, let’s add a flag to specify the operation (addition, subtraction, multiplication, division).
- Modify the Code: Update your
main.goas follows:
package main
import (
"flag"
"fmt"
"os"
)
func main() {
var num1 float64
var num2 float64
var operation string
flag.Float64Var(&num1, "num1", 0, "First number")
flag.Float64Var(&num2, "num2", 0, "Second number")
flag.StringVar(&operation, "operation", "add", "Operation to perform: add, subtract, multiply, divide")
flag.Parse()
if num1 == 0 && num2 == 0 {
fmt.Println("Please provide two numbers using the -num1 and -num2 flags.")
os.Exit(1)
}
var result float64
switch operation {
case "add":
result = num1 + num2
case "subtract":
result = num1 - num2
case "multiply":
result = num1 * num2
case "divide":
if num2 == 0 {
fmt.Println("Error: Division by zero is not allowed.")
os.Exit(1)
}
result = num1 / num2
default:
fmt.Println("Invalid operation. Use add, subtract, multiply, or divide.")
os.Exit(1)
}
fmt.Printf("The result of %s %.2f and %.2f is %.2f\n", operation, num1, num2, result)
}Running the Updated Application
You can now specify the operation you wish to perform:
go run main.go -num1 10 -num2 2 -operation divideExpected Output
The result of divide 10.00 and 2.00 is 5.00Conclusion
In this tutorial, you learned how to build a simple command-line application in Go using the flag package. You created a program that accepts user input for two numbers and an operation, performs the calculation, and displays the result. This foundational knowledge can be expanded to create more complex command-line tools tailored to your needs.
