Home > OS >  Enable Cors policy in golang
Enable Cors policy in golang

Time:10-19

How do we enable cors policy in server side using golang ? main.go

func main() {
    defer config.CloseDatabaseConnection(db)
    r := gin.Default()
    dataRoutes := r.Group("api/item")
    {
        dataRoutes.GET("/", dataController.All)
        dataRoutes.POST("/", dataController.Insert)
        dataRoutes.GET("/:id", dataController.FindByID)
        dataRoutes.PUT("/:id", dataController.Update)
        dataRoutes.DELETE("/:id", dataController.Delete)
    }

    r.Run() 
}

I found

func Cors(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html; charset=ascii")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Headers","Content-Type,access-control-allow-origin, access-control-allow-headers")
    }
  

But I am not sure how we implement in the golang? I have use above code while doing with c# but I am stuck in golang while implementing it.

CodePudding user response:

If you are using gin-gonic then you can use the CORS middleware as shown in the example below.

If you need to set other CORS specific headers, see the documentation on cors.Config.

import (
    // your other imports ...

    "github.com/gin-contrib/cors"
    "github.com/gin-gonic/gin"
)

func main() {
    defer config.CloseDatabaseConnection(db)
    r := gin.Default()
    r.Use(cors.New(cors.Config{
        AllowOrigins: []string{"*"},
        AllowMethods: []string{"POST", "PUT", "PATCH", "DELETE"},
        AllowHeaders: []string{"Content-Type,access-control-allow-origin, access-control-allow-headers"},
    }))

    dataRoutes := r.Group("api/item")
    {
        dataRoutes.GET("/", dataController.All)
        dataRoutes.POST("/", dataController.Insert)
        dataRoutes.GET("/:id", dataController.FindByID)
        dataRoutes.PUT("/:id", dataController.Update)
        dataRoutes.DELETE("/:id", dataController.Delete)
    }

    r.Run() 
}
  • Related