How to Add Flags and Arguments to a Go CLI

Cli
Define flags using the flag package and access positional arguments via flag.Args() after calling flag.Parse().

Use the flag package to define flags and os.Args to access positional arguments. Define flags with flag.String, flag.Int, or flag.Bool, then call flag.Parse() before accessing them.

package main

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

func main() {
	name := flag.String("name", "World", "A name to greet")
	count := flag.Int("count", 1, "Number of greetings")
	flag.Parse()

	args := flag.Args()
	for i := 0; i < *count; i++ {
		fmt.Printf("Hello, %s!\n", *name)
		if len(args) > 0 {
			fmt.Println("Extra arg:", args[0])
		}
	}
}

Run with: go run main.go -name=Go -count=2 extra-text