You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
33 lines
973 B
Go
33 lines
973 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"golang.org/x/exp/slices"
|
|
)
|
|
|
|
func CORSMiddleware(allowOrigin []string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
httpOrigin := c.Request.Header.Get("Origin")
|
|
|
|
// 检测origin是否在CORS列表内
|
|
if slices.Contains(allowOrigin, httpOrigin) {
|
|
c.Writer.Header().Set("Access-Control-Allow-Origin", httpOrigin)
|
|
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
|
|
c.Writer.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, Content-Length, X-CSRF-Token, Token, session, Origin, Host, Connection, Accept-Encoding, Accept-Language, X-Requested-With, Range")
|
|
}
|
|
|
|
// 直接返回OPTIONS请求
|
|
if c.Request.Method == http.MethodOptions {
|
|
c.AbortWithStatus(http.StatusNoContent)
|
|
return
|
|
}
|
|
|
|
c.Request.Header.Del("Origin")
|
|
|
|
c.Next()
|
|
}
|
|
}
|