Files
goSportpunktetafel/internal/httpapi/httpapi.go
T

142 lines
3.5 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"
)
// Server represents the HTTP API server.
type Server struct {
addr string
sb *logik.Scoreboard
mux *http.ServeMux
}
// NewServer creates a new HTTP API server.
func NewServer(addr string, sb *logik.Scoreboard) *Server {
s := &Server{
addr: addr,
sb: sb,
mux: http.NewServeMux(),
}
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)
}
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)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `{"status":"ok","team":"rot","score":%d}`, s.sb.RedScore)
case "green", "gruen":
s.sb.Score(logik.TeamGreen)
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()
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()
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)
}