goext/ginext/cors.go

26 lines
746 B
Go
Raw Permalink 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:45:56 +02:00
func CorsMiddleware(allowheader []string, exposeheader []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:45:56 +02:00
c.Writer.Header().Set("Access-Control-Allow-Headers", strings.Join(allowheader, ", "))
if len(exposeheader) > 0 {
c.Writer.Header().Set("Access-Control-Expose-Headers", strings.Join(exposeheader, ", "))
}
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()
}
}
}