Skip to content

Instantly share code, notes, and snippets.

@StevenACoffman
Last active March 12, 2026 15:24
Show Gist options
  • Select an option

  • Save StevenACoffman/9741542fc5c005f702370a0ccc9d716a to your computer and use it in GitHub Desktop.

Select an option

Save StevenACoffman/9741542fc5c005f702370a0ccc9d716a to your computer and use it in GitHub Desktop.
Command Pattern in Go

This is the command pattern in Go, for CLIs

package base
type Command struct {
// Run runs the command. The args are the arguments after the command name.
Run func(cmd *Command, args []string)
// UsageLine is the one-line usage message.
UsageLine string
// Short is the short description shown in the 'help' output.
Short string
// Long is the long message shown in the 'go help <this-command>' output.
Long string
}
package main
import (
"fmt"
"os"
"main/base"
)
func NewFirstCommand() *base.Command {
cmd := &base.Command{
UsageLine: "c1",
Short: "command1",
Long: "Sample command, the first one",
Run: runMyFirstCommand,
}
return cmd
}
func runMyFirstCommand(cmd *base.Command, args []string) {
fmt.Println("Hello from command1")
}
func NewSecondCommand() *base.Command {
cmd := &base.Command{
UsageLine: "c2",
Short: "command2",
Long: "Sample command, the second one",
Run: runMySecondCommand,
}
return cmd
}
func runMySecondCommand(cmd *base.Command, args []string) {
fmt.Println("Hello from command2")
}
func main() {
arg := os.Args[1]
cmd1 := NewFirstCommand()
cmd2 := NewSecondCommand()
var m = make(map[string]*base.Command)
m[cmd1.UsageLine] = cmd1
m[cmd2.UsageLine] = cmd2
var cmd = m[arg]
cmd.Run(cmd, nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment