NASutils Knowledge BaseUnofficialPolski

Go · projectA status page of the NAS with net/http

This Go program turns the NAS's state into a small web page. Open it from any browser on your network and it reloads itself every 5 seconds with fresh numbers: model, uptime, load, cores and logical processors, memory and each data volume with a bar. The program needs no web server of QTS; it is its own.

Programming on the NAS › Go in 30 lessons

Listening on http://127.0.0.1:18099/
GET / 200 OK, text/html; charset=utf-8

<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta http-equiv="refresh" content="5"><title>TBS-h574TX status</title>
<style>body{font:15px system-ui;background:#111;color:#ddd;margin:2em}
h1{color:#ffaf00} .bar{background:#333;width:20em;height:.8em}
.bar i{display:block;height:100%;background:#3c3}</style></head>
<body><h1>TBS-h574TX</h1>
<p>Up for 1 d 13 h 10 min, load 1.17 / 0.90 / 0.88.</p>
<p>10 cores, 12 logical processors.</p>
<p>Memory: 36 % in use</p><div class="bar"><i style="width:36%"></i></div>
<p>CACHEDEV1_DATA: 21 % in use</p><div class="bar"><i style="width:21%"></i...
<p>CACHEDEV2_DATA: 14 % in use</p><div class="bar"><i style="width:14%"></i...
</body></html>
The test run with -once: the address, the answer 200 OK as HTML, and the first lines of the page with the model, uptime, load, cores, memory and two data volumes.

Download it on the NAS

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

web.go Download web.go

// web.go: a small status page of the NAS. net/http serves the model, uptime, CPU, load, memory and data volumes as
// an HTML page that reloads itself every 5 seconds. It runs until Ctrl+C; -once fetches the page once and ends.
// Build and run it: go build web.go && ./web [-addr :8099] [-once]   (PROC and DF may point it at sample files)
package main

import (
	"bufio"
	"cmp"
	"context"
	"flag"
	"fmt"
	"html/template"
	"net"
	"net/http"
	"os"
	"os/exec"
	"os/signal"
	"strconv"
	"strings"
)

var page = template.Must(template.New("page").Parse(`<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta http-equiv="refresh" content="5"><title>{{.Model}} status</title>
<style>body{font:15px system-ui;background:#111;color:#ddd;margin:2em}
h1{color:#ffaf00} .bar{background:#333;width:20em;height:.8em}
.bar i{display:block;height:100%;background:#3c3}</style></head>
<body><h1>{{.Model}}</h1>
<p>Up for {{.Uptime}}, load {{.Load}}.</p>
<p>{{.Cores}} cores, {{.Logical}} logical processors.</p>
<p>Memory: {{.MemUsed}} % in use</p><div class="bar"><i style="width:{{.MemUsed}}%"></i></div>
{{range .Volumes}}<p>{{.Name}}: {{.Used}} % in use</p><div class="bar"><i style="width:{{.Used}}%"></i></div>
{{end}}</body></html>
`))

type volume struct {
	Name string
	Used int
}

type status struct {
	Model, Uptime, Load string
	Cores, Logical      int
	MemUsed             int
	Volumes             []volume
}

func read(name string) string {
	b, _ := os.ReadFile(cmp.Or(os.Getenv("PROC"), "/proc") + "/" + name)
	return string(b)
}

func collect() status { // read the NAS anew for every request, so each reload shows fresh numbers
	var st status
	model, _ := exec.Command("getsysinfo", "model").Output()
	st.Model = cmp.Or(strings.TrimSpace(string(model)), "NAS")
	var s int
	fmt.Sscanf(read("uptime"), "%d", &s)
	st.Uptime = fmt.Sprintf("%d d %d h %d min", s/86400, s%86400/3600, s%3600/60)
	st.Load = strings.Join(strings.Fields(read("loadavg"))[:3], " / ")
	cores, physical := map[string]bool{}, ""
	for _, l := range strings.Split(read("cpuinfo"), "\n") {
		k, v, _ := strings.Cut(l, ":")
		switch strings.TrimSpace(k) {
		case "processor":
			st.Logical++
		case "physical id":
			physical = strings.TrimSpace(v)
		case "core id":
			cores[physical+"-"+strings.TrimSpace(v)] = true
		}
	}
	st.Cores = len(cores)
	mem := map[string]int{}
	for _, l := range strings.Split(read("meminfo"), "\n") {
		if f := strings.Fields(l); len(f) > 1 {
			mem[f[0]], _ = strconv.Atoi(f[1])
		}
	}
	if mem["MemTotal:"] > 0 {
		st.MemUsed = (mem["MemTotal:"] - mem["MemAvailable:"]) * 100 / mem["MemTotal:"]
	}
	out, err := os.ReadFile(os.Getenv("DF"))
	if err != nil {
		out, _ = exec.Command("df", "-k").Output()
	}
	for _, l := range strings.Split(string(out), "\n") {
		if f := strings.Fields(l); len(f) > 5 && strings.HasPrefix(f[5], "/share/") && strings.Count(f[5], "/") == 2 {
			used, _ := strconv.Atoi(strings.TrimSuffix(f[4], "%"))
			st.Volumes = append(st.Volumes, volume{strings.TrimPrefix(f[5], "/share/"), used})
		}
	}
	return st
}

func main() {
	addr := flag.String("addr", ":8099", "the address and port to listen on")
	once := flag.Bool("once", false, "fetch the page once, print its first lines and end")
	flag.Parse()
	const amber, green, dim, reset = "\033[38;5;214m", "\033[32m", "\033[2m", "\033[0m"

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if err := page.Execute(w, collect()); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})
	ln, err := net.Listen("tcp", *addr) // listen first, so the address is taken before we print it
	if err != nil {
		fmt.Fprintln(os.Stderr, "web:", err)
		os.Exit(1)
	}
	srv := &http.Server{}
	go srv.Serve(ln)
	url := "http://" + strings.Replace(ln.Addr().String(), "[::]", "localhost", 1) + "/"
	fmt.Printf("%sListening on %s%s\n", amber, url, reset)

	if *once { // the test: one request with net/http's client, then the end
		resp, err := http.Get(url)
		if err != nil {
			fmt.Fprintln(os.Stderr, "web:", err)
			os.Exit(1)
		}
		defer resp.Body.Close()
		fmt.Printf("GET / %s%s%s, %s\n\n", green, resp.Status, reset, resp.Header.Get("Content-Type"))
		sc := bufio.NewScanner(resp.Body)
		for n := 0; n < 14 && sc.Scan(); n++ {
			line := sc.Text()
			if r := []rune(line); len(r) > 78 { // cut long lines by characters, not by bytes
				line = string(r[:75]) + "..."
			}
			fmt.Printf("%s%s%s\n", dim, line, reset)
		}
		return
	}
	fmt.Println("Open the address in a browser. Ctrl+C stops the server.")
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) // Ctrl+C ends the wait
	defer stop()
	<-ctx.Done()
	srv.Shutdown(context.Background())
	fmt.Println("\nStopped.")
}

What you learn

  • http.HandleFunc("/", ...) answers every request with a function, here one that fills a template.
  • html/template escapes every value it inserts, so a strange share name cannot break the page.
  • net.Listen first and srv.Serve(ln) after it: the port is taken before the program prints its address.
  • <meta http-equiv="refresh" content="5"> makes the browser load the page again every 5 seconds.
  • signal.NotifyContext turns Ctrl+C into a context that ends, and srv.Shutdown stops the server cleanly.

How it works

The page is one template in the program. Its fields come from collect, which reads /proc, df -k and getsysinfo anew for each request, so each reload shows the current state. The bars are two nested blocks: the outer one is grey, and the inner one gets the percentage as its width.

main reads two options. -addr is the address and port to listen on, :8099 by default, which means every network address of the NAS. -once is for the test and for a quick check: the program fetches its own page once with net/http's client, prints the status and the first 14 lines of the HTML, and ends. Without -once it prints its address and waits until you press Ctrl+C.

Notes to the lines

  • 22–34The page; {{range .Volumes}} repeats the line of a volume for each data volume.
  • 53collect runs once for every request.
  • 80–82The memory in use as a whole percentage; the check avoids a division by zero when the file is empty.
  • 102–107The handler: the header names the type, and page.Execute writes the HTML straight into the answer.
  • 108–114Listen, then serve in a goroutine, so main can go on.
  • 115[::] (every address) becomes localhost in the printed address, which a browser on the NAS can open.
  • 118–135-once: http.Get, the status line, then the first lines of the body through a bufio.Scanner.
  • 137–141Wait for Ctrl+C, then let open requests finish and stop.

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 web.go
./web

Open http://192.0.2.10:8099/ in a browser on your network, with the address of your NAS in place of 192.0.2.10. If a firewall such as QuFirewall runs on the NAS, allow port 8099 there. ./web -addr :9000 uses another port, and ./web -once checks the page without a browser. Ctrl+C stops the server.

Try it yourself

Add a second handler for /json that answers with the struct from collect through encoding/json. Add the CPU temperature from getsysinfo cputmp to the page.

More projects in Go