Files
gralias/main.go
2025-06-27 13:22:00 +03:00

81 lines
2.4 KiB
Go

package main
import (
"context"
"gralias/config"
"gralias/handlers"
"gralias/pkg/cache"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
var cfg *config.Config
func init() {
cfg = config.LoadConfigOrDefault("")
}
func ListenToRequests(port string) *http.Server {
mux := http.NewServeMux()
server := &http.Server{
Handler: handlers.LogRequests(handlers.GetSession(mux)),
Addr: ":" + port,
ReadTimeout: time.Second * 5, // TODO: to cfg
WriteTimeout: 0, // sse streaming
}
fs := http.FileServer(http.Dir("assets/"))
mux.Handle("GET /assets/", http.StripPrefix("/assets/", fs))
//
mux.HandleFunc("GET /ping", handlers.HandlePing)
mux.HandleFunc("GET /", handlers.HandleHome)
mux.HandleFunc("POST /login", handlers.HandleFrontLogin)
mux.HandleFunc("POST /join-team", handlers.HandleJoinTeam)
mux.HandleFunc("GET /end-turn", handlers.HandleEndTurn)
mux.HandleFunc("POST /room-create", handlers.HandleCreateRoom)
mux.HandleFunc("GET /start-game", handlers.HandleStartGame)
mux.HandleFunc("GET /room-join", handlers.HandleJoinRoom)
mux.HandleFunc("POST /give-clue", handlers.HandleGiveClue)
mux.HandleFunc("GET /room/exit", handlers.HandleExit)
//elements
mux.HandleFunc("GET /actionhistory", handlers.HandleActionHistory)
mux.HandleFunc("GET /room/createform", handlers.HandleShowCreateForm)
mux.HandleFunc("GET /room/hideform", handlers.HandleHideCreateForm)
mux.HandleFunc("GET /word/show-color", handlers.HandleShowColor)
mux.HandleFunc("POST /check/name", handlers.HandleNameCheck)
mux.HandleFunc("GET /add-bot", handlers.HandleAddBot)
mux.HandleFunc("GET /remove-bot", handlers.HandleRemoveBot)
mux.HandleFunc("GET /mark-card", handlers.HandleMarkCard)
// special
mux.HandleFunc("GET /renotify-bot", handlers.HandleRenotifyBot)
// sse
mux.Handle("GET /sub/sse", handlers.Notifier)
slog.Info("Listening", "addr", port)
return server
}
func main() {
// Setup graceful shutdown
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
server := ListenToRequests(cfg.ServerConfig.Port)
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
panic(err)
}
}()
<-stop
slog.Info("Shutting down server...")
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
slog.Error("server shutdown failed", "error", err)
}
cache.MemCache.BackupNow()
}