Files
goSportpunktetafel/internal/httpapi/httpapi.go
T
hermes bd05edfb9c M7: Frontend - HTML/JS/CSS mit dunklem Design, Vollbild, WebSocket-Updates, embed.FS-Integration
- Frontend: index.html, style.css, app.js
  - Dunkles Kontrast-Design mit Team-Farben (Rot/Grün)
  - Vollbild-Toggle, Responsive Design
  - Echtzeit-Updates über WebSocket + Polling-Fallback
  - Tastatur-Shortcuts (R/G für Punkte, N für nächste Runde)
  - Rundenverlauf mit Farbcodierung

- Go-Integration:
  - frontend.go: embed.FS für statische Dateien
  - websocket.go: WebSocket-Handler (/ws) für State-Broadcast
  - httpapi.go: broadcastState() nach jeder Mutation, /ws-Route
  - main.go: api.SetupFrontend() für Frontend-Einbettung
  - Frontend unter '/' verfügbar, API unter '/api/'

- Tests: 17 End-to-End-Tests bestanden
  - Alle HTTP-Endpunkte funktionsfähig
  - Frontend-Assets korrekt eingebettet
  - Persistenz (state.json) funktioniert
2026-07-14 16:32:21 +02:00

169 lines
4.2 KiB
Go

// Package httpapi provides the HTTP API server for the scoreboard.
package httpapi
import (
"encoding/json"
"fmt"
"net"
"net/http"
"os"
"strings"
"git.jlserver.de/goSportpunktetafel/internal/logik"
)
// SaveFunc is the type for saving the scoreboard state.
type SaveFunc func(state interface{}) error
// Server represents the HTTP API server.
type Server struct {
addr string
sb *logik.Scoreboard
mux *http.ServeMux
saveFunc SaveFunc
}
// NewServer creates a new HTTP API server.
func NewServer(addr string, sb *logik.Scoreboard, save SaveFunc) *Server {
s := &Server{
addr: addr,
sb: sb,
mux: http.NewServeMux(),
saveFunc: save,
}
s.setupRoutes()
return s
}
// ListenAndServe starts the HTTP server and blocks until it stops.
func (s *Server) ListenAndServe() error {
// Create listener that supports both IPv4 and IPv6
listener, err := net.Listen("tcp", s.addr)
if err != nil {
return fmt.Errorf("failed to create listener: %w", err)
}
addr := listener.Addr().String()
fmt.Fprintf(os.Stderr, "[httpapi] Starting HTTP server on %s\n", addr)
return http.Serve(listener, s.mux)
}
// Close gracefully shuts down the HTTP server.
func (s *Server) Close() error {
return nil
}
func (s *Server) setupRoutes() {
s.mux.HandleFunc("/api/score", s.handleScore)
s.mux.HandleFunc("/api/state", s.handleState)
s.mux.HandleFunc("/api/next", s.handleNextRound)
s.mux.HandleFunc("/api/reset", s.handleReset)
s.mux.HandleFunc("/api/", s.handleAPI)
s.mux.HandleFunc("/ws", s.wsHandler)
}
func (s *Server) persist() {
if s.saveFunc != nil {
if err := s.saveFunc(s.sb); err != nil {
fmt.Fprintf(os.Stderr, "[persist] Save error: %v\n", err)
}
}
}
func (s *Server) handleScore(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
team := r.URL.Query().Get("team")
switch strings.ToLower(team) {
case "red", "rot":
s.sb.Score(logik.TeamRed)
s.persist()
s.broadcastState()
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `{"status":"ok","team":"rot","score":%d}`, s.sb.RedScore)
case "green", "gruen":
s.sb.Score(logik.TeamGreen)
s.persist()
s.broadcastState()
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `{"status":"ok","team":"gruen","score":%d}`, s.sb.GreenScore)
default:
http.Error(w, `{"error":"invalid team. use red or green"}`, http.StatusBadRequest)
}
}
func (s *Server) handleState(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
response := map[string]interface{}{
"current_round": s.sb.CurrentRound,
"red_score": s.sb.RedScore,
"green_score": s.sb.GreenScore,
"rounds": s.sb.Rounds,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func (s *Server) handleNextRound(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
s.sb.NextRound()
s.persist()
s.broadcastState()
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `{"status":"ok","round":%d}`, s.sb.CurrentRound)
}
func (s *Server) handleReset(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
s.sb.Reset()
s.persist()
s.broadcastState()
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `{"status":"ok"}`)
}
func (s *Server) handleAPI(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"service": "sportscore",
"version": "1.0",
"endpoints": []string{
"GET /api/state",
"POST /api/score?team=red|green",
"POST /api/next",
"POST /api/reset",
},
})
}
// PrintFlags prints the configuration flags to stderr.
func PrintFlags(port int, bindAddr string) {
addr := bindAddr
if addr == "" {
addr = "0.0.0.0"
}
fmt.Fprintf(os.Stderr, "[config] HTTP API: %s:%d\n", addr, port)
}
// SetupFrontend registers the frontend handler on the server's mux.
func (s *Server) SetupFrontend() {
SetupFrontend(s.mux)
}