Skip to content

Commit

Permalink
fix: 增加跨域 middleware 快捷方法
Browse files Browse the repository at this point in the history
  • Loading branch information
tangx committed Dec 6, 2021
1 parent 81cbcdf commit 0d2fe89
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions pkg/middlewares/cors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package middlewares

import (
"net/http"

"github.com/gin-gonic/gin"
"github.com/tangx/rum-gonic/rum"
)

// DefaultCorsPolicy 默认跨域规则, 所有来源
func DefaultCorsPolicy() rum.MiddlewareOperator {
return CorsPolicy("*")
}

// CorsPolicy 允许跨域来源
// example, sorigin = https://developer.mozilla.org
func CorsPolicy(origin string) rum.MiddlewareOperator {

cors := func(c *gin.Context) {
method := c.Request.Method
if method != "" {
c.Header("Access-Control-Allow-Origin", origin) // 可将将 * 替换为指定的域名
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization,X-Token")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
}

if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}

c.Next()
}

return rum.NewMiddleware(cors)
}

0 comments on commit 0d2fe89

Please sign in to comment.