119 lines
3.4 KiB
Go
119 lines
3.4 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"path"
|
|
"runtime/pprof"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/go-chi/cors"
|
|
"medad.fun/internal/api"
|
|
"medad.fun/internal/api/v1/middleware"
|
|
"medad.fun/internal/config"
|
|
"medad.fun/internal/database"
|
|
"medad.fun/internal/frontend"
|
|
"medad.fun/internal/state"
|
|
"medad.fun/internal/version"
|
|
)
|
|
|
|
func main() {
|
|
cfg, err := config.Load()
|
|
if err != nil {
|
|
log.Fatalln("error loading configuration:", err)
|
|
}
|
|
log.Printf("Starting medad.fun server version '%s'\n", version.Version)
|
|
|
|
if cfg.CPUProfilePath != "" {
|
|
log.Println("Starting CPU profiling ....")
|
|
cpuProfileFile, err := os.Create(cfg.CPUProfilePath)
|
|
if err != nil {
|
|
log.Fatal("error creating cpuprofile file:", err)
|
|
}
|
|
if err := pprof.StartCPUProfile(cpuProfileFile); err != nil {
|
|
log.Fatal("error starting cpu profiling:", err)
|
|
}
|
|
}
|
|
|
|
router := http.NewServeMux()
|
|
corsWrapper := cors.Handler(cors.Options{
|
|
AllowedOrigins: cfg.CORS.AllowedOrigins,
|
|
AllowCredentials: cfg.CORS.AllowCredentials,
|
|
})
|
|
|
|
// 1. Create a basic register function for public routes
|
|
register := func(method, p string, handler http.HandlerFunc) {
|
|
if !strings.HasPrefix(p, "/") {
|
|
p = "/" + p
|
|
}
|
|
log.Printf("Registering route: %s %s\n", method, p)
|
|
// Wrap with CORS
|
|
router.HandleFunc(fmt.Sprintf("%s %s", method, p), corsWrapper(handler).ServeHTTP)
|
|
}
|
|
|
|
// 2. Create a protected register function for authenticated routes
|
|
// This wraps the handler in JWT middleware BEFORE CORS
|
|
protectedRegister := func(method, p string, handler http.HandlerFunc) {
|
|
if !strings.HasPrefix(p, "/") {
|
|
p = "/" + p
|
|
}
|
|
log.Printf("Registering PROTECTED route: %s %s\n", method, p)
|
|
|
|
// Chain: JWT Middleware -> CORS Wrapper -> Actual Handler
|
|
// Note: JWT checks auth first. If valid, it passes to CORS, then handler.
|
|
protectedHandler := middleware.JWTMiddleware([]byte(cfg.JWTSecret))(http.HandlerFunc(handler))
|
|
router.HandleFunc(fmt.Sprintf("%s %s", method, p), corsWrapper(protectedHandler).ServeHTTP)
|
|
}
|
|
|
|
// Healthcheck for deployments with monitoring if required.
|
|
register("GET", path.Join(cfg.RootPath, "health"), func(writer http.ResponseWriter, _ *http.Request) {
|
|
writer.WriteHeader(http.StatusOK)
|
|
})
|
|
|
|
api.NewHandler(cfg).SetupRoutes(cfg.RootPath, register, protectedRegister)
|
|
|
|
frontendHandler, err := frontend.NewHandler(cfg)
|
|
if err != nil {
|
|
log.Fatal("error setting up frontend:", err)
|
|
}
|
|
frontendHandler.SetupRoutes(register)
|
|
|
|
if cfg.LobbyCleanup.Interval > 0 {
|
|
state.LaunchCleanupRoutine(cfg.LobbyCleanup)
|
|
}
|
|
|
|
signalChan := make(chan os.Signal, 1)
|
|
signal.Notify(signalChan, syscall.SIGTERM, syscall.SIGINT)
|
|
go func() {
|
|
defer os.Exit(0)
|
|
log.Printf("Received %s, gracefully shutting down.\n", <-signalChan)
|
|
state.ShutdownLobbiesGracefully()
|
|
if cfg.CPUProfilePath != "" {
|
|
pprof.StopCPUProfile()
|
|
log.Println("Finished CPU profiling.")
|
|
}
|
|
}()
|
|
|
|
database.ConnectToDB(cfg.DatabaseURL)
|
|
|
|
address := fmt.Sprintf("%s:%d", cfg.NetworkAddress, cfg.Port)
|
|
log.Println("Started, listening on: http://" + address)
|
|
|
|
httpServer := &http.Server{
|
|
Addr: address,
|
|
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/" && r.URL.Path[len(r.URL.Path)-1] == '/' {
|
|
r.URL.Path = r.URL.Path[:len(r.URL.Path)-1]
|
|
}
|
|
router.ServeHTTP(w, r)
|
|
}),
|
|
ReadHeaderTimeout: 10 * time.Second,
|
|
}
|
|
log.Fatalln(httpServer.ListenAndServe())
|
|
}
|