Files
powerwatts/internal/server/server.go
T
2026-04-20 15:42:34 +02:00

131 lines
3.5 KiB
Go

package server
import (
"encoding/json"
"errors"
"html/template"
"net/http"
"strconv"
"io/fs"
"strings"
"powerwatts/internal/chart"
"powerwatts/internal/store"
)
type Server struct {
secret string
chartMax int
store *store.Store
templates fs.FS
}
func New(secret string, chartMax int, st *store.Store, templates fs.FS) *Server {
return &Server{secret: secret, chartMax: chartMax, store: st, templates: templates}
}
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(s.templates, "static/index.html")
if err != nil {
http.Error(w, "template error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
watts, updatedAt, history := s.store.Snapshot()
updatedLabel := "not updated yet"
if !updatedAt.IsZero() {
updatedLabel = updatedAt.Format("02.01.2006 15:04:05")
}
if err := page.Execute(w, map[string]any{
"Watts": chart.FormatGermanNumber(watts),
"UpdatedAt": updatedLabel,
"HistoryChart": chart.BuildHistoryChart(history, s.chartMax),
}); err != nil {
http.Error(w, "render error", http.StatusInternalServerError)
}
}
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")
}
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>`