cors.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package middleware
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. "github.com/sirupsen/logrus"
  6. )
  7. // CORS handles Cross-Origin Resource Sharing (CORS) for the API
  8. func CORS() gin.HandlerFunc {
  9. return func(c *gin.Context) {
  10. origin := c.Request.Header.Get("Origin")
  11. // Debug logging
  12. logger := logrus.WithFields(logrus.Fields{
  13. "origin": origin,
  14. "path": c.Request.URL.Path,
  15. "method": c.Request.Method,
  16. })
  17. logger.Debug("CORS request received")
  18. // For development, allow all origins
  19. // In production, you would want to restrict this
  20. if origin != "" {
  21. c.Header("Access-Control-Allow-Origin", origin)
  22. c.Header("Access-Control-Allow-Credentials", "true")
  23. c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
  24. c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Accept, X-Requested-With")
  25. c.Header("Access-Control-Expose-Headers", "Content-Length, Content-Type, Authorization")
  26. }
  27. // Handle preflight requests
  28. if c.Request.Method == http.MethodOptions {
  29. c.AbortWithStatus(http.StatusOK)
  30. return
  31. }
  32. c.Next()
  33. }
  34. }