Skip to content

Instantly share code, notes, and snippets.

@mkdym
Created April 4, 2023 13:50
Show Gist options
  • Save mkdym/5909a81fa947ab32599918ee7aba7ce2 to your computer and use it in GitHub Desktop.
Save mkdym/5909a81fa947ab32599918ee7aba7ce2 to your computer and use it in GitHub Desktop.
golang corsMiddleware
func corsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin") //请求头部
if origin != "" {
c.Header("Access-Control-Allow-Origin", origin)
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, X-Extra-Header, Content-Type, Accept, Authorization")
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()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment