M6: HTTP-API-Server mit allen Endpunkten, Flag-Config, DualStack-Listener

This commit is contained in:
2026-07-14 14:35:28 +02:00
parent 33f3f157b5
commit 9a6a561f39
2 changed files with 477 additions and 0 deletions
+141
View File
@@ -0,0 +1,141 @@
// 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)
}
+336
View File
@@ -0,0 +1,336 @@
package httpapi
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
"git.jlserver.de/goSportpunktetafel/internal/logik"
)
func newTestServer() (*Server, *logik.Scoreboard) {
sb := logik.NewScoreboard()
s := NewServer("127.0.0.1:0", sb)
return s, sb
}
func TestHandleState(t *testing.T) {
s, sb := newTestServer()
defer s.Close()
sb.Score(logik.TeamRed)
sb.Score(logik.TeamRed)
sb.Score(logik.TeamGreen)
req := httptest.NewRequest(http.MethodGet, "/api/state", nil)
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("Status = %d, want %d", w.Code, http.StatusOK)
}
var response map[string]interface{}
if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
t.Fatalf("Failed to decode response: %v", err)
}
if int(response["red_score"].(float64)) != 2 {
t.Errorf("red_score = %v, want 2", response["red_score"])
}
if int(response["green_score"].(float64)) != 1 {
t.Errorf("green_score = %v, want 1", response["green_score"])
}
if int(response["current_round"].(float64)) != 1 {
t.Errorf("current_round = %v, want 1", response["current_round"])
}
}
func TestHandleState_WithRounds(t *testing.T) {
s, sb := newTestServer()
defer s.Close()
sb.Score(logik.TeamRed)
sb.Score(logik.TeamRed)
sb.Score(logik.TeamRed)
sb.NextRound()
sb.Score(logik.TeamGreen)
sb.Score(logik.TeamGreen)
sb.NextRound()
req := httptest.NewRequest(http.MethodGet, "/api/state", nil)
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("Status = %d, want %d", w.Code, http.StatusOK)
}
var response map[string]interface{}
if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
t.Fatalf("Failed to decode response: %v", err)
}
if int(response["current_round"].(float64)) != 3 {
t.Errorf("current_round = %v, want 3", response["current_round"])
}
rounds := response["rounds"].([]interface{})
if len(rounds) != 2 {
t.Fatalf("len(rounds) = %d, want 2", len(rounds))
}
r1 := rounds[0].(map[string]interface{})
if int(r1["Red"].(float64)) != 3 {
t.Errorf("round 1 red = %v, want 3", r1["Red"])
}
r2 := rounds[1].(map[string]interface{})
if int(r2["Green"].(float64)) != 2 {
t.Errorf("round 2 green = %v, want 2", r2["Green"])
}
}
func TestHandleScore_Red(t *testing.T) {
s, sb := newTestServer()
defer s.Close()
req := httptest.NewRequest(http.MethodPost, "/api/score?team=red", nil)
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("Status = %d, want %d", w.Code, http.StatusOK)
}
if sb.RedScore != 1 {
t.Errorf("RedScore = %d, want 1", sb.RedScore)
}
}
func TestHandleScore_Green(t *testing.T) {
s, sb := newTestServer()
defer s.Close()
req := httptest.NewRequest(http.MethodPost, "/api/score?team=green", nil)
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("Status = %d, want %d", w.Code, http.StatusOK)
}
if sb.GreenScore != 1 {
t.Errorf("GreenScore = %d, want 1", sb.GreenScore)
}
}
func TestHandleScore_InvalidTeam(t *testing.T) {
s, _ := newTestServer()
defer s.Close()
req := httptest.NewRequest(http.MethodPost, "/api/score?team=blue", nil)
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("Status = %d, want %d", w.Code, http.StatusBadRequest)
}
}
func TestHandleScore_WrongMethod(t *testing.T) {
s, _ := newTestServer()
defer s.Close()
req := httptest.NewRequest(http.MethodGet, "/api/score?team=red", nil)
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Errorf("Status = %d, want %d", w.Code, http.StatusMethodNotAllowed)
}
}
func TestHandleNextRound(t *testing.T) {
s, sb := newTestServer()
defer s.Close()
sb.Score(logik.TeamRed)
sb.Score(logik.TeamRed)
req := httptest.NewRequest(http.MethodPost, "/api/next", nil)
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("Status = %d, want %d", w.Code, http.StatusOK)
}
if sb.CurrentRound != 2 {
t.Errorf("CurrentRound = %d, want 2", sb.CurrentRound)
}
if sb.RedScore != 0 {
t.Errorf("RedScore after next = %d, want 0", sb.RedScore)
}
if sb.GreenScore != 0 {
t.Errorf("GreenScore after next = %d, want 0", sb.GreenScore)
}
var response map[string]interface{}
json.NewDecoder(w.Body).Decode(&response)
if int(response["round"].(float64)) != 2 {
t.Errorf("response round = %v, want 2", response["round"])
}
}
func TestHandleReset(t *testing.T) {
s, sb := newTestServer()
defer s.Close()
sb.Score(logik.TeamRed)
sb.Score(logik.TeamGreen)
sb.Score(logik.TeamGreen)
sb.NextRound()
sb.Score(logik.TeamRed)
req := httptest.NewRequest(http.MethodPost, "/api/reset", nil)
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("Status = %d, want %d", w.Code, http.StatusOK)
}
if sb.CurrentRound != 1 {
t.Errorf("CurrentRound = %d, want 1", sb.CurrentRound)
}
if sb.RedScore != 0 {
t.Errorf("RedScore = %d, want 0", sb.RedScore)
}
if sb.GreenScore != 0 {
t.Errorf("GreenScore = %d, want 0", sb.GreenScore)
}
if len(sb.Rounds) != 0 {
t.Errorf("len(Rounds) = %d, want 0", len(sb.Rounds))
}
}
func TestHandleReset_WrongMethod(t *testing.T) {
s, _ := newTestServer()
defer s.Close()
req := httptest.NewRequest(http.MethodGet, "/api/reset", nil)
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Errorf("Status = %d, want %d", w.Code, http.StatusMethodNotAllowed)
}
}
func TestHandleNextRound_WrongMethod(t *testing.T) {
s, _ := newTestServer()
defer s.Close()
req := httptest.NewRequest(http.MethodGet, "/api/next", nil)
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Errorf("Status = %d, want %d", w.Code, http.StatusMethodNotAllowed)
}
}
func TestHandleState_WrongMethod(t *testing.T) {
s, _ := newTestServer()
defer s.Close()
req := httptest.NewRequest(http.MethodPost, "/api/state", nil)
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Errorf("Status = %d, want %d", w.Code, http.StatusMethodNotAllowed)
}
}
func TestHandleAPI(t *testing.T) {
s, _ := newTestServer()
defer s.Close()
req := httptest.NewRequest(http.MethodGet, "/api/", nil)
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("Status = %d, want %d", w.Code, http.StatusOK)
}
body, err := io.ReadAll(w.Body)
if err != nil {
t.Fatalf("Failed to read body: %v", err)
}
if !contains(string(body), `"service"`) {
t.Errorf("Response missing service field: %s", string(body))
}
if !contains(string(body), `"sportscore"`) {
t.Errorf("Response missing sportscore value: %s", string(body))
}
}
func TestHandleAPI_ContentType(t *testing.T) {
s, _ := newTestServer()
defer s.Close()
req := httptest.NewRequest(http.MethodGet, "/api/", nil)
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
contentType := w.Header().Get("Content-Type")
if contentType != "application/json" {
t.Errorf("Content-Type = %q, want %q", contentType, "application/json")
}
}
func TestEndToEnd(t *testing.T) {
// Simulate a complete game
s, sb := newTestServer()
defer s.Close()
// Round 1: Red scores 3, Green scores 1
sb.Score(logik.TeamRed)
sb.Score(logik.TeamRed)
sb.Score(logik.TeamGreen)
sb.Score(logik.TeamRed)
// Check state
req := httptest.NewRequest(http.MethodGet, "/api/state", nil)
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
var state map[string]interface{}
json.NewDecoder(w.Body).Decode(&state)
if int(state["red_score"].(float64)) != 3 {
t.Errorf("After round 1: red_score = %v, want 3", state["red_score"])
}
// Next round
req = httptest.NewRequest(http.MethodPost, "/api/next", nil)
w = httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
if sb.CurrentRound != 2 {
t.Errorf("After next: CurrentRound = %d, want 2", sb.CurrentRound)
}
}
// contains is a simple string contains check.
func contains(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}