COMMAND LINE · IN THE APP NOW
Cobra CLI
A command-line tool called forge with two subcommands, built the way larger Go CLIs are: a command tree, typed flags and argument rules.
Downloads github.com/spf13/cobra on first build
What it is
Cobra is not bundled with the app. The project's go.mod requires github.com/spf13/cobra v1.10.2, with spf13/pflag and inconshreveable/mousetrap as indirect requirements, and the first build downloads them from the Go module proxy.
Run arguments set in the app go to the program as usual. With none, main runs a short demonstration of three commands through root.SetArgs.
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
cobra-cli/
├── go.mod
├── go.sum
└── main.goThe code
main.go
package main
import (
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
)
func newRootCommand() *cobra.Command {
root := &cobra.Command{
Use: "forge",
Short: "A small command-line tool built with Cobra",
}
var shout bool
greet := &cobra.Command{
Use: "greet [name]",
Short: "Greet someone",
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
name := "gopher"
if len(args) == 1 {
name = args[0]
}
message := fmt.Sprintf("hello, %s", name)
if shout {
message = strings.ToUpper(message)
}
fmt.Fprintln(cmd.OutOrStdout(), message)
},
}
greet.Flags().BoolVarP(&shout, "shout", "s", false, "print in capitals")
count := &cobra.Command{
Use: "count word...",
Short: "Count the words given",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Fprintf(cmd.OutOrStdout(), "%d words\n", len(args))
},
}
root.AddCommand(greet, count)
return root
}
// Cobra is downloaded on the first build. Run arguments go to the program as
// usual; with none, a short demonstration runs instead.
func main() {
root := newRootCommand()
if len(os.Args) > 1 {
if err := root.Execute(); err != nil {
os.Exit(1)
}
return
}
for _, args := range [][]string{{"greet"}, {"greet", "ada", "--shout"}, {"count", "go", "is", "fun"}} {
fmt.Printf("$ forge %s\n", strings.Join(args, " "))
root.SetArgs(args)
_ = root.Execute()
}
}What you learn
- Build a command tree with cobra.Command and AddCommand.
- Validate positional arguments with cobra.MaximumNArgs and cobra.MinimumNArgs.
- Bind a flag with a long and a short name using BoolVarP.
- Write through cmd.OutOrStdout so output can be captured.
- Drive commands from code with SetArgs and Execute.
Run it on a server
Build a binary and call it like any other command. Cobra adds --help and a help command.
go build -o forge .
./forge greet ada --shout
./forge count go is fun
./forge --helpRelated: Around Go: command line · Explain the selected version before running go get