CORS handling in Go-Gin Framework!
Learner, Love to make things simple, Full Stack Developer, StackOverflower, Passionate about using machine learning, deep learning and AI
Search for a command to run...
Learner, Love to make things simple, Full Stack Developer, StackOverflower, Passionate about using machine learning, deep learning and AI
No comments yet. Be the first to comment.
Move beyond traditional RESTful thinking. Learn how to design APIs specifically for MCP (Model Context Protocol) servers. This guide covers the shift in mindset, a practical OpenAPI 3.1 example, and a Spring Boot implementation to make your services ...

Extending Kestra to Every Corner of Your Data Stack. Introduction: The Power of Plugins Imagine you're a master chef. You don't just have one knife - you have specialized tools for every task: a paring knife for delicate work, a chef's knife for chop...
Mastering Complex Orchestration Scenarios. Introduction: The Orchestrator's Toolkit Imagine you're conducting a symphony. You don't just wave your baton - you cue sections, adjust tempo, handle surprises, and ensure harmony. That's what advanced work...
From Data Extraction to Loading - A Practical Guide Introduction: Why ETL Still Matters in the Modern Data Stack Remember when data engineering was "extract, transform, load"? Some say ETL is dead, replaced by ELT, reverse ETL, and data mesh. But her...
Building Blocks of Declarative Orchestration. Introduction: The Power of Simplicity Imagine trying to build a house without understanding bricks, beams, and blueprints. That's what using an orchestration tool without understanding its core concepts f...

CORS (Cross-Origin Resource Sharing) is a security mechanism that prevents a web page from making requests to a different domain than the one that served the page. When making cross-origin requests, the browser sends an Origin header to the server to indicate the domain of the page that made the request. The server then decides whether to allow or deny the request based on the domain of the Origin header.
In this article, we will explore how to handle CORS in Gin framework using middleware.
Before we dive into CORS handling, let's set up a simple Gin server that we will use throughout this article.
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/hello", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello, World!",
})
})
r.Run(":8080")
}
This server has a single endpoint /hello that returns a JSON response with a message "Hello, World!". Let's now see how to handle CORS in this server.
Gin provides a middleware called Cors() that can be used to handle CORS. This middleware can be added to the Gin engine using the Use() method.
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.Use(corsMiddleware())
r.GET("/hello", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello, World!",
})
})
r.Run(":8080")
}
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")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
In the above code, we have added a corsMiddleware() function that returns a Gin middleware function. This middleware sets the necessary CORS headers in the response, allowing cross-origin requests.
The Access-Control-Allow-Origin header is set to "*" to allow any domain to make requests. In a production environment, you should set this header to the domain(s) that are allowed to make requests.
The Access-Control-Allow-Methods header specifies the HTTP methods that are allowed for cross-origin requests. In this example, we have allowed GET, POST, PUT, and DELETE methods.
The Access-Control-Allow-Headers header specifies the request headers that are allowed for cross-origin requests. In this example, we have allowed the Content-Type and Authorization headers.
The middleware also checks if the HTTP method is OPTIONS. The OPTIONS method is used by the browser to check if a cross-origin request is allowed. If the method is OPTIONS, the middleware responds with a status code 204 and aborts the request.
In this article, we have seen how to handle CORS in Gin framework using middleware. Gin provides a Cors() middleware that can be used to set the necessary headers to allow cross-origin requests. By using this middleware, we can easily handle CORS in our Gin applications.
I hope this helps, you!!
More such articles:
https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA
\==========================**=========================
If this article adds any value to you then please clap and comment.
Let’s connect on Stackoverflow, LinkedIn, & Twitter.