Home >Backend Development >Golang >How to Properly Configure CORS Middleware in Go Gin to Handle OPTIONS Requests?

How to Properly Configure CORS Middleware in Go Gin to Handle OPTIONS Requests?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 03:10:09385browse

How to Properly Configure CORS Middleware in Go Gin to Handle OPTIONS Requests?

Enabling CORS in Go Gin Framework

The Go gin framework provides a powerful middleware for enabling CORS (Cross-Origin Resource Sharing) in your applications. By adding this middleware to your app, you can allow requests from different origins to access your API endpoints.

Consider the following CORS middleware implementation:

func CORSMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Content-Type", "application/json")
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Max-Age", "86400")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, X-Max")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(200)
        } else {
            c.Next()
        }
    }
}

However, if using this middleware results in a status code of 200 OK but no further action after OPTION requests, you may have missed a crucial step:

Fix:

func CORSMiddleware() gin.HandlerFunc {</p>
<pre class="brush:php;toolbar:false">return func(c *gin.Context) {
    c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
    c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
    c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
    c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")

    if c.Request.Method == "OPTIONS" {
        c.AbortWithStatus(204)
        return
    }

    c.Next()
}

}

In the updated middleware, c.AbortWithStatus(204) will return a response status of 204 No Content without any body, indicating a successful OPTIONS request and allowing the client to proceed with the actual request.

The above is the detailed content of How to Properly Configure CORS Middleware in Go Gin to Handle OPTIONS Requests?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn