thermograph/frontend/server/internal/handlers/handlers.go

138 lines
5 KiB
Go
Raw Normal View History

frontend: rewrite the SSR content service in Go Ports frontend/ (Jinja2/FastAPI, ~1180 LOC) to Go with html/template. No climate math, no DB, no auth here -- every route fetches from the backend's /content/* API, so this is I/O-bound glue with no hard-porting wall; the risk was always in reproducing the rendering exactly, not the language. Verified with a golden-HTML diff, not just unit tests: both the Python original and the Go rewrite were run against the same committed fixtures (frontend/tests/fixtures/) and every one of the 11 routes compared byte-for-byte. The only surviving differences after that process are insignificant inter-tag whitespace and one attribute where Go's stricter escaper HTML-encodes an apostrophe Jinja left literal (functionally identical in every browser) -- confirmed programmatically by normalizing whitespace and unescaping before diffing, not by eyeballing. That process caught defects unit tests alone would have missed, because map[string]any has no compile-time field check: - Render-context keys were snake_case throughout (content.py's Jinja convention, ported verbatim) while the templates -- written independently -- read PascalCase fields. A missing map key doesn't error in html/template, it silently renders empty, so this was invisible in every status code and every "it built" signal: title, meta description, canonical URL, OpenGraph tags, the homepage's entire ranked list, and the brand-tag/nav-active state were all blank across every page. Fixed by renaming every key to match each template's own header comment (the authoritative per-page field contract) and, where an API struct's exported fields already matched what a template needed (contentapi.CityInfo, Crumb, HomeRanked, HubCountry, ...), passing the struct straight through instead of hand-rewrapping it in a map -- removes a whole layer of future drift risk, not just this instance of it. - Three pages 500'd outright: `.ToolHref` needed a fully-composed href string, not the bare "lat,lon" fragment the handlers were building; the all-time-records table needed the raw contentapi.AllTimeRecords struct, not a re-wrapped map. - JSON-LD was being double-encoded: `<script type="application/ld+json">` is JAVASCRIPT context to html/template's contextual escaper regardless of the script's `type` attribute, so a template.HTML-typed value placed there gets re-escaped as a quoted JS string instead of emitted raw -- the entire structured-data payload shipped as a JSON string containing JSON, which no crawler would parse as the intended object. Needed template.JS instead, the type that actually means "trusted JS source." The glossary term page's JSON-LD was simply never built at all (the Jinja original assembled it inline in the template rather than through content.py's context dict, and that got lost in translation) -- added. - html/template silently strips literal HTML comments AND JavaScript comments from the parsed output (verified in isolation, zero template actions involved) -- confirmed as real engine behavior, not a bug in either port, so both need a FuncMap function returning template.HTML / template.JS respectively to survive parsing rather than a literal `<!-- -->` or `//` in the template source. Packaging: multi-stage Go build, final image alpine (not distroless -- the Swarm stack's env-entrypoint.sh shim needs bash), 187MB -> 22.6MB. Two defects caught before they reached a host: - The Swarm stack overrides `entrypoint:` with no `command:`, which drops the image's own CMD entirely (Docker/Swarm semantics, not merged) -- env-entrypoint.sh then fell through to its hardcoded `exec uvicorn app:app` fallback, which doesn't exist in this image. Every deploy would have exited 127. Fixed with an explicit `command:` on the stack's frontend service, and corrected the shim's stale comment claiming CMD passes through automatically. - `COPY --chown=thermograph` resolves the group by NAME at copy time; Alpine's `adduser -S` with no `-G` doesn't create a same-named group, so the classic (non-BuildKit) Docker builder -- which this CI runner falls back to, since it installs plain `docker.io` with no buildx plugin -- failed outright. Fixed with an explicit group and numeric --chown. Verification: go build/vet/test -race clean across all packages; the Docker image builds and passes its embedded go test step under both BuildKit and the classic builder; shellcheck 0 findings on the one script touched; rebased onto current main (the ERA5 lake stack landed on both main and dev during this work -- confirmed additive, no overlap with frontend/daemon).
2026-07-24 00:49:49 +00:00
// Package handlers is the Go port of app.py's own route layer: the
// interactive tool's SPA shells (app.py's _page) and static-asset serving
// with the short Cache-Control revalidation window. The server-rendered
// content pages, robots.txt/sitemap.xml and the IndexNow key file live in
// internal/content (the content.py port), exactly as the two modules split
// the work in Python.
//
// Wiring (see main.go): content.Handlers.Register takes this package's
// Static() handler so its lazy IndexNow fallback route can hand non-key
// requests back to the file server; Register here adds the shells, the
// static catch-all under BASE, and the bare-BASE 307 redirect.
package handlers
import (
"html/template"
"io"
"log/slog"
"net/http"
)
// Options configures the app.py-layer routes.
type Options struct {
// Base is config.Base: "" or "/x" (THERMOGRAPH_BASE, normalized).
Base string
// StaticDir holds every static asset, including the SPA shell HTML files.
StaticDir string
// GoogleVerify / BingVerify feed the search-console <meta> tags injected
// into the SPA shells (content.head_verify_html read the same env vars;
// the SSR pages get theirs via the template FuncMap's head_verify — the
// two copies must keep emitting identical markup).
GoogleVerify string
BingVerify string
// Log defaults to slog.Default().
Log *slog.Logger
}
// Server holds the state the shell/static handlers share. Safe for
// concurrent use.
type Server struct {
base string
staticDir string
headVerify template.HTML
log *slog.Logger
}
// New builds the Server. It does not touch the filesystem — shell files are
// read lazily on first request, like the Python's _page.
func New(o Options) *Server {
log := o.Log
if log == nil {
log = slog.Default()
}
return &Server{
base: o.Base,
staticDir: o.StaticDir,
headVerify: headVerifyHTML(o.GoogleVerify, o.BingVerify),
log: log,
}
}
// Register attaches the SPA-shell routes, the static catch-all and the
// bare-BASE redirect. Go 1.22 mux precedence (most-specific pattern wins)
// replaces Starlette's registration-order rule — the explicit content routes
// registered elsewhere beat the catch-all no matter who registers first.
// "GET" patterns serve HEAD too, covering the Python's methods=["GET","HEAD"].
func (s *Server) Register(mux *http.ServeMux) {
// The SPA shells for the interactive tool (app.py's _page routes).
// /alerts deliberately serves subscriptions.html.
for _, sh := range []struct{ path, file string }{
{"/calendar", "calendar.html"},
{"/day", "day.html"},
{"/score", "score.html"},
{"/compare", "compare.html"},
{"/legend", "legend.html"},
{"/alerts", "subscriptions.html"},
} {
mux.HandleFunc("GET "+s.base+sh.path, s.shellHandler(sh.file))
}
// Everything else under BASE (app.js, style.css, nav.js, manifest,
// favicons, …) is a static asset. Patterns must start with "/", so at the
// root (Base == "") this registers at "/" — the explicit routes still win
// under the 1.22 precedence rules, replacing Starlette's mount-last order.
mux.Handle("GET "+s.base+"/", s.Static())
if s.base != "" {
// Starlette's redirect_slashes answered the bare base path with a 307
// to BASE+"/" (the only slash redirect the Python actually emitted —
// every other trailing-slash miss fell into the static mount's 404).
// Registered explicitly so the mux's implicit 301 doesn't apply.
base := s.base
mux.HandleFunc("GET "+base, func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, base+"/", http.StatusTemporaryRedirect)
})
}
}
// Static returns the static-asset handler (also handed to
// content.Handlers.Register for its lazy IndexNow fallback delegation).
func (s *Server) Static() http.Handler {
return http.HandlerFunc(s.serveStatic)
}
// originOf is content.py's _origin, which app.py's _page deliberately reused
// rather than a simpler duplicate: the shells are reached both directly
// (Caddy) and through backend's internal proxy fallback, and only this
// version prefers X-Forwarded-Host over Host — required for the proxied case
// to resolve the real browser-facing host instead of this internal hop's own
// address.
func originOf(r *http.Request) string {
proto := r.Header.Get("X-Forwarded-Proto")
if proto == "" {
if r.TLS != nil {
proto = "https"
} else {
proto = "http"
}
}
host := r.Header.Get("X-Forwarded-Host")
if host == "" {
host = r.Host // covers both the Host header and the URL netloc
}
return proto + "://" + host
}
func (s *Server) serverError(w http.ResponseWriter, r *http.Request, err error) {
s.log.Error("internal error", "path", r.URL.Path, "err", err)
writePlain(w, http.StatusInternalServerError, "Internal Server Error")
}
// writePlain mirrors Starlette's PlainTextResponse: text/plain with charset,
// nothing appended to the body.
func writePlain(w http.ResponseWriter, status int, body string) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(status)
_, _ = io.WriteString(w, body)
}