You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

303 lines
6.8 KiB

package web
import (
"context"
"embed"
"encoding/json"
"fmt"
"io/fs"
"net/http"
"sync"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"track-gopher/derby"
"track-gopher/web/templates"
)
//go:embed static
var content embed.FS
// Server represents the web server for the derby clock
type Server struct {
router *chi.Mux
clock *derby.DerbyClock
events <-chan derby.Event
clients map[chan string]bool
clientsMux sync.Mutex
port int
server *http.Server
shutdown chan struct{}
}
// NewServer creates a new web server
func NewServer(clock *derby.DerbyClock, events <-chan derby.Event, port int) (*Server, error) {
// Create server
s := &Server{
router: chi.NewRouter(),
clock: clock,
events: events,
clients: make(map[chan string]bool),
clientsMux: sync.Mutex{},
port: port,
shutdown: make(chan struct{}),
}
// Set up routes
s.routes()
// Start event forwarder
go s.forwardEvents()
return s, nil
}
// routes sets up the HTTP routes
func (s *Server) routes() {
// Middleware
s.router.Use(middleware.Logger)
s.router.Use(middleware.Recoverer)
s.router.Use(middleware.Timeout(10 * time.Second))
// Static files
staticFS, _ := fs.Sub(content, "static")
s.router.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(http.FS(staticFS))))
// Pages
s.router.Get("/", s.handleIndex())
// API endpoints
s.router.Post("/api/reset", s.handleReset())
s.router.Post("/api/force-end", s.handleForceEnd())
s.router.Get("/api/status", s.handleStatus())
s.router.Get("/api/events", s.handleEvents())
}
// Start starts the web server
func (s *Server) Start() error {
addr := fmt.Sprintf(":%d", s.port)
s.server = &http.Server{
Addr: addr,
Handler: s.router,
}
// Start server in a goroutine
go func() {
if err := s.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Printf("HTTP server error: %v\n", err)
}
}()
return nil
}
// Stop gracefully shuts down the server
func (s *Server) Stop() error {
// Signal event forwarder to stop
close(s.shutdown)
// Close all client connections
s.clientsMux.Lock()
for clientChan := range s.clients {
delete(s.clients, clientChan)
close(clientChan)
}
s.clientsMux.Unlock()
// Create a context with timeout for shutdown
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Shutdown the HTTP server
if s.server != nil {
return s.server.Shutdown(ctx)
}
return nil
}
// forwardEvents forwards derby events to SSE clients
func (s *Server) forwardEvents() {
for {
select {
case event, ok := <-s.events:
if !ok {
return
}
// Process the event and send to clients
s.broadcastEvent(event)
case <-s.shutdown:
return
}
}
}
// broadcastEvent sends an event to all connected clients
func (s *Server) broadcastEvent(event derby.Event) {
var message string
switch event.Type {
case derby.EventRaceStart:
statusMsg := struct {
Status string `json:"status"`
}{
Status: "running",
}
statusJSON, _ := json.Marshal(statusMsg)
message = fmt.Sprintf("event: status\ndata: %s", statusJSON)
case derby.EventLaneFinish:
// Create a message for lane finish
laneData := struct {
Lane int `json:"lane"`
Time float64 `json:"time"`
Place int `json:"place"`
}{
Lane: event.Result.Lane,
Time: event.Result.Time,
Place: event.Result.FinishPlace,
}
laneJSON, _ := json.Marshal(laneData)
message = fmt.Sprintf("event: lane-finish\ndata: %s", laneJSON)
case derby.EventRaceComplete:
statusMsg := struct {
Status string `json:"status"`
}{
Status: "finished",
}
statusJSON, _ := json.Marshal(statusMsg)
message = fmt.Sprintf("event: status\ndata: %s", statusJSON)
}
if message == "" {
return
}
// Send to all clients
s.clientsMux.Lock()
for clientChan := range s.clients {
select {
case clientChan <- message:
default:
// Client channel is full, could log this
}
}
s.clientsMux.Unlock()
}
// handleIndex handles the index page
func (s *Server) handleIndex() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
templates.Index().Render(r.Context(), w)
}
}
// handleReset handles the reset API endpoint
func (s *Server) handleReset() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := s.clock.Reset(); err != nil {
http.Error(w, fmt.Sprintf("Failed to reset clock: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"status": "reset"}`))
}
}
// handleForceEnd handles the force end API endpoint
func (s *Server) handleForceEnd() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := s.clock.ForceEnd(); err != nil {
http.Error(w, fmt.Sprintf("Failed to force end race: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"status": "forced"}`))
}
}
// handleStatus handles the status API endpoint
func (s *Server) handleStatus() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
status := s.clock.Status()
var statusStr string
switch status {
case derby.StatusIdle:
statusStr = "idle"
case derby.StatusRunning:
statusStr = "running"
case derby.StatusFinished:
statusStr = "finished"
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(fmt.Sprintf(`{"status": "%s"}`, statusStr)))
}
}
// handleEvents handles SSE events
func (s *Server) handleEvents() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Set headers for SSE
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
// Create a channel for this client
clientChan := make(chan string, 10)
// Add client to map with mutex protection
s.clientsMux.Lock()
s.clients[clientChan] = true
s.clientsMux.Unlock()
// Remove client when connection is closed
defer func() {
s.clientsMux.Lock()
delete(s.clients, clientChan)
s.clientsMux.Unlock()
close(clientChan)
}()
// Send initial status
status := s.clock.Status()
var statusStr string
switch status {
case derby.StatusIdle:
statusStr = "idle"
case derby.StatusRunning:
statusStr = "running"
case derby.StatusFinished:
statusStr = "finished"
}
fmt.Fprintf(w, "event: status\ndata: {\"status\": \"%s\"}\n\n", statusStr)
w.(http.Flusher).Flush()
// Keep the connection open
for {
select {
case message, ok := <-clientChan:
if !ok {
return
}
// Send the message to the client
fmt.Fprint(w, message)
w.(http.Flusher).Flush()
case <-r.Context().Done():
// Client disconnected
return
}
}
}
}