NASutils Knowledge BaseUnofficialPolski

Go · projectA framed menu in Go with raw keys

This Go program draws a menu in the SSH window and reacts to each key at once: the arrow keys move the bar, Enter opens a box with memory, volumes, or uptime and load. It uses only Go's standard library and the stty command, and it puts the terminal back as it found it.

Programming on the NAS › Go in 30 lessons

 NAS menu                                                             TBS-h574TX


   ╔═ Menu ═══════════════╗
   ║                      ║
   ║  ▶ Memory            ║
   ║    Volumes           ║
   ║    Uptime and load   ║
   ║                      ║
   ╚══════════════════════╝













 ↑↓ move   Enter open   q quit
The menu with the bar on Memory and the NAS model in the title bar.
 NAS menu                                                             TBS-h574TX


   ╔═ Menu ═══════════════╗
   ║                      ║
   ║  ▶ Memory            ║    ╔═ Memory ═══════════════════════════════════╗
   ║    Volumes           ║    ║                                            ║
   ║    Uptime and load   ║    ║  Total      15.4 GiB                       ║
   ║                      ║    ║  In use     5.6 GiB                        ║
   ╚══════════════════════╝    ║  Available  9.8 GiB                        ║
                               ║  ██████████░░░░░░░░░░░░░░░░░░░░ 36 %       ║
                               ╚════════════════════════════════════════════╝











 Any key closes the box
The Memory box: 15.4 GiB in all, 5.6 GiB in use, 9.8 GiB available, a bar at 36 %.
 NAS menu                                                             TBS-h574TX


   ╔═ Menu ═══════════════╗
   ║                      ║
   ║    Memory            ║    ╔═ Uptime and load ══════════════════════════╗
   ║    Volumes           ║    ║                                            ║
   ║  ▶ Uptime and load   ║    ║  Up for     1 d 13 h 10 min                ║
   ║                      ║    ║  Load       1.17 / 0.90 / 0.88             ║
   ╚══════════════════════╝    ║             1, 5 and 15 minutes            ║
                               ║  Cores      10                             ║
                               ║  Processors 12 logical                     ║
                               ║                                            ║
                               ╚════════════════════════════════════════════╝









 Any key closes the box
The Uptime and load box: 1 d 13 h 10 min, the load averages, 10 cores and 12 logical processors.

Download it on the NAS

curl -fsSLO https://kb.nasutils.net/projects/go/menu.go

menu.go Download menu.go

// menu.go: a framed menu in Go with raw keys. The arrow keys move the bar, Enter opens a box with the NAS's memory,
// volumes or uptime and load, any key closes it, q quits. Run: go build menu.go && ./menu (PROC, DF: sample files)
package main

import (
	"cmp"
	"fmt"
	"os"
	"os/exec"
	"strconv"
	"strings"
)

const amber, green, red, dim, bold, reset = "\033[38;5;214m", "\033[32m", "\033[31m", "\033[2m", "\033[1m", "\033[0m"
const barColour = "\033[1;30;48;5;214m"       // black letters on amber
var proc = cmp.Or(os.Getenv("PROC"), "/proc") // the root of /proc; the test points it at a sample

func at(line, col int, format string, a ...any) {
	fmt.Printf("\033[%d;%dH"+format, append([]any{line, col}, a...)...)
}

// box draws a double frame in amber with its title in the top edge.
func box(line, col, height, width int, title string) {
	at(line, col, "%s╔%s╗", amber, strings.Repeat("═", width-2))
	for i := 1; i < height-1; i++ {
		at(line+i, col, "║%s║", strings.Repeat(" ", width-2))
	}
	at(line+height-1, col, "╚%s╝", strings.Repeat("═", width-2))
	at(line, col+2, "%s %s %s", bold+amber, title, reset)
}

// bar fills pct percent of width: green up to 69 %, amber up to 89 %, red from 90 %.
func bar(pct, width int) string {
	colour := green
	if pct >= 90 {
		colour = red
	} else if pct >= 70 {
		colour = amber
	}
	full := pct * width / 100
	return colour + strings.Repeat("█", full) + dim + strings.Repeat("░", width-full) + reset
}

func gib(kib int64) string        { return fmt.Sprintf("%.1f GiB", float64(kib)/1048576) }
func readFile(name string) string { b, _ := os.ReadFile(proc + "/" + name); return string(b) }

func showMemory() {
	m := map[string]int64{}
	for _, l := range strings.Split(readFile("meminfo"), "\n") {
		if f := strings.Fields(l); len(f) >= 2 {
			m[strings.TrimSuffix(f[0], ":")], _ = strconv.ParseInt(f[1], 10, 64)
		}
	}
	used := m["MemTotal"] - m["MemAvailable"]
	pct := int(used * 100 / m["MemTotal"])
	box(6, 32, 7, 46, "Memory")
	at(8, 35, "Total      %s", gib(m["MemTotal"]))
	at(9, 35, "In use     %s", gib(used))
	at(10, 35, "Available  %s%s%s", green, gib(m["MemAvailable"]), reset)
	at(11, 35, "%s %d %%", bar(pct, 30), pct)
}

func showVolumes() {
	out, err := os.ReadFile(os.Getenv("DF")) // a sample of df -k, or else the real one
	if err != nil {
		out, _ = exec.Command("df", "-k").Output()
	}
	box(6, 32, 8, 46, "Volumes")
	line := 8
	for _, l := range strings.Split(string(out), "\n") {
		f := strings.Fields(l)
		if len(f) < 6 || !strings.HasPrefix(f[5], "/share/") || strings.Count(f[5], "/") != 2 {
			continue // only the data volumes, one level under /share
		}
		size, _ := strconv.ParseInt(f[1], 10, 64)
		used, _ := strconv.ParseInt(f[2], 10, 64)
		pct, _ := strconv.Atoi(strings.TrimSuffix(f[4], "%"))
		at(line, 35, "%s%-15s%s %s of %s", bold, strings.TrimPrefix(f[5], "/share/"), reset, gib(used), gib(size))
		at(line+1, 35, "%s %d%%", bar(pct, 30), pct)
		line += 2
	}
}

func showUptime() {
	var s int
	fmt.Sscanf(readFile("uptime"), "%d", &s) // the whole seconds before the dot
	load := strings.Fields(readFile("loadavg"))
	logical, physical, cores := 0, "", map[string]bool{}
	for _, l := range strings.Split(readFile("cpuinfo"), "\n") {
		k, v, _ := strings.Cut(l, ":")
		switch strings.TrimSpace(k) {
		case "processor":
			logical++
		case "physical id":
			physical = strings.TrimSpace(v)
		case "core id":
			cores[physical+"-"+strings.TrimSpace(v)] = true // a core is a distinct pair of physical id and core id
		}
	}
	box(6, 32, 9, 46, "Uptime and load")
	at(8, 35, "Up for     %s%d d %d h %d min%s", bold, s/86400, s%86400/3600, s%3600/60, reset)
	at(9, 35, "Load       %s / %s / %s", load[0], load[1], load[2])
	at(10, 35, "%s           1, 5 and 15 minutes%s", dim, reset)
	at(11, 35, "Cores      %d", len(cores))
	at(12, 35, "Processors %d logical", logical)
}

var items = []string{"Memory", "Volumes", "Uptime and load"}

func draw(sel int) {
	model, _ := exec.Command("getsysinfo", "model").Output() // QNAP's own command; on a PC the title stays short
	at(1, 1, "\033[2J%s %-58s%21s%s", barColour, "NAS menu", strings.TrimSpace(string(model)), reset)
	box(4, 4, len(items)+4, 24, "Menu")
	for i, it := range items {
		if i == sel {
			at(6+i, 6, "%s ▶ %-17s%s", barColour, it, reset)
		} else {
			at(6+i, 6, "   %-17s", it)
		}
	}
	at(24, 1, "%s ↑↓ move   Enter open   q quit%s", dim, reset)
}

// key reads one key press; an arrow key arrives as three bytes in one read.
func key() string {
	b := make([]byte, 8)
	if n, err := os.Stdin.Read(b); err == nil {
		return string(b[:n])
	}
	return "q"
}

func main() {
	stty := func(args ...string) string { // stty works on the terminal it gets as its input
		c := exec.Command("stty", args...)
		c.Stdin = os.Stdin
		out, _ := c.Output()
		return strings.TrimSpace(string(out))
	}
	saved := stty("-g") // the terminal's settings, to put back at the end
	stty("raw", "-echo")
	fmt.Print("\033[?1049h\033[?25l") // a screen of its own, no cursor
	defer func() { fmt.Print("\033[0m\033[?25h\033[?1049l"); stty(saved) }()

	for sel := 0; ; {
		draw(sel)
		switch key() {
		case "\033[A", "\033OA":
			sel = (sel + len(items) - 1) % len(items)
		case "\033[B", "\033OB":
			sel = (sel + 1) % len(items)
		case "q", "Q", "\003": // \003 is Ctrl+C, which raw mode delivers as a byte
			return
		case "\r":
			[]func(){showMemory, showVolumes, showUptime}[sel]()
			at(24, 1, "\033[2K%s Any key closes the box%s", dim, reset)
			key()
		}
	}
}

What you learn

  • stty raw -echo makes the terminal hand over each key at once and stop showing it; stty -g saves the settings before, so the program can restore them.
  • exec.Command with Stdin = os.Stdin lets stty work on the program's own terminal.
  • In raw mode, Ctrl+C is the byte 3 and no signal, so the program treats it like q.
  • "\033[%d;%dH" moves the cursor, and strings.Repeat("═", n) makes the edges of a box.
  • A map of /proc/meminfo and a set of (physical id, core id) pairs come from a few lines of strings.

How it works

main saves the terminal's settings with stty -g, switches to raw mode and to a screen of its own, and sets up a defer that undoes all of it when main returns. Every way out of the program goes through return, so the defer always runs.

The loop draws the menu and reads one key with os.Stdin.Read. An arrow key comes as three bytes in one read, such as ESC [ A for up, and the switch compares the whole string. Enter in raw mode is \r. It calls one of the three functions from a slice, picked by the number of the highlighted entry, and the next key closes the box.

The boxes read the same files as the Bash menu of this series. Memory in use is MemTotal minus MemAvailable. The volumes are the lines of df -k mounted one level under /share. Logical processors are the processor lines of /proc/cpuinfo, and cores are the distinct pairs of physical id and core id: 10 cores and 12 logical processors on this NAS.

Notes to the lines

  • 14–16The colours as constants; cmp.Or takes PROC or, when it is empty, /proc.
  • 18–20at puts the cursor at a line and a column, then prints like Printf.
  • 33–42bar fills a share of its width with █ and the rest with dim ░, in green, amber or red.
  • 44%.1f rounds the size in GiB to one decimal.
  • 48–53Each line of /proc/meminfo gives a name and a number for the map.
  • 64–67With DF set, the program reads the sample file; otherwise it runs df -k.
  • 72Only mount points like /share/CACHEDEV1_DATA, with exactly two slashes, count as data volumes.
  • 86%d reads the whole seconds of /proc/uptime and stops at the dot.
  • 88–99The loop counts the logical processors and puts each pair of physical id and core id in a map; the size of the map is the number of cores.
  • 111getsysinfo model is QNAP's own command; where it is missing, the title shows no model.
  • 124–131One read gets one key or one whole escape sequence.
  • 134–143The terminal goes raw, and the defer restores the saved settings, the cursor and the normal screen.
  • 152Ctrl+C arrives as \003.
  • 155A slice of functions, indexed by the highlighted entry.

Run it

Build it in the terminal of Bucket & Code's editor, with its Go runtime:

eval "$(bvs use go-1.27-x86_64)"
go build menu.go
./menu

Up and Down move the bar, Enter opens the box, any key closes it, q or Ctrl+C quits. The finished file runs on the NAS without Go. It calls stty, which TurboShell has; QTS 6.1 has no stty of its own.

Try it yourself

Add a fourth entry that shows the CPU temperature from getsysinfo cputmp, with its function in the slice. Make Home and End jump to the first and the last entry: they arrive as \033[H and \033[F.

More projects in Go