GoLang – 22 – Creating CLI (Command Line Interface) Applications

Creating CLI Applications in Go: Parsing Command-Line Arguments and Formatting Output

Command-Line Interface (CLI) applications are a common use case in software development. In this section, we’ll explore how to create CLI applications in Go, covering the parsing of command-line arguments and formatting output for a user-friendly experience.

Parsing Command-Line Arguments

Parsing command-line arguments is essential for CLI applications, allowing users to provide input and configuration. Go provides the “flag” and “pflag” packages to handle command-line arguments efficiently.

Using the “flag” Package

The “flag” package simplifies the process of defining and parsing command-line flags. Here’s how to create and parse flags:


package main

import (
    "flag"
    "fmt"
)

func main() {
    var name string
    var age int

    flag.StringVar(&name, "name", "", "User's name")
    flag.IntVar(&age, "age", 0, "User's age")

    flag.Parse()

    fmt.Printf("Name: %s\n", name)
    fmt.Printf("Age: %d\n", age)
}

In this example, the “flag” package is used to define two flags, “name” and “age.” Users can provide these flags when running the CLI application. The “flag.Parse()” function parses the provided flags, making them available for use in the application.

Using the “pflag” Package

The “pflag” package, an enhanced version of the “flag” package, offers more features like subcommands and a POSIX/GNU-style command line. It provides a more user-friendly and flexible CLI experience.


package main

import (
    "github.com/spf13/pflag"
    "fmt"
)

func main() {
    var name string
    var age int

    pflag.StringVarP(&name, "name", "n", "", "User's name")
    pflag.IntVarP(&age, "age", "a", 0, "User's age")

    pflag.Parse()

    fmt.Printf("Name: %s\n", name)
    fmt.Printf("Age: %d\n", age)
}

With “pflag,” you can define flags using the “VarP” function and provide both short and long flag names, making the CLI application more user-friendly.

Formatting Output

Formatting output is essential for conveying information to the user in a readable and structured manner. Go provides various ways to format output, such as using the “fmt” package and templates.

Using the “fmt” Package

The “fmt” package provides a variety of functions for formatting and printing output. Here are some examples:


package main

import (
    "fmt"
)

func main() {
    name := "Alice"
    age := 30

    // Basic printing
    fmt.Print("Hello, ")
    fmt.Println(name)

    // Printf for formatted output
    fmt.Printf("Name: %s, Age: %d\n", name, age)

    // Sprintf to format into a string
    formatted := fmt.Sprintf("Name: %s, Age: %d", name, age)
    fmt.Println(formatted)
}

The “fmt” package’s functions like “Print,” “Printf,” and “Sprintf” allow you to format and print output in different ways.

Using Templates

Go’s text/template and html/template packages provide a powerful way to format output using templates. Templates are especially useful for generating dynamic content, such as HTML or configuration files.


package main

import (
    "fmt"
    "os"
    "text/template"
)

func main() {
    data := struct {
        Name string
        Age  int
    }{
        Name: "Bob",
        Age: 25,
    }

    templateStr := "Name: {{.Name}}, Age: {{.Age}}"
    tmpl, err := template.New("example").Parse(templateStr)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(1)
    }

    err = tmpl.Execute(os.Stdout, data)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(1)
    }
}

In this example, a template is defined, and data is passed to it. The “tmpl.Execute” function processes the template and writes the formatted output to the standard output.

Example of a CLI Application

Let’s look at an example of a simple CLI application that parses command-line arguments and formats output:


package main

import (
    "flag"
    "fmt"
)

func main() {
    var name string
    var age int

    flag.StringVar(&name, "name", "", "User's name")
    flag.IntVar(&age, "age", 0, "User's age")

    flag.Parse()

    if name == "" {
        fmt.Println("Please provide a name using the -name flag.")
        return
    }

    if age <= 0 {
        fmt.Println("Please provide a valid age using the -age flag.")
        return
    }

    fmt.Printf("Name: %s\n", name)
    fmt.Printf("Age: %d\n", age)
}

In this example, the CLI application accepts user information via the “name” and “age” flags, performs basic validation, and formats the output.

Creating CLI applications in Go is a common use case. By understanding how to parse command-line arguments and format output, you can build powerful and user-friendly command-line tools.