initial commit

This commit is contained in:
flo_isea committed 2026-04-20 10:45:34 +02:00
commit fc1673dcff
6 files changed
+295

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
*.exe
config.json
+3
View File
@@ -0,0 +1,3 @@
module powerwatts
go 1.22
+183
View File
@@ -0,0 +1,183 @@
package main
import (
"embed"
"encoding/json"
"errors"
"html/template"
"log"
"net/http"
"os"
"strconv"
"strings"
"sync"
)
//go:embed static/*
var indexHTML embed.FS
type store struct {
mu sync.RWMutex
value int
}
func (s *store) get() int {
s.mu.RLock()
defer s.mu.RUnlock()
return s.value
}
func (s *store) set(v int) {
s.mu.Lock()
s.value = v
s.mu.Unlock()
}
func main() {
secret := os.Getenv("WRITE_SECRET")
addr := os.Getenv("ADDR")
if cfg, err := loadConfig("config.json"); err != nil {
if !errors.Is(err, os.ErrNotExist) {
log.Fatalf("load config: %v", err)
}
} else {
if secret == "" {
secret = cfg.WriteSecret
}
if addr == "" {
addr = cfg.Addr
}
}
if secret == "" {
log.Fatal("WRITE_SECRET is required")
}
if addr == "" {
addr = ":8080"
}
app := &server{
secret: secret,
store: &store{},
}
log.Printf("listening on %s", addr)
log.Fatal(http.ListenAndServe(addr, app.routes()))
}
type server struct {
secret string
store *store
}
type config struct {
WriteSecret string `json:"write_secret"`
Addr string `json:"addr"`
}
func loadConfig(path string) (config, error) {
data, err := os.ReadFile(path)
if err != nil {
return config{}, err
}
var cfg config
if err := json.Unmarshal(data, &cfg); err != nil {
return config{}, err
}
return cfg, nil
}
func (s *server) routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/", s.handleIndex)
mux.HandleFunc("/favicon.svg", s.handleFavicon)
mux.HandleFunc("/write", s.handleWrite)
return mux
}
func (s *server) handleIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
page, err := template.New("index.html").ParseFS(indexHTML, "static/index.html")
if err != nil {
http.Error(w, "template error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := page.Execute(w, map[string]any{"Watts": s.store.get()}); err != nil {
http.Error(w, "render error", http.StatusInternalServerError)
}
}
const faviconSVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Power meter">
<defs>
<linearGradient id="g" x1="16" y1="12" x2="48" y2="52" gradientUnits="userSpaceOnUse">
<stop offset="0" stop-color="#38bdf8"/>
<stop offset="1" stop-color="#22c55e"/>
</linearGradient>
</defs>
<rect x="10" y="14" width="44" height="36" rx="9" fill="#0f172a"/>
<rect x="14" y="18" width="36" height="28" rx="6" fill="none" stroke="url(#g)" stroke-width="3"/>
<path d="M32 22 L25 34 H31 L28 44 L39 30 H33 Z" fill="url(#g)"/>
<path d="M20 50h24" stroke="#334155" stroke-width="4" stroke-linecap="round"/>
</svg>`
func (s *server) handleFavicon(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/favicon.svg" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "image/svg+xml")
_, _ = w.Write([]byte(faviconSVG))
}
func (s *server) handleWrite(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if got := r.Header.Get("X-Secret"); got == "" || got != s.secret {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
value, err := parseWatts(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
s.store.set(value)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"watts": value})
}
func parseWatts(r *http.Request) (int, error) {
contentType := r.Header.Get("Content-Type")
if strings.Contains(contentType, "application/json") {
var payload struct {
Watts *int `json:"watts"`
}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
return 0, errors.New("invalid json")
}
if payload.Watts == nil {
return 0, errors.New("missing watts")
}
return *payload.Watts, nil
}
if err := r.ParseForm(); err != nil {
return 0, errors.New("invalid form data")
}
if v := r.FormValue("watts"); v != "" {
return strconv.Atoi(v)
}
return 0, errors.New("missing watts")
}
+73
View File
@@ -0,0 +1,73 @@
package main
import (
"bytes"
"os"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestHandleIndexRendersWatts(t *testing.T) {
srv := &server{secret: "secret", store: &store{value: 123}}
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
srv.handleIndex(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
if !strings.Contains(rec.Body.String(), "123") {
t.Fatalf("response did not contain watt value: %s", rec.Body.String())
}
}
func TestHandleWriteRequiresSecret(t *testing.T) {
srv := &server{secret: "secret", store: &store{}}
req := httptest.NewRequest(http.MethodPost, "/write", bytes.NewBufferString(`{"watts":456}`))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
srv.handleWrite(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusUnauthorized)
}
}
func TestHandleWriteStoresValue(t *testing.T) {
srv := &server{secret: "secret", store: &store{}}
req := httptest.NewRequest(http.MethodPost, "/write", bytes.NewBufferString(`{"watts":456}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Secret", "secret")
rec := httptest.NewRecorder()
srv.handleWrite(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
if got := srv.store.get(); got != 456 {
t.Fatalf("stored watts = %d, want %d", got, 456)
}
}
func TestLoadConfig(t *testing.T) {
path := t.TempDir() + "/config.json"
if err := os.WriteFile(path, []byte(`{"write_secret":"secret","addr":":9090"}`), 0o600); err != nil {
t.Fatalf("write config: %v", err)
}
cfg, err := loadConfig(path)
if err != nil {
t.Fatalf("loadConfig returned error: %v", err)
}
if cfg.WriteSecret != "secret" {
t.Fatalf("write_secret = %q, want %q", cfg.WriteSecret, "secret")
}
if cfg.Addr != ":9090" {
t.Fatalf("addr = %q, want %q", cfg.Addr, ":9090")
}
}
+12
View File
@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Power meter">
<defs>
<linearGradient id="g" x1="16" y1="12" x2="48" y2="52" gradientUnits="userSpaceOnUse">
<stop offset="0" stop-color="#38bdf8"/>
<stop offset="1" stop-color="#22c55e"/>
</linearGradient>
</defs>
<rect x="10" y="14" width="44" height="36" rx="9" fill="#0f172a"/>
<rect x="14" y="18" width="36" height="28" rx="6" fill="none" stroke="url(#g)" stroke-width="3"/>
<path d="M32 22 L25 34 H31 L28 44 L39 30 H33 Z" fill="url(#g)"/>
<path d="M20 50h24" stroke="#334155" stroke-width="4" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 645 B

+22
View File
@@ -0,0 +1,22 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Power Display</title>
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<style>
:root { color-scheme: light dark; }
body { font-family: system-ui, sans-serif; margin: 0; min-height: 100vh; display: grid; place-items: center; background: #0f172a; color: #e2e8f0; }
main { text-align: center; padding: 2rem; }
.value { font-size: clamp(3rem, 12vw, 8rem); font-weight: 800; line-height: 1; }
.unit { margin-top: 0.75rem; font-size: 1.25rem; color: #94a3b8; }
</style>
</head>
<body>
<main>
<div class="value">{{.Watts}}</div>
<div class="unit">watts</div>
</main>
</body>
</html>