package server import ( "fmt" "log" "os" "studia/internal/auth" "studia/internal/config" "studia/internal/database" "time" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" ) func StartServer(cfg *config.Config) { router := gin.Default() db := database.New(cfg) // 2. CORS-Konfiguration // Lese die Frontend-URL aus den Umgebungsvariablen frontendURL := os.Getenv("FRONTEND_URL") // Lokaler Fallback (wichtig für die Entwicklung) allowedOrigins := []string{ "http://localhost:5173", // Gängiger Vite-Dev-Port } if frontendURL != "" { allowedOrigins = append(allowedOrigins, frontendURL) fmt.Printf("CORS: Erlaubte Produktiv-URL hinzugefügt: %s\n", frontendURL) } else { log.Println("ACHTUNG: FRONTEND_URL fehlt in den Umgebungsvariablen. Nur lokale URLs erlaubt.") } // CORS // Konfiguriere die CORS-Middleware config := cors.Config{ // Setze die erlaubten Ursprünge (deine React-URLs) AllowOrigins: allowedOrigins, // Erlaube die notwendigen HTTP-Methoden AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"}, // Erlaube Header (z.B. für JSON und Authentifizierung) AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"}, // Erlaube Cookies und Credentials (falls du Tokens oder Sessions nutzt) AllowCredentials: true, // Wie lange die Preflight-Anfrage (OPTIONS) gecacht werden darf MaxAge: 12 * time.Hour, } router.Use(cors.New(config)) router.POST("/login", func(c *gin.Context) { auth.Login(c, db) // Pass the actual DB connection instead of nil }) router.Run(":" + cfg.Port) }