Files
chart/viewer/handler.go
2026-03-15 17:28:19 +03:00

74 lines
1.7 KiB
Go

package viewer
import (
"io"
"net/http"
"strings"
"reanimator/chart/web"
)
type HandlerOptions struct {
Title string
}
func NewHandler(opts HandlerOptions) http.Handler {
title := strings.TrimSpace(opts.Title)
if title == "" {
title = "Reanimator Chart"
}
mux := http.NewServeMux()
mux.Handle("GET /static/", http.StripPrefix("/static/", web.Static()))
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
})
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
html, err := RenderHTML(nil, title)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write(html)
})
mux.HandleFunc("POST /render", func(w http.ResponseWriter, r *http.Request) {
var payload string
if strings.Contains(r.Header.Get("Content-Type"), "application/json") {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
payload = string(body)
} else {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
payload = r.FormValue("snapshot")
}
page, err := buildPageData([]byte(payload), title)
if err != nil {
page = pageData{
Title: title,
Error: err.Error(),
InputJSON: prettyJSON(payload),
}
} else {
page.InputJSON = prettyJSON(payload)
}
html, renderErr := web.Render(page)
if renderErr != nil {
http.Error(w, renderErr.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write(html)
})
return mux
}