How to Build a CLI Application in Go

Cli
Initialize a Go module, write a main function to handle arguments, and compile the binary to create a CLI application.

You build a CLI application in Go by initializing a module, writing a main function that parses arguments, and compiling the binary with go build.

package main

import (
	"fmt"
	"os"
)

func main() {
	if len(os.Args) > 1 {
		fmt.Println("Hello,", os.Args[1])
	} else {
		fmt.Println("Hello, World")
	}
}
  1. Initialize a new module with go mod init myapp.
  2. Create a file named main.go and paste the code above into it.
  3. Build the executable binary using go build -o myapp.
  4. Run your new CLI tool by executing ./myapp.