package main
import (
"embed"
"html"
"io/fs"
"log/slog"
"net/http"
"os"
"os/exec"
"strings"
)
//go:embed web/*
var webFS embed.FS
func main() {
addr := os.Getenv("LISTEN_ADDR")
if addr == "" {
addr = "127.0.0.1:8080"
}
static, err := fs.Sub(webFS, "web")
if err != nil {
slog.Error("embed fs", "err", err)
os.Exit(1)
}
indexHTML, err := fs.ReadFile(static, "index.html")
if err != nil {
slog.Error("read index", "err", err)
os.Exit(1)
}
mux := http.NewServeMux()
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
uptime := uptimeLine()
body := strings.ReplaceAll(string(indexHTML), "{{uptime}}", html.EscapeString(uptime))
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write([]byte(body))
})
mux.Handle("GET /style.css", http.FileServer(http.FS(static)))
slog.Info("listening", "addr", addr)
if err := http.ListenAndServe(addr, mux); err != nil {
slog.Error("serve", "err", err)
os.Exit(1)
}
}
func uptimeLine() string {
out, err := exec.Command("uptime").Output()
if err != nil {
return "uptime unavailable"
}
return strings.TrimSpace(string(out))
}