Writing a Basic CLI Application Using Go
Go is a great language for building command-line tools due to its simplicity and powerful standard library. In this article, we will go through how to create a simple CLI app in Go that accepts commands and flags from the user.
Step 1: Install Go
Before you start, ensure that Go is installed on your machine. You can download it from here. Once installed, verify by running:
go version
Step 2: Set Up Your Project
Create a new folder for your project and navigate into it:
mkdir cli-app
cd cli-app
Step 3: Write Your CLI App
In your project folder, create a file called main.go
. This is where we'll write our CLI code.
package main
import (
"flag"
"fmt"
"os"
)
func main() {
name := flag.String("name", "World", "a name to say hello to")
flag.Parse()
if len(os.Args) < 2 {
fmt.Println("Usage: go run main.go --name [your name]")
os.Exit(1)
}
fmt.Printf("Hello, %s!\n", *name)
}
Step 4: Run the Application
You can now run your CLI app by using the following command:
go run main.go --name=John
This will output:
Hello, John!
If you omit the --name
flag, it will default to:
Hello, World!
Step 5: Add More Functionality
You can add more flags to extend your CLI tool. For example, to add a flag for age:
age := flag.Int("age", 0, "your age")
Then use it in the output:
fmt.Printf("Hello, %s! You are %d years old.\n", *name, *age)
This simple guide demonstrates how easy it is to build a basic CLI application using Go. By using Go's flag
package, you can create commands and flags to handle user input efficiently. With more advanced packages, you can build even more powerful CLI tools.
Comments
Post a Comment
Comment on articles for more info.