Skip to content
← back|oz@writing:~$

Building a CLI Tool in Go

Building CLI tools in Go is a rewarding experience. The standard library provides everything you need to create powerful command-line applications.

Why Go?

Go offers several advantages for CLI development:

  • Single binary distribution
  • Fast compilation
  • Excellent standard library for I/O operations
  • Easy cross-compilation

Getting Started

Here's a simple example of a Go CLI that accepts a subcommand:

package main
 
import (
    "fmt"
    "os"
)
 
func main() {
    if len(os.Args) < 2 {
        fmt.Println("Usage: mycli <command>")
        os.Exit(1)
    }
 
    switch os.Args[1] {
    case "init":
        fmt.Println("Initializing...")
    case "build":
        fmt.Println("Building...")
    default:
        fmt.Printf("Unknown command: %s\n", os.Args[1])
        os.Exit(1)
    }
}

Key Takeaways

  • Use the flag package for parsing command-line arguments
  • Consider using a library like cobra for complex CLI applications
  • Always handle errors explicitly

That's it for this quick introduction to building CLIs in Go!