Follow

Follow

CORS handling in Go-Gin Framework!

Maheshwar Ligade's photo
Maheshwar Ligade
·May 15, 2023·

3 min read

Play this article

Table of contents

  • Introduction:
  • Setting up Gin:
  • Handling CORS in Gin:
  • Conclusion:

Introduction:

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.

Setting up Gin:

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.

Handling CORS in Gin:

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.

Conclusion:

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://medium.com/techwasti

https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA

https://www.techwasti.com/

\==========================**=========================

If this article adds any value to you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this