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

Article from Issue 278/2024
Author(s):

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>'
Figure 1: The author's weight fluctuations over the years.

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

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Google Chart

    The Google Chart API lets you draw custom graphs, charts, maps, and barcodes through a simple web interface.

  • Perl: Google Chart Instructions

    A CPAN module passes drawing instructions in object-oriented Perl to Google Chart, which draws visually attractive diagrams.

  • Perl: Jawbone UP Data

    The Jawbone UP electronic bracelet measures the wearer's daily activity and nocturnal sleep patterns. If you are bored by the official smartphone app, you can create your own Perl scripts and access your data via the unofficial web API.

  • Perl: Pinpointing Spammers

    To identify the geographic regions from which link spam originated, a database locates IP addresses and the Google Charts service puts them onto a world map.

  • Wanderlust

    For running statistics on his recorded hiking trails, Mike Schilli turns to Go to extract the GPS data while relying on plotters and APIs for a bit of geoanalysis.

comments powered by Disqus
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

News