Building a Golang Tui Application

Author

Reads 1.2K

A Close-Up Shot of a Terminal
Credit: pexels.com, A Close-Up Shot of a Terminal

Building a Golang Tui Application is a great way to create interactive command-line interfaces. This approach is perfect for building tools that can be used in a terminal environment.

To get started, you'll need to install the "github.com/mabu7942/tui" package, which provides a simple and easy-to-use API for building Tui applications. This package is widely used in the Golang community and is a great choice for beginners.

One of the key benefits of using Tui is that it allows you to create complex interfaces using a simple and intuitive API. This makes it easy to build applications with multiple windows, buttons, and other interactive elements.

Getting Started

To get started with a GoLang TUI project, first create a basic skeleton using the command line.

Create a new directory for your project with `mkdir system-monitor-tui` and navigate into it with `cd system-monitor-tui`.

Then, initialize a new Go module with `go mod init github.com/ivan-penchev/system-monitor-tui` and create a new file called `main.go` with `touch main.go`.

The project structure is now in place, and you can start focusing on the code.

The `main.go` file should start with the basic Go package and import statements, as shown below:

```go

packagemain

import("fmt")

```

This sets the foundation for your TUI project.

Creating the App

Credit: youtube.com, Build a real life Terminal User Interface ( TUI ) Application in Golang

Creating the App is a crucial step in building a tui app with Go. The Application widget is the top-level node of our app, and it's the starting point for everything else.

To create an app, we first call a series of setup methods, including enabling mouse detection and issuing a Run command. This gets our app up and running, but we haven't told it to display anything yet.

We use the SetRoot function to tell the tview app which widget to display when the application starts. In this case, we've chosen to use a Box widget, which is the parent type of all other widgets.

The Box widget can't do much on its own, but it's a great starting point. We can then add other widgets to it to create a more interactive app.

Running this code will display a blank black screen in our terminal. It's not very exciting, but it's a start. We've created an app, but we still need to add some content to it.

Credit: youtube.com, This Go library makes your CLI apps look INSANE

To display our contacts, we need to clear the widget and then rewrite the content. This process is similar to how we saved our contact to the contacts slice earlier.

Finally, we need to add our new textbox to the layout. This will allow us to interact with our app and make it more useful.

Widgets and Pages

Tview is built on top of tcell, which provides an API for interacting with the terminal in Go, and offers pre-built components called widgets that help you create common UI elements like lists, forms, dropdown menus, and tables.

These widgets include tools to help you build layouts with grids, flexboxes, and multiple pages. Tview's widgets are a huge time-saver, allowing you to create complex UIs with ease.

Tview also includes a Pages widget that makes it easy to switch between different views, like pages on a website. This is especially useful when you want to create multiple pages in your app, like a menu and a form page.

Widgets

Man working at desk with computers in office
Credit: pexels.com, Man working at desk with computers in office

Widgets are pre-built components that help you create common UI elements like lists, forms, dropdown menus, and tables. They're built on top of the tcell package, which provides an API for interacting with the terminal in Go.

Tview's widgets make it easy to build layouts with grids, flexboxes, and multiple pages. This is super helpful for creating complex interfaces without having to start from scratch.

A List widget is a great example of a widget in action. It's used to display a list of items, like contacts. You can add items to the list by passing a string, which will be the main text displayed.

The secondary text option is available, but it's turned off in this example to keep things simple. You can pass an empty string to get away with just the main text.

You can also use a rune to display a character next to each item. In this case, numbers 1..n are used, which is achieved by passing the ASCII code for the number 1.

Pages

A TUI Boeing 787 Dreamliner prepares for takeoff on a cloudy day at the airport.
Credit: pexels.com, A TUI Boeing 787 Dreamliner prepares for takeoff on a cloudy day at the airport.

Using a Pages widget allows us to switch between different views like pages on a website.

In the example, we refactored our code to use a Pages widget, creating a page for our Form and a page for our TextView. We can switch between them easily.

The Pages widget offers a special way to switch between views, making it easier to manage multiple pages in our app.

In the main function, we added code to create a page for our Form and a page for our TextView.

We updated our if statement to switch to the form page when the user presses ‘a’. This allows us to easily navigate between the menu and the form.

In our addContactForm function, we updated our save button to bring us back to the menu after the form is filled out.

Now, if we run the code and use the form to add a contact, we should be brought back to the menu and see a list displaying the first and last name of the contact we just added.

User Interaction

Credit: youtube.com, Understanding the Bubble Tea TUI Framework Architecture for Building Terminal Apps in Go/Golang

User Interaction is a crucial aspect of any application, and in the context of GoLang TUI, it's no different. You can respond to events like mouse clicks, on focus actions, and key presses.

To capture key press events, you can use the SetInputCapture function, which takes a function as an argument that gets passed an EventKey type. This function holds information about the key press event, such as the ascii code for the key, which you can access by calling Rune().

If the key pressed is "q", you can call Stop() to quit the application. This is exactly what the example code does, and it's a simple yet effective way to add a quit functionality to your TUI application.

Responding to Input

Tview allows us to respond to all sorts of events that are happening in the terminal, including mouse clicks, on focus actions, and yes, key presses.

We can set up our app to quit when a user presses q by using the SetInputCapture function, which takes a function as an argument that gets passed an EventKey type.

Credit: youtube.com, Asking the user for Information (INPUT)

This EventKey type holds information about the key press event, and we can access the ascii code for the key by calling Rune(). If the key pressed is q, we call Stop() which will quit the application.

We can also update our text view with the info about the new command, but we need to tell our app about our new form and give it a way to switch from the TextView to the Form.

As we learned earlier, we won’t be able to see our list until we give our app a way to display it, but we want to be able to display the List and the TextView that’s displaying our menu options on the same page.

Refreshing

Refreshing is a crucial aspect of user interaction, and it's not just about feeling revitalized after a long day. We can fix issues like duplicates and doubled-up forms by clearing widgets each time we change pages.

Credit: youtube.com, The Refreshed SLS User Interface

The current system adds to the existing page, rather than recreating it with new updates. This is a common problem that can be easily addressed.

Clearing widgets is a simple solution that can make a big difference in user experience. Now, users can add multiple contacts without seeing duplicates and without doubling up on forms.

Writing the App

Creating an app in Go TUI is a straightforward process. We start with the top-level node, the Application, which we set up by enabling mouse detection and issuing a Run command.

The SetRoot function tells the app which widget to display when it starts. We've chosen to use a Box widget as the top-level widget, which is the parent type of all other widgets.

We've created an app, but it's not doing much yet – it's just a blank black screen. We can end the program by pressing ctrl+c. To add some content, we'll need to clear the widget and rewrite its content.

Installing Tview

Two women working together on code at a computer in a modern office setting.
Credit: pexels.com, Two women working together on code at a computer in a modern office setting.

Installing Tview is a straightforward process. To get started, you'll need to run the command "go get github.com/rivo/tview" in your terminal.

This will download the necessary files and make them available for use in your project. You can then import both tview and tcell in your main.go file.

Go1.22.3 Windows/AMD64

To get started with writing the app, you're using Go version go1.22.3 on Windows/AMD64. This version is a great choice for building a TUI.

The installation process begins with setting up Go, which will guide you step by step through the environment setup.

You'll then move on to installing the tview package, which will be a crucial part of your TUI.

The building process of the TUI will involve designing and coding the interface, making it interactive and visually appealing.

Define Our Model

To define our model, we need to create a struct that implements the tea.Model interface. This interface requires three methods: Init, Update, and View.

TUI Airways plane taxiing on a runway under a cloudy sky. Perfect for travel and aviation themes.
Credit: pexels.com, TUI Airways plane taxiing on a runway under a cloudy sky. Perfect for travel and aviation themes.

The Init method is called once when the app starts and is used to initialize the model and set up any initial commands. If we don't want to perform any initial commands, we simply return nil.

The Update method is called when a message is received and is used to inspect messages and update the model accordingly. It can also send a command in response to the message.

The View method renders the program's UI as a string. It's called after every Update.

Our model will store some data for our state, including the width and height of the terminal, a table for processing, and various system statistics like CPU and memory usage.

Here's a breakdown of the required methods for our model:

These methods provide a solid foundation for our model, allowing us to store and update our state while also rendering a user-friendly interface.

Tview and TUI

Tview is a comprehensive library for building rich Terminal User Interfaces (TUIs) in Go.

Credit: youtube.com, From Bash to Golang: Elevate Your Terminal Experience with Tview

It offers a variety of components such as tables, forms, lists, and more, enabling developers to craft intricate terminal applications.

Tview operates seamlessly across various Unix/Linux terminals and Windows command prompts, making it a cross-platform solution.

Here are the key features of tview:

  • Cross-Platform Compatibility
  • Rich Component Set
  • Event Handling
  • Customizable Styling
  • Developer-Friendly API

The library emphasizes a functional programming paradigm, promoting clear and maintainable code structures, making it easier for developers to create and maintain their applications.

Why a Tui?

A TUI is a great way to automate interactions and reduce the need to rely on memory. We can do this by scripting repetitive tasks, which is a common approach that many engineers use.

Scripting repetitive tasks can be a huge time-saver, but it often lacks a user-friendly interface. This is where a TUI comes in – it provides a graphical interface within a text-only terminal environment, making it easier to navigate and use.

A TUI can offer a better user experience than a simple script, with features like immediate feedback, error handling, and a more intuitive navigation system. This can be especially important for complex or critical tasks.

Credit: youtube.com, The best TUIs - powerful terminal apps

Here are some benefits of using a TUI:

  • Automates procedures to ensure processes are followed accurately and efficiently
  • Reduces the risk of human error
  • Increases productivity

By using a TUI, engineers can focus on more important tasks and reduce the likelihood of mistakes. And, as one engineer noted, making a TUI can be a fun and rewarding experience, especially when it aligns with your goals and can be helpful to others.

Tview

Tview is a comprehensive library designed for building rich TUIs in Go. It offers a variety of components such as tables, forms, lists, and more, enabling developers to craft intricate terminal applications.

Key features of tview include Cross-Platform Compatibility, Rich Component Set, Event Handling, Customizable Styling, and a Developer-Friendly API. These features allow developers to build complex terminal applications with ease.

Here are the key features of tview in a concise list:

  • Cross-Platform Compatibility
  • Rich Component Set
  • Event Handling
  • Customizable Styling
  • Developer-Friendly API

tview is designed with simplicity in mind, allowing for quick onboarding and reduced complexity in terminal UI development. This makes it an ideal choice for developers who want to build complex terminal applications without getting bogged down in complicated code.

Publishing

Credit: youtube.com, Golang TUI Project Basics - Shopping List | Part I

Publishing a Go TUI can be a challenge, especially when working with external tools. Publishing my TUI to homebrew was a struggle.

I learned that sqlite, a database engine written in C, relies on CGO, which is using C in your Go code. This caused issues with gorelaser, the tool I used to publish my TUI.

To fix this, I used goreleaser-cross and set the CGO_ENABLED environment variable to 1 in my .goreleaser.yml file. This was a crucial step in getting CGO to work with gorelaser.

I also eliminated the binaries for linux and windows to avoid supporting them. It's a good idea to keep things simple and focus on your target platform.

I still don't fully understand what's going on in my Makefile, but I was able to figure out how to publish releases and create release candidates.

Victoria Kutch

Senior Copy Editor

Victoria Kutch is a seasoned copy editor with a keen eye for detail and a passion for precision. With a strong background in language and grammar, she has honed her skills in refining written content to convey a clear and compelling message. Victoria's expertise spans a wide range of topics, including digital marketing solutions, where she has helped numerous businesses craft engaging and informative articles that resonate with their target audiences.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.