[Golang] Write a simple CLI program

I will show a simple example in this post. Let’s say the program called cli-example.

package main  

import (
	"flag"
	"fmt"
	"os"
)

func main() {
	command := os.Args[1]
	os.Args = append(os.Args[:1], os.Args[2:]...)

	switch command {
	case "version":
		fmt.Println("1.1.1")
	}
}

The 1st argument will always be the binary name, so the command starts from the 2nd argument. If your app also needs the subcommand, then extract it from the 3rd argument, like docker image ls.

Run ./cli-example version

1.1.1

Without command option, the CLI program is not completed. In Golang, we can implement command option by using flag package

package main

import (
	"flag"
	"fmt"
	"os"
)

func main() {
	command := os.Args[1]
	os.Args = append(os.Args[:1], os.Args[2:]...)

	var all bool

	flag.BoolVar(&all, "all", false, "Print all")
	flag.Parse()

	switch command {
	case "version":
		fmt.Println("1.1.1")

	case "ps":
		fmt.Printf("CONTAINER ID\tIMAGE\n")
		fmt.Printf("%s\t%s\n", "1f95b6030605", "registry:2")
		if all {
			fmt.Printf("%s\t%s\n", "cc88de0b8f35", "quay.io/minio/minio")
		}
	}
}

Run ./cli-example ps.

CONTAINER ID    IMAGE
1f95b6030605    registry:2

Run ./cli-example ps --all.

CONTAINER ID    IMAGE
1f95b6030605    registry:2
cc88de0b8f35    quay.io/minio/minio

A good CLI program definitely needs the help command as well. It can be done like below.

package main

import (
	"flag"
	"fmt"
	"os"
)

func main() {
	command := os.Args[1]
	os.Args = append(os.Args[:1], os.Args[2:]...)

	var all bool

	flag.BoolVar(&all, "all", false, "Print all")
	flag.Parse()

	switch command {
	case "version":
		fmt.Println("1.1.1")

	case "ps":
		fmt.Printf("CONTAINER ID\tIMAGE\n")
		fmt.Printf("%s\t%s\n", "1f95b6030605", "registry:2")
		if all {
			fmt.Printf("%s\t%s\n", "cc88de0b8f35", "quay.io/minio/minio")
		}

	case "help":
		help := 
`Usage: cli-example [OPTIONS] COMMAND 

Options:
	--all	
Commands: 
	ps	List fake containers
	version	Show the version information
		`
		fmt.Println(help)
	}
}

Run ./cli-example help.

Usage: cli-example [OPTIONS] COMMAND 

Options:
        --all
Commands: 
        ps      List fake containers
        version Show the version information

With the CLI program skeleton, you can add more features.


If this post helped you to solve a problem or provided you with new insights, please upvote it and share your experience in the comments below. Your comments can help others who may be facing similar challenges. Thank you!
Buy Me A Coffee
DigitalOcean Referral Badge
Sign up to get $200, 60-day account credit !