Announcement

👇Official Account👇

Welcome to join the group & private message

Article first/tail QR code

Skip to content

Go CLI Utility Development Practice

Preface

While searching for documentation, I saw someone using Rust to write a terminal weather query tool. Inspired, I tried to use golang to create a command-line utility. The result is as follows:

In fact, using golang to write is very convenient, with many available libraries.

Cobra Library

cobra is a command-line program library for writing CLI programs. It also provides a scaffolding tool for generating cobra-based application frameworks. Many well-known open-source projects use cobra for CLI construction, such as Kubernetes, Hugo, etcd, etc.

Installation

shell
go get github.com/spf13/cobra/cobra

Note: After installation, check go/bin/ to see if the command is available.

Usage

Create a new project folder pf_tools and initialize the project:

shell
cobra-cli init

This initializes a CLI project with the following structure:

├── LICENSE
├── README.md
├── cmd
│   ├── pfM.go
│   ├── pfWt.go
│   └── root.go
├── go.mod
├── go.sum
├── main.go
└── pak
    ├── mobile.go
    └── weather.go

In the cmd directory, root.go is generated by default, with code like:

go
// ... Go code unchanged ...

cobra.Command represents a command, with the following properties:

  • Use: command name
  • Short: short description
  • Long: full description
  • Run: function to execute when the command is run

rootCmd.Execute() is the entry point for command execution. It parses os.Args[1:] (by default, or can be set via Command.SetArgs), traverses the command tree, and finds the appropriate match and flag.

Add Subcommands

Since the utility has more than one function, you need to add subcommands, such as:

shell
cobra-cli add pf_m

pf_m is used to query mobile phone attribution, with the following effect:

The code is similar to root.go, just add a command and initialize it, then implement the function.

Termui Library

To make the terminal display look better, I used the termui library, which is a fully customizable cross-platform terminal dashboard and widget library built on termbox-go.

Installation

Since go mod is used for management, just use go mod directly.

Import in code:

go
    ui "github.com/gizak/termui/v3"
    "github.com/gizak/termui/v3/widgets"

Then run go mod tidy to download dependencies.

Layout

The weather query uses the Table widget, code as follows:

go
// ... Go code unchanged ...

The mobile query uses the List widget, code as follows:

go
// ... Go code unchanged ...

The structure doesn't change much. The official termui GitHub repo has examples, but some properties like table.Title, l.TitleStyle are not used in the official examples and need to be tried out yourself.

Code Address

https://github.com/PFinal-tool/pf_tools

Finally, have fun!

Last updated: