kacarmichael 309eeef59a
Some checks failed
Build Go Binaries / build (push) Has been cancelled
Health/status http endpoint, logging
2026-08-06 01:24:29 -05:00

61 lines
1.9 KiB
Go

package health
import (
"context"
_ "embed"
"encoding/json"
"fmt"
"m3u8-downloader/pkg/config"
"m3u8-downloader/pkg/logging"
"net"
"net/http"
)
//go:embed dashboard.html
var dashboardHTML []byte
// Start binds the health/status HTTP server and returns immediately once the
// listener is bound, so callers see bind failures (e.g. port already in use)
// synchronously rather than losing them in a background goroutine. The
// returned *http.Server should be shut down by the caller via Shutdown(ctx).
//
// Security note: cfg.Addr is expected to be a bind-all address (e.g. ":8090")
// so status can be checked from other devices on the local network during a
// live event. There is no authentication or TLS on these endpoints - this is
// only safe on a trusted local network, never exposed to the open internet.
func Start(ctx context.Context, cfg *config.HealthConfig, reg *Registry) (*http.Server, error) {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(dashboardHTML)
})
mux.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(reg.Snapshot()); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
})
ln, err := net.Listen("tcp", cfg.Addr)
if err != nil {
return nil, fmt.Errorf("failed to bind health server to %s: %w", cfg.Addr, err)
}
srv := &http.Server{Handler: mux}
go func() {
if err := srv.Serve(ln); err != nil && err != http.ErrServerClosed {
logging.MustGetFactory().App.Error("health server stopped unexpectedly", logging.KeyError, err.Error())
}
}()
return srv, nil
}