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

  1. Create a New Directory: Start by creating a directory for your project.
   mkdir go-cli-app
   cd go-cli-app
  1. Initialize a Go Module: Run the following command to initialize a new Go module.
   go mod init go-cli-app

Creating the Command-Line Application

Now, let's create a simple command-line application that takes two numbers as input and performs addition.

  1. Create a New File: Create a file named main.go.
   touch main.go
  1. Write the Code: Open main.go and 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 main indicates that this is an executable program.
  • Imports: We import the flag, fmt, and os packages. The flag package is used for command-line flag parsing, fmt for formatted I/O, and os for handling OS-level operations.
  • Flag Definitions: We define two flags, num1 and num2, which are of type float64. The Float64Var function 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.5

Expected Output

The output should display the sum of the two numbers:

The sum of 5.50 and 4.50 is 10.00

Handling 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).

  1. Modify the Code: Update your main.go as 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 divide

Expected Output

The result of divide 10.00 and 2.00 is 5.00

Conclusion

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.

Learn more with useful resources