package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "Hello, World!"}) }) r.Run() }
func CorsMiddleware() gin.HandlerFunc { return func(c *gin.Context) { c.Writer.Header().Set("Access-Control-Allow-Origin", "*") c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") c.Writer.Header().Set("Content-Type", "application/json") if c.Request.Method == "OPTIONS" { c.AbortWithStatus(http.StatusOK) return } c.Next() } } func main() { r := gin.Default() r.Use(CorsMiddleware()) r.GET("/", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "Hello, World!"}) }) r.Run() }In this example, we define a middleware function `CorsMiddleware()` that adds CORS headers to every response. We use the `Use()` method to add this middleware to our router, so it gets executed on every request. The middleware function first sets the required headers, then checks if the request is an OPTIONS request, and if so, returns a 200 response. Finally, it calls `Next()` to continue processing the request. We then define a route with a JSON response like before.