In Go's gin framework, configuring Cross-Origin Resource Sharing (CORS) allows clients from different origins to access your resources. However, you may encounter issues where CORS requests don't return expected behavior, as in the case of the user who experienced an empty response after sending an OPTIONS request.
To resolve this issue, we can analyze the user's provided middleware and compare it to a working example:
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() } } }
func CORSMiddleware() gin.HandlerFunc { 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() } }
Differences:
Therefore, to solve the problem, the user should update their middleware to match the working example, especially by correcting the abort status code and adjusting the allowed methods.
The above is the detailed content of How to Properly Configure CORS Middleware in Go's Gin Framework?. For more information, please follow other related articles on the PHP Chinese website!