Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Command-Line Applications

32. Command-Line Applications

Command-line applications are an essential part of many software development tasks. In Go, building command-line applications is straightforward due to the standard library's excellent support for handling command-line arguments and input/output. In this tutorial, we'll explore how to create a basic command-line application in Go.

Step 1: Set Up Your Project:

Before diving into code, create a new directory for your project and set up a Go module:

mkdir mycliapp
cd mycliapp
go mod init mycliapp

 

Step 2: Define Your CLI App:

Now, let's create a simple command-line application that calculates the sum of two numbers passed as command-line arguments.

package main

import (
	"fmt"
	"os"
	"strconv"
)

func main() {
	// Check if the correct number of arguments is provided
	if len(os.Args) != 3 {
		fmt.Println("Usage: mycliapp  ")
		os.Exit(1)
	}

	// Get and parse the command-line arguments
	arg1 := os.Args[1]
	arg2 := os.Args[2]

	num1, err := strconv.Atoi(arg1)
	if err != nil {
		fmt.Println("Invalid number:", arg1)
		os.Exit(1)
	}

	num2, err := strconv.Atoi(arg2)
	if err != nil {
		fmt.Println("Invalid number:", arg2)
		os.Exit(1)
	}

	// Calculate and print the sum
	sum := num1 + num2
	fmt.Printf("Sum of %d and %d is %d\n", num1, num2, sum)
}

 

In this code, we:

  • Check if the correct number of command-line arguments is provided.
  • Parse the two numbers provided as arguments.
  • Calculate their sum and print the result.

Step 3: Build and Run Your CLI App:

You can build and run your CLI app using the 'go'  command:

go build
./mycliapp 10 20

 

This should produce the following output:
Sum of 10 and 20 is 30

 

Step 4: Handle Flags and Options:

To make your CLI app more feature-rich, you can use packages like  'flag' or 'pflag' to handle flags and options. Here's an example using the 'flag'package:

package main

import (
	"flag"
	"fmt"
)

func main() {
	// Define command-line flags
	num1 := flag.Int("num1", 0, "First number")
	num2 := flag.Int("num2", 0, "Second number")

	// Parse command-line arguments
	flag.Parse()

	// Calculate and print the sum
	sum := *num1 + *num2
	fmt.Printf("Sum of %d and %d is %d\n", *num1, *num2, sum)
}

 

With this updated code, you can run your app like this:
go build
./mycliapp -num1=10 -num2=20

 

Step 5: Additional Enhancements:

Depending on your CLI app's complexity, you can add features like subcommands, configuration file support, error handling, and more. You can also use third-party libraries to simplify tasks such as input validation, colored output, and interactive prompts.

Conclusion:

Creating command-line applications in Go is straightforward thanks to the language's excellent support for handling command-line arguments and input/output. You can start with a simple app like the one shown here and gradually add more features as needed for your specific use case.