I love CLI applications. They are lightweight, no-dependency, and consume fewer resources. However, building an application for the terminal from scratch is far from easy.

Fortunately, we can always simplify the task with tools or libraries. In this tutorial, I’ll show you how to build a terminal-based dashboard in less than 300 lines of Golang source code by leveraging a great terminal library, termui.

Background

We have a web application that serves millions of users a day. And we want to monitor the real-time memory consumption (and GC) of this application.

You may think about some monitor system and observability platforms like Prometheus + Grafana, but it’s a little bit overkill for this situation.

So I decided to build a simple one in Golang.

How it works

Golang has built-in support for memory statistics: runtime.MemStats.

This object could be exposed via HTTP at /debug/vars in JSON format.

All we need to do is import _ “expvar” in our HTTP server(For more detail, please refer to the official doc of expvar).

Below are the fields of runtime.MemStats I’d like to monitor:

HeapObjects, is the number of allocated heap objects. Sys, is the total bytes of memory obtained from the OS. GCCPUFraction, is the fraction of this program's available CPU time used by the GC since the program started. HeapAlloc, is bytes of allocated heap objects. HeapInuse / HeapIdle, is bytes in in-use/idle spans. —from official golang document

My plan is to fetch statistics data from the web application and visualize them in a terminal dashboard.

The UX design is quite intuitive, every field is presented in an appropriate manner: