Go · projectA login greeting with text/template
This Go program prints the same framed greeting as the Bash one of this series, and shows a different way to build it: a text/template holds the content, a struct holds the facts, and a short loop draws the frame around them. To change the layout, you change the template and leave the code alone.
╔═ Hello ══════════════════════════════════════════════════════════════════╗ ║ ║ ║ ░▒▓█ Good morning, root █▓▒░ 2026-11-27 09:30 ║ ║ ║ ║ Model TBS-h574TX ║ ║ Up for 1 d 13 h 10 min ║ ║ CPU 10 cores, 12 logical processors ║ ║ Load 1.17 0.90 0.88 (1, 5 and 15 minutes) ║ ║ ║ ║ Free space on the data volumes ║ ║ CACHEDEV1_DATA ████░░░░░░░░░░░░░░░░ 1044.8 GiB free of 1327.1 GiB ║ ║ CACHEDEV2_DATA ██░░░░░░░░░░░░░░░░░░ 1054.6 GiB free of 1232.3 GiB ║ ║ ║ ║ Tip cat /proc/mdstat shows the state of every RAID group. ║ ║ ║ ╚══════════════════════════════════════════════════════════════════════════╝
SEED=7.Download it on the NAS
curl -fsSLO https://kb.nasutils.net/projects/go/hello.gohello.go Download hello.go
// hello.go: a greeting for the SSH login. A text/template lays out the facts of the NAS: a greeting for the time of
// day, the model, uptime, CPU, load, the free space of the data volumes and a tip of the day; the code frames it.
// Build and run it: go build hello.go && ./hello (NOW, SEED, PROC and DF may replace the clock and the files)
package main
import (
"bytes"
"cmp"
"fmt"
"os"
"os/exec"
"os/user"
"strconv"
"strings"
"text/template"
"time"
)
const width = 76 // the frame's width
// The template holds only the content; {{col 57}} jumps to column 57, the functions add the colours.
const banner = `{{amber "░▒▓█"}} {{bold (printf "%s, %s" .Greeting .User)}} {{amber "█▓▒░"}}{{col 57}}{{dim .Date}}
{{printf "%-12s" "Model"}}{{bold .Model}}
{{printf "%-12s" "Up for"}}{{.Uptime}}
{{printf "%-12s" "CPU"}}{{.Cores}} cores, {{.Logical}} logical processors
{{printf "%-12s" "Load"}}{{index .Load 0}} {{index .Load 1}} {{index .Load 2}} {{dim "(1, 5 and 15 minutes)"}}
{{bold "Free space on the data volumes"}}
{{range .Volumes}}{{printf "%-16s" .Name}}{{bar .Pct}} {{green (gib .Free)}} free of {{gib .Size}}
{{end}}
{{amber "Tip"}} {{.Tip}}`
type volume struct {
Name string
Size, Free int64 // KiB
Pct int
}
type facts struct {
Greeting, User, Date, Model, Uptime, Tip string
Cores, Logical int
Load []string
Volumes []volume
}
var tips = []string{
"getsysinfo cputmp prints the temperature of the CPU.",
"cat /proc/mdstat shows the state of every RAID group.",
"getcfg System Version prints the version of QTS.",
"ls /share lists the shared folders of the NAS.",
"df -h shows the size and the free space of every volume.",
"uptime prints how long the NAS has run and its load.",
}
func colour(code string) func(string) string {
return func(s string) string { return "\033[" + code + "m" + s + "\033[0m" }
}
var funcs = template.FuncMap{
"amber": colour("38;5;214"), "green": colour("32"), "bold": colour("1"), "dim": colour("2"),
"col": func(n int) string { return fmt.Sprintf("\033[%dG", n) },
"gib": func(kib int64) string { return fmt.Sprintf("%.1f GiB", float64(kib)/1048576) },
"bar": func(pct int) string { // 20 cells: green up to 69 %, amber up to 89 %, red from 90 %
c := "32"
if pct >= 70 {
c = "38;5;214"
}
if pct >= 90 {
c = "31"
}
return colour(c)(strings.Repeat("█", pct/5)) + colour("2")(strings.Repeat("░", 20-pct/5))
},
}
func read(name string) string {
b, _ := os.ReadFile(cmp.Or(os.Getenv("PROC"), "/proc") + "/" + name)
return string(b)
}
func gather() facts {
now, err := time.ParseInLocation(time.DateTime, os.Getenv("NOW"), time.Local)
if err != nil {
now = time.Now()
}
f := facts{Date: now.Format("2006-01-02 15:04"), Load: strings.Fields(read("loadavg"))[:3]}
switch h := now.Hour(); {
case h >= 5 && h < 12:
f.Greeting = "Good morning"
case h >= 12 && h < 18:
f.Greeting = "Good afternoon"
case h >= 18 && h < 22:
f.Greeting = "Good evening"
default:
f.Greeting = "Working late"
}
seed, err := strconv.Atoi(os.Getenv("SEED"))
if err != nil {
seed = now.YearDay() // without SEED, a new tip each day
}
f.Tip = tips[seed%len(tips)]
f.User = os.Getenv("USER")
if u, err := user.Current(); f.User == "" && err == nil {
f.User = u.Username
}
model, _ := exec.Command("getsysinfo", "model").Output()
f.Model = strings.TrimSpace(string(model))
var s int
fmt.Sscanf(read("uptime"), "%d", &s)
f.Uptime = fmt.Sprintf("%d d %d h %d min", s/86400, s%86400/3600, s%3600/60)
cores, physical := map[string]bool{}, ""
for _, l := range strings.Split(read("cpuinfo"), "\n") {
k, v, _ := strings.Cut(l, ":")
switch strings.TrimSpace(k) {
case "processor":
f.Logical++
case "physical id":
physical = strings.TrimSpace(v)
case "core id":
cores[physical+"-"+strings.TrimSpace(v)] = true
}
}
f.Cores = len(cores)
out, err := os.ReadFile(os.Getenv("DF"))
if err != nil {
out, _ = exec.Command("df", "-k").Output()
}
for _, l := range strings.Split(string(out), "\n") {
w := strings.Fields(l)
if len(w) < 6 || !strings.HasPrefix(w[5], "/share/") || strings.Count(w[5], "/") != 2 {
continue // only the data volumes, one level under /share
}
v := volume{Name: strings.TrimPrefix(w[5], "/share/")}
v.Size, _ = strconv.ParseInt(w[1], 10, 64)
v.Free, _ = strconv.ParseInt(w[3], 10, 64)
v.Pct, _ = strconv.Atoi(strings.TrimSuffix(w[4], "%"))
f.Volumes = append(f.Volumes, v)
}
return f
}
func main() {
var body bytes.Buffer
t := template.Must(template.New("banner").Funcs(funcs).Parse(banner))
if err := t.Execute(&body, gather()); err != nil {
fmt.Fprintln(os.Stderr, "hello:", err)
os.Exit(1)
}
a, n := "\033[38;5;214m", "\033[0m" // amber frame, then back to normal
fmt.Printf("%s╔═ Hello %s╗%s\n", a, strings.Repeat("═", width-10), n)
fmt.Printf("%s║%s\033[%dG%s║%s\n", a, n, width, a, n)
for _, line := range strings.Split(body.String(), "\n") {
fmt.Printf("%s║%s %s\033[%dG%s║%s\n", a, n, line, width, a, n)
}
fmt.Printf("%s║%s\033[%dG%s║%s\n%s╚%s╝%s\n", a, n, width, a, n, a, strings.Repeat("═", width-2), n)
}
What you learn
template.FuncMapgives the template your own functions:amber,bold,bar,gibandcol.{{range .Volumes}}repeats a line for each entry of a slice in the struct.{{printf "%-12s" "Model"}}pads a label inside the template, so the values line up.time.ParseInLocation(time.DateTime, ...)reads a time like "2026-11-27 09:30:00", here fromNOW.strings.Count(w[5], "/") != 2keeps/share/CACHEDEV1_DATAand skips folders mounted inside a volume.
How it works
gather collects the facts into the struct facts. The greeting depends on the hour: morning from 5, afternoon from 12, evening from 18, and "Working late" from 22. The tip is one of six, picked by SEED, or else by the day of the year, so each day shows another tip. Cores are the distinct pairs of physical id and core id in /proc/cpuinfo, logical processors the processor lines.
main parses the template once, with the functions, and runs it with the facts into a buffer. Each line of the buffer then gets the left edge, three spaces, the text and \033[76G with the right edge. The escape moves the cursor to column 76, so the edge lines up whatever colours the line holds.
The program only prints and ends, so it fits the end of a login. To show it at every SSH login, see the Bash greeting of this series: the steps are the same with ./hello in place of bash hello.sh.
Notes to the lines
- 21–32The template: text, fields such as
.Model, and calls of the functions with their arguments. - 34–45The data of the template; only exported fields (capital letters) are visible to it.
- 56–58
colourreturns a function that wraps a text in one colour and the reset after it. - 60–74The functions of the template;
bardraws 20 cells, one for each 5 %. - 82–85Without
NOWor with a time it cannot read, the program takes the clock. - 87–96A
switchwithout a value takes the first case that is true. - 97–101
strconv.Atoifails on an emptySEED, and the day of the year takes its place. - 102–105
USERfirst;user.Currentreads/etc/passwdwhenUSERis empty. - 128–139One
volumeper data volume fromdf -k: size, free space and the percentage in use. - 144–148
template.Muststops the program at once if the template has a mistake. - 152–154The frame around each line of the result.
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 hello.go
./helloThe program prints the greeting and ends. The finished file runs on the NAS without Go.
Try it yourself
Add a field Temp to facts, fill it from getsysinfo cputmp, and add a line for it to the template. Move the tip above the volumes by moving one line of the template.
More projects in Go
- A framed menu in Go with raw keysA Go program puts the terminal into raw mode, draws a framed menu with ANSI escapes and opens boxes with the NAS's memory, volumes, uptime and load. You learn raw keys without extra packages and how to give the terminal back its settings.
- A login greeting with text/templateA Go program fills a text/template with the facts of the NAS (greeting, model, uptime, CPU, load, free space, tip of the day) and frames the result. You learn templates with your own functions and a struct as their data.
- A NAS summary on screen and as JSONA Go program collects the CPU, temperature, memory, data volumes and network ports of the NAS into structs and prints them as a screen with bars, or with -json as JSON. You learn structs with json tags, the flag package and one source of facts for two outputs.
- Packet catcher: a game with goroutinesIn this Go game packets fall down the screen and you catch them with a switch moved by the arrow keys; three missed packets end the game. You learn goroutines, channels and select, with one goroutine for the clock and one for the keys.
- A status page of the NAS with net/httpA Go program serves the model, uptime, CPU, load, memory and data volumes of the NAS as a web page that reloads every 5 seconds, so you can watch it from any browser on your network. You learn net/http, html/template and a clean stop on Ctrl+C.
- Find duplicate files with a pool of workersA Go program finds duplicate files in a folder of the NAS. It compares sizes first, hashes only the files that share a size with SHA-256 in a pool of goroutines, and shows each group with the space its extra copies take. You learn worker pools, channels and sync.WaitGroup.