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
Then now import to your main.go file
import "github.com/gin-contrib/cors"
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))
}
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()
}
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?