Monitor hard disk usage with Go
Signed vs. Unsigned
The Statfs()
function returns the remaining disk space in line 64 as uint64
, (i.e., as an unsigned 64-bit integer that can never assume a negative value). However, the difference between two of these values can definitely be negative.
If you simply subtract both values from each other, you might be surprised to see that Go (like other languages) returns absolutely insane values for the difference if the subtrahend (the number we're subtracting) turns out to be larger than the minuend (the number we're subtracting from). The result should be negative in this case, but instead you get very large positive values. Without any help, Go assumes that the result of an operation with two unsigned integers is also an unsigned integer. The solution: Typecasting with int(x-y)
makes it clear to Go that the result of the difference of two uint64
values x
and y
is in fact a signed value.
But before line 51 divides the difference by an empirically determined value of 100,000, resulting in a floating point value between
and 1
for the average disk performance, line 48 first needs to convert the result type to float64
. Now, if the velocity is greater than 1
or less than -1
, the if-else construct from line 53 squashes it into the range between -1
and +1
.
All that remains for the main program in Listing 1 to do is to determine the current directory (line 10), start the user interface (UI) (line 17), and close it in any situation with the defer
statement in line 18 as soon as the main program stops running.
On the Screen
Listing 2 shows how the program conjures up the UI with the speedometer display in a terminal window using the tried and tested termui project from GitHub. It defines three stacked widgets: a paragraph widget to display the program name Disk Speedo v1.0
, a progress bar of the Gauge
type, and a pie chart of the PieChart
type that forms the speedometer.
Listing 2
ui.go
01 package main 02 import ( 03 "math" 04 tui "github.com/gizak/termui/v3" 05 "github.com/gizak/termui/v3/widgets" 06 ) 07 type UI struct { 08 Gauge *widgets.Gauge 09 Pie *widgets.PieChart 10 Head *widgets.Paragraph 11 } 12 13 func NewUI() *UI { 14 h := widgets.NewParagraph() 15 h.TextStyle.Fg = tui.ColorBlack 16 h.SetRect(6, 1, 30, 2) 17 h.Text = "Disk Speedo v1.0" 18 h.Border = false 19 g := widgets.NewGauge() 20 g.SetRect(2, 2, 28, 5) 21 g.Percent = 0 22 g.BarColor = tui.ColorRed 23 p := widgets.NewPieChart() 24 p.SetRect(-10, 5, 40, 20) 25 p.Border = false 26 p.Data = fract(0) 27 p.AngleOffset = -1.5 * math.Pi 28 return &UI{Gauge: g, 29 Pie: p, Head: h} 30 } 31 32 func (ui UI) Run() chan bool { 33 done := make(chan bool) 34 err := tui.Init() 35 if err != nil { 36 panic("termui init failed") 37 } 38 39 go func() { 40 events := tui.PollEvents() 41 for { 42 select { 43 case e := <-events: 44 switch e.ID { 45 case "q", "<C-c>": 46 done <- true 47 return 48 } 49 } 50 } 51 }() 52 return done 53 } 54 55 func (ui UI) Close() { 56 tui.Close() 57 } 58 59 func (ui UI) Update( 60 level int, 61 speed float64) { 62 ui.Gauge.Percent = level 63 ui.Pie.Colors = []tui.Color{ 64 tui.ColorBlack, tui.ColorRed} 65 if speed < 0 { 66 ui.Pie.Colors[1] = 67 tui.ColorGreen 68 speed = -speed 69 } 70 ui.Pie.Data = fract(speed) 71 tui.Render(ui.Head, ui.Gauge, 72 ui.Pie) 73 } 74 75 func fract( 76 val float64) []float64 { 77 num := (1 - val) * 100 78 denom := val * 100 79 return []float64{num, denom} 80 }
The NewUI()
constructor from line 13 defines the widgets, including their dimensions, geometric positions, and colored bits, and returns an initialized structure of the UI
type (defined in line 7). The main program uses this later to call method-style functions such as Run()
(from line 32) and to give them the context of the previously initialized widgets – object orientation Go-style.
Listening on the Channels
The Run()
function from line 32 onwards starts the termui interface in a parallel Goroutine from line 39 onwards. Like every UI, it also continuously delivers events such as keystrokes or mouse clicks that need to be intercepted and processed in order to give the illusion of a seamless user interaction.
The infinite loop from line 41 waits with its select
statement for the user to press either Q or Ctrl+C. In this case, it sends the value true
into a newly created channel, done
, to the listening main program, causing it to stop all operations. To do this, the main program simultaneously monitors – in the select statement from line 32 of Listing 1 – whether the UI has reported the end of the program or, alternatively, the ticking seconds timer (Listing 1, line 35) has expired. If the timer has expired, the program moves on to the next round, fetches new values for the disk fill level, and displays them.
In general terms, Listing 2 abstracts the features of the termui library and encapsulates them from the main flow. When it's time to pack up shop, the main program simply calls the Close()
function (Listing 2 from line 55) to wrap up the terminal UI, which in turn triggers a Close()
call in the termui library.
« Previous 1 2 3 Next »
Buy this article as PDF
(incl. VAT)
Buy Linux Magazine
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters
Support Our Work
Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.
News
-
Gnome 48 Debuts New Audio Player
To date, the audio player found within the Gnome desktop has been meh at best, but with the upcoming release that all changes.
-
Plasma 6.3 Ready for Public Beta Testing
Plasma 6.3 will ship with KDE Gear 24.12.1 and KDE Frameworks 6.10, along with some new and exciting features.
-
Budgie 10.10 Scheduled for Q1 2025 with a Surprising Desktop Update
If Budgie is your desktop environment of choice, 2025 is going to be a great year for you.
-
Firefox 134 Offers Improvements for Linux Version
Fans of Linux and Firefox rejoice, as there's a new version available that includes some handy updates.
-
Serpent OS Arrives with a New Alpha Release
After months of silence, Ikey Doherty has released a new alpha for his Serpent OS.
-
HashiCorp Cofounder Unveils Ghostty, a Linux Terminal App
Ghostty is a new Linux terminal app that's fast, feature-rich, and offers a platform-native GUI while remaining cross-platform.
-
Fedora Asahi Remix 41 Available for Apple Silicon
If you have an Apple Silicon Mac and you're hoping to install Fedora, you're in luck because the latest release supports the M1 and M2 chips.
-
Systemd Fixes Bug While Facing New Challenger in GNU Shepherd
The systemd developers have fixed a really nasty bug amid the release of the new GNU Shepherd init system.
-
AlmaLinux 10.0 Beta Released
The AlmaLinux OS Foundation has announced the availability of AlmaLinux 10.0 Beta ("Purple Lion") for all supported devices with significant changes.
-
Gnome 47.2 Now Available
Gnome 47.2 is now available for general use but don't expect much in the way of newness, as this is all about improvements and bug fixes.