myxce/src/frontend/apiserver/middleware/cors.go

58 lines
1.4 KiB
Go

package middleware
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// CORSMiddleware returns a middleware that sets CORS headers.
// allowedOrigins: list of allowed origins; pass nil to disable CORS entirely.
// Pass []string{"*"} to allow all origins.
func CORSMiddleware(allowedOrigins []string) gin.HandlerFunc {
return func(c *gin.Context) {
if len(allowedOrigins) == 0 {
c.Next()
return
}
origin := c.Request.Header.Get("Origin")
allowed := ""
for _, o := range allowedOrigins {
if o == "*" || o == origin {
allowed = o
break
}
}
if allowed != "" {
c.Header("Access-Control-Allow-Origin", allowed)
c.Header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization")
c.Header("Access-Control-Max-Age", "86400")
}
if c.Request.Method == http.MethodOptions {
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
}
}
// CORSOriginsFromConfig builds the allowed origins list from a config string slice.
// Returns nil if CORS is disabled (empty slice).
func CORSOriginsFromConfig(enabled bool, origins []string) []string {
if !enabled || len(origins) == 0 {
return nil
}
result := make([]string, 0, len(origins))
for _, o := range origins {
if s := strings.TrimSpace(o); s != "" {
result = append(result, s)
}
}
return result
}