Ever wanted to create a powerful Command Line Interface (CLI) app using Go? Well, you’re in the right place! Let’s build a Go CLI that actually does something useful.
Why Build a CLI in Go? (Because Typing is Cool!)
- Performance – Runs fast with minimal memory usage.
- Cross-platform – Works on Windows, macOS, and Linux.
- Easy to Build – The standard library is enough to get started.
Setting Up Your Go CLI Project (Let's Get Started!)
First, ensure Go is installed. Then create a new project:
mkdir go-cli && cd go-cli
go mod init github.com/yourusername/go-cli
Install the cobra package for better CLI handling:
go get -u github.com/spf13/cobra@latest
Writing Your First CLI Command (It's Easier Than You Think!)
Create a new file main.go
and add:
package main
import (
"fmt"
"github.com/spf13/cobra"
)
func main() {
var rootCmd = &cobra.Command{
Use: "greet",
Short: "Prints a greeting message",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hello, CLI world!")
},
}
rootCmd.Execute()
}
Run it:
go run main.go
You should see:
Hello, CLI world!
Boom! You just made your first CLI app!
Adding Flags and Arguments (Because Options Are Cool!)
Modify main.go
to accept a name argument:
var name string
func main() {
var rootCmd = &cobra.Command{
Use: "greet",
Short: "Prints a greeting message",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Hello, %s!\n", name)
},
}
rootCmd.Flags().StringVarP(&name, "name", "n", "World", "Name to greet")
rootCmd.Execute()
}
Run it:
go run main.go --name=Alice
You should see:
Hello, Alice!
You just built your first Go CLI app! Keep improving it by adding subcommands, config files, and even colorful output. The CLI world is yours!
0 Comments