Table of Contents
Introduction
In this tutorial, we will learn how to write a command-line interface (CLI) tool using Go that can read data and visualize it. By the end of this tutorial, you will have a Go-based CLI tool that can read data from a file, process it, and generate a visual representation of the data.
Prerequisites
To follow along with this tutorial, you should have a basic understanding of the Go programming language and how to set up a Go development environment. You should also have Go installed on your machine. If you need help with the installation process, please refer to the official Go documentation.
Setup
Before we can start writing our CLI tool, we need to set up a new Go module. Open your terminal and navigate to the directory where you want to create your project. Then, run the following command to initialize a new Go module:
go mod init cli-tool
This command creates a new Go module named “cli-tool” in the current directory.
Creating the CLI Tool
Let’s create a new Go file named “cli.go” in your project directory. This file will contain our main program.
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Welcome to the Data Visualization CLI tool!")
}
In the above code, we import the necessary packages, including fmt
for printing messages to the console and os
for handling command-line arguments and file operations. The main
function is the entry point of our CLI tool, and it simply prints a welcome message to the console.
To compile and run our CLI tool, execute the following command:
go run cli.go
You should see the “Welcome to the Data Visualization CLI tool!” message displayed in the console.
Reading Data
Now, let’s add functionality to read data from a file. We will use the os
package to get the file path from the command-line arguments and read the file contents.
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Usage: cli [file-path]")
os.Exit(1)
}
filePath := os.Args[1]
data, err := ioutil.ReadFile(filePath)
if err != nil {
fmt.Printf("Error reading file: %s\n", err.Error())
os.Exit(1)
}
fmt.Println("Data:", string(data))
}
In the above code, we check if the command-line arguments contain the file path. If not, we print a usage message and exit the program. Otherwise, we read the file contents using ioutil.ReadFile
and print the data to the console.
To test the “Reading Data” functionality, create a new text file named “data.txt” in the project directory and add some sample data. Then, run the CLI tool with the path to the “data.txt” file:
go run cli.go data.txt
You should see the contents of the “data.txt” file displayed in the console.
Data Visualization
Now that we can read data from a file, let’s add data visualization functionality to our CLI tool using a third-party Go package named “termui”.
To use “termui”, we first need to install it. Execute the following command in your terminal:
go get github.com/gizak/termui/v3
Once the package is installed, update your main program to use “termui” for data visualization:
package main
import (
"fmt"
"io/ioutil"
"os"
ui "github.com/gizak/termui/v3"
"github.com/gizak/termui/v3/widgets"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Usage: cli [file-path]")
os.Exit(1)
}
filePath := os.Args[1]
data, err := ioutil.ReadFile(filePath)
if err != nil {
fmt.Printf("Error reading file: %s\n", err.Error())
os.Exit(1)
}
err = ui.Init()
if err != nil {
fmt.Printf("Failed to initialize termui: %s\n", err.Error())
os.Exit(1)
}
defer ui.Close()
// Create a new BarChart widget
bc := widgets.NewBarChart()
// Set the BarChart data
bc.Data = []float64{1, 3, 2, 5, 4, 8}
// Render the BarChart on the terminal
ui.Render(bc)
// Wait for user input to exit
uiEvents := ui.PollEvents()
for {
e := <-uiEvents
if e.Type == ui.KeyboardEvent {
break
}
}
}
In the updated code, we import the necessary packages, including "github.com/gizak/termui/v3"
for using “termui” and "github.com/gizak/termui/v3/widgets"
for creating visual widgets like BarChart
.
We initialize the “termui” library using ui.Init()
and defer the cleanup using defer ui.Close()
to ensure the program shuts down gracefully. We create a new BarChart
widget, set the data to be visualized on the chart, and render it on the terminal using ui.Render(bc)
.
To test the “Data Visualization” functionality, update the “data.txt” file with a series of numbers separated by spaces or new lines. Then, run the CLI tool with the path to the “data.txt” file:
go run cli.go data.txt
You should see a bar chart representing the data from the “data.txt” file displayed in the terminal.
Conclusion
Congratulations! You have successfully created a Go-based CLI tool for data visualization. In this tutorial, we learned how to read data from a file, process it, and visualize it using the “termui” package. You can further enhance the tool by adding additional visual widgets or customizing the data visualization.
Feel free to explore the Go documentation for more information on Go programming and the “termui” documentation for advanced usage of the library.
Remember to check out the Go and “termui” documentation for more information about the available functions and customization options.
Happy coding!