Track your weight with a CGI script and Go
Programming Snapshot – Go CGI Scripting
![© Lead Image © mathias the dread, photocase.com © Lead Image © mathias the dread, photocase.com](/var/linux_magazin/storage/images/issues/2024/278/scales-well/po-21670-photocase-mathias_the_dread_photocase_com-babywaage_resized.png/832395-1-eng-US/PO-21670-Photocase-mathias_the_dread_photocase_com-Babywaage_resized.png_medium.png)
© Lead Image © mathias the dread, photocase.com
Mike Schilli steps on the scale every week and records his weight fluctuations as a time series. To help monitor his progress, he writes a CGI script in Go that stores the data and draws visually appealing charts.
Capturing datapoints, adding them to a time series, and showing values over time graphically is usually the domain of tools like Prometheus. The tool retrieves the status of monitored systems at regular intervals and stores the data as a time series. If outliers occur, the messenger of the gods alerts its human to the fact. Viewing tools such as Grafana display the collected time series in dashboards spread over the last week or year as graphs, if so desired, so that even senior managers can see at a glance what's going on in the trenches.
However, my el cheapo web host won't let me install arbitrary software packages for this purpose on my rented virtual server. Plus, maintaining such complicated products with their continuous updates would be too time consuming for me, anyway. However, there is a '90s-style CGI interface on the web server. How hard could it be to write a CGI program in Go that receives measured values via HTTPS like an API, formats the time series generated from them into an attractive chart, and sends the results back to the browser in PNG format? Let's find out.
Figure 1 shows the graph of a time series that outputs my weight in kilograms over the past few years (possibly embellished for this article) as a chart in the browser after pointing it to the URL on the server. The same CGI script also accepts new incoming data. For example, if my scale shows 82.5 kilograms one day, calling
curl '.../cgi/minipro?add=82.5&apikey=<Key>'
will add the value with the current date to the time series, now permanently stored on the server. If I replace add=...
in the URL with chart=1
, the script will return the chart with all the values fed in so far.
Jurassic Tech
The CGI protocol is bona fide dinosaur technology from the heady '90s of the last century. At the time, the first dynamic websites came into fashion after users, having acquired a taste for more than static HTML, began to crave customized content.
It's a time I remember very well: I was working at AOL back then, tasked with freshening up AOL's website in San Mateo, California, as a freshly imported engineer from Germany. At the time, we did everything live on a single server without any form of safety net. A CGI script at the top of the portal page displayed the current date. However, this caused the (only!) server to collapse under the load of what was quite a considerable number of users, because of the need to launch a Perl interpreter for every call. I brought the machine back to life with a compiled C program that did the same job but started faster. Later on, persistent environments such as mod_perl
came along and made things a thousand times faster.
All Inclusive
Today, the CGI protocol is frowned upon because a script might tear open a security hole in the server environment, and the startup costs of an external program that launches for every incoming request are immense as user numbers increase. But of course, for my weight barometer, where the server will field maybe two requests per day, this design is justifiable. In a scripting language such as Python, such a mini project would be implemented in next to no time.
But I like the challenge of bundling adding values and displaying the chart into one single static Go binary that has no dependencies. Refreshing various Python libraries every so often by hand with pip3 seems like too much trouble. Once compiled – even if cross-compiled on another platform – a statically linked Go program will run until the end of time. Even if the web host were to upgrade the Linux distro to a new version with libraries suddenly disappearing as a result, the all-inclusive Go binary will still soldier on.
Getting Started with CGI
If a web server determines that it needs to respond to a request with an external CGI script based on its configuration, it sets the REQUEST_URI
environment variable to the URL of the request, among other things, and calls the associated program or script. The script then retrieves the information required to process the request from its environment variables. In case of a GET
request, for example, you only need the URL in REQUEST_URI
; its path also includes all the CGI form parameters if present. As a response to the inquiring browser, the script then simply uses print()
to write the answer to stdout
. The web server picks up the text stream and sends it back to the requesting client.
Listing 1 shows a minimal CGI program in Go. It uses the standard net/http/cgi library, whose Serve()
function in line 19 parses the incoming request and then sends the response back to the server.
Listing 1
cgi-test.go
To do this, it expects a handler
function as a parameter. The handler
function, defined in line 10, in turn, expects a writer for the output and a reader for the incoming request data as parameters. Calling the Query()
library function on the incoming request URL inside the handler returns a map that assigns the names of the incoming CGI parameters to their values. The for
loop starting in line 14 iterates over all the entries in the hashmap and outputs all incoming form parameters and their values to the w
writer.
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.
![Learn More](https://www.linux-magazine.com/var/linux_magazin/storage/images/media/linux-magazine-eng-us/images/misc/learn-more/834592-1-eng-US/Learn-More_medium.png)
News
-
Wine 10 Includes Plenty to Excite Users
With its latest release, Wine has the usual crop of bug fixes and improvements, along with some exciting new features.
-
Linux Kernel 6.13 Offers Improvements for AMD/Apple Users
The latest Linux kernel is now available, and it includes plenty of improvements, especially for those who use AMD or Apple-based systems.
-
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.