← Project templates

BASICS · IN THE APP NOW

Command-line tool

The smallest useful Go program with options: two flags, a parsed command line and a greeting on stdout.

Offline: standard library only

Open it in the browser Playground →

What it is

The standard flag package defines each option with a name, a default and a usage string, and returns a pointer that flag.Parse fills in. Run arguments set in the app reach the program as usual.

Every template's Go program was compiled for GOOS=wasip1 GOARCH=wasm with Go 1.27, then run, vetted and tested before it was added to the app.

Files

text
cli/
├── go.mod
└── main.go

The code

main.go

go
package main

import (
	"flag"
	"fmt"
	"strings"
)

func main() {
	name := flag.String("name", "gopher", "who to greet")
	loud := flag.Bool("loud", false, "shout the greeting")
	flag.Parse()

	greeting := fmt.Sprintf("hello, %s", *name)
	if *loud {
		greeting = strings.ToUpper(greeting)
	}
	fmt.Println(greeting)
}

What you learn

  • Declare typed options with flag.String and flag.Bool and read them through pointers.
  • Call flag.Parse once, before the first option is used.
  • Build output with fmt.Sprintf and strings.ToUpper.
  • Get -h usage text from the flag package without writing it yourself.

Run it on a server

Nothing changes: build it and pass the flags on the command line.

bash
go build -o greet .
./greet -name ada -loud
./greet -h

Related: Go core unit · Go toolbelt: modules, tests, vet and build