goext/ginext/cors.go

23 lines
588 B
Go
Raw Normal View History

2023-07-18 14:40:10 +02:00
package ginext
import (
"github.com/gin-gonic/gin"
"net/http"
2024-07-18 17:29:18 +02:00
"strings"
2023-07-18 14:40:10 +02:00
)
2024-07-18 17:29:18 +02:00
func CorsMiddleware(header []string) gin.HandlerFunc {
2023-07-18 14:40:10 +02:00
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
2024-07-18 17:29:18 +02:00
c.Writer.Header().Set("Access-Control-Allow-Headers", strings.Join(header, ", "))
2023-07-18 14:40:10 +02:00
c.Writer.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE, COUNT")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(http.StatusOK)
} else {
c.Next()
}
}
}