Configure CORS for a Go backend

Total
0
Shares

According to mozilla.org, Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

When writing a backend for your app using golang in the local environment you can perform requests to your APIs without the need to configure CORS, but once you deploy the backend you will require CORS or else you will face errors communicating with the backend.

This tutorial will help you fix this error in a go backend that uses gin framework.

We will first download and install the cors middleware using the following line

go get github.com/gin-contrib/cors
Enter fullscreen mode

Exit fullscreen mode

Then now import to your main.go file

import "github.com/gin-contrib/cors"
Enter fullscreen mode

Exit fullscreen mode

Now let’s add cors middleware

Add the following code in the main.go file

func main() {
    r := gin.Default()
    config := cors.DefaultConfig()
    config.AllowAllOrigins = true
    config.AllowMethods = []string{"POST", "GET", "PUT", "OPTIONS"}
    config.AllowHeaders = []string{"Origin", "Content-Type", "Authorization", "Accept", "User-Agent", "Cache-Control", "Pragma"}
    config.ExposeHeaders = []string{"Content-Length"}
    config.AllowCredentials = true
    config.MaxAge = 12 * time.Hour

    r.Use(cors.New(config))
}
Enter fullscreen mode

Exit fullscreen mode

Your main.go file should now look like below now;

package main

import (
    "time"

    "github.com/gin-contrib/cors"
    "github.com/gin-gonic/gin"
    "github.com/username/appname/controllers"
)

func init() {
    //initialize app
}

func main() {
    r := gin.Default()
    config := cors.DefaultConfig()
    config.AllowAllOrigins = true
    config.AllowMethods = []string{"POST", "GET", "PUT", "OPTIONS"}
    config.AllowHeaders = []string{"Origin", "Content-Type", "Authorization", "Accept", "User-Agent", "Cache-Control", "Pragma"}
    config.ExposeHeaders = []string{"Content-Length"}
    config.AllowCredentials = true
    config.MaxAge = 12 * time.Hour

    r.Use(cors.New(config))

        //Add endpoints here
    r.POST("/ping/", controllers.Pong)

    r.Run()
}

Enter fullscreen mode

Exit fullscreen mode

You can now deploy and run your go backend successfully on a serverless platform like railway easily and CORS error should be fixed now.

Have any questions?

Total
0
Shares
Valentsea

Deploy Azure Infrastructure using Terraform Cloud

Note: You can get the whole code from this repository: aniketkumarsinha/azure-terraform-infrastructure What is Terraform?Terraform is an infrastructure as…