Go CLI Basics
Introduction to Go CLI
Go (Golang) provides excellent support for building command-line interfaces (CLI). The language's simplicity and performance make it an ideal choice for creating tools and utilities that run in a terminal. This document covers the basics of building a CLI application in Go, including handling arguments, flags, and command structures.
Setting Up a Go CLI Application
1. Creating a New Go Project
To start building a CLI application, create a new Go project:
mkdir my-cli-app
cd my-cli-app
go mod init my-cli-app
2. Writing Your First CLI Program
Create a new file named main.go
and add the following code:
package main
import (
"fmt"
"os"
)
func main() {
// Print a welcome message
fmt.Println("Welcome to My CLI Application!")
// Check for arguments
if len(os.Args) > 1 {
fmt.Println("Arguments passed:", os.Args[1:])
} else {
fmt.Println("No arguments provided.")
}
}
3. Running Your CLI Application
To run your CLI application, use the following command:
go run main.go arg1 arg2
You should see the output:
Welcome to My CLI Application!
Arguments passed: [arg1 arg2]
Handling Command-Line Flags
Go provides the flag
package for parsing command-line flags. Here's how to use it:
1. Importing the Flag Package
Add the flag
package to your imports:
import (
"flag"
"fmt"
"os"
)
2. Defining Flags
Modify your main.go
to include flag definitions:
func main() {
// Define a string flag
name := flag.String("name", "User", "Your name")
// Parse the flags
flag.Parse()
// Print a welcome message
fmt.Printf("Welcome to My CLI Application, %s!\n", *name)
// Check for additional arguments
if len(flag.Args()) > 0 {
fmt.Println("Additional arguments:", flag.Args())
}
}
3. Running with Flags
You can now run your application with flags:
go run main.go -name=John arg1 arg2
Output:
Welcome to My CLI Application, John!
Additional arguments: [arg1 arg2]
Structuring Your CLI Application
For more complex applications, consider structuring your CLI with subcommands. You can use libraries like Cobra or urfave/cli for better command management.
Example with Cobra
-
Install Cobra:
go get -u github.com/spf13/cobra/cobra
-
Create a New Command:
Create a new file
cmd/root.go
and define your commands:package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "mycli",
Short: "My CLI Application",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Welcome to My CLI Application!")
},
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
} -
Integrate in main.go:
Update
main.go
to callExecute()
from thecmd
package:package main
import "my-cli-app/cmd"
func main() {
cmd.Execute()
}
Conclusion
Building a CLI in Go is straightforward and efficient. By using the built-in flag
package or leveraging external libraries like Cobra, you can create powerful command-line applications that are easy to use and extend. Start experimenting with these basics to build your CLI tools!