package middleware import ( "net/http" "strings" "github.com/gin-gonic/gin" ) func CORSMiddleware() gin.HandlerFunc { return func(c *gin.Context) { origin := c.Request.Header.Get("Origin") // Define allowed origins (add your React app's URL) allowedOrigins := []string{ "http://localhost:3000", "http://localhost:3001", "http://localhost:5173", // Vite development server "http://127.0.0.1:3000", "http://127.0.0.1:5173", "http://103.110.8.103:80", // Add production URL "http://103.110.8.103", "http://nam.winteraccess.id", "https://nam.winteraccess.id", "https://nam-dev.winteraccess.id", } // Check if origin is in allowed list isAllowed := false for _, allowed := range allowedOrigins { if origin == allowed { isAllowed = true break } } // For development, also allow localhost variations if strings.Contains(origin, "localhost") || strings.Contains(origin, "127.0.0.1") { isAllowed = true } if origin != "" && isAllowed { // For allowed origins, set specific origin and enable credentials c.Writer.Header().Set("Access-Control-Allow-Origin", origin) c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") } else if origin == "" { // For requests without origin (direct API calls, mobile apps, etc.) c.Writer.Header().Set("Access-Control-Allow-Origin", "*") // Don't set credentials for wildcard } else { // For disallowed origins, still set basic CORS but no credentials c.Writer.Header().Set("Access-Control-Allow-Origin", "*") } c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE, PATCH") c.Writer.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, accept, origin, Cache-Control, X-Requested-With") c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length, Content-Type") c.Writer.Header().Set("Access-Control-Max-Age", "86400") // Handle preflight requests if c.Request.Method == http.MethodOptions { c.AbortWithStatus(http.StatusNoContent) return } c.Next() } }