-2

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.

Notation
  • 323
  • 6
  • 19
  • Does this answer your question? [Go gin framework CORS](https://stackoverflow.com/questions/29418478/go-gin-framework-cors) – rustyx Oct 18 '21 at 10:11
  • Listing `access-control-allow-origin` and `access-control-allow-headers` as allowed request headers is pointless since those headers are _response_ headers. – jub0bs Feb 12 '23 at 15:16

1 Answers1

1

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() 
}
mkopriva
  • 35,176
  • 4
  • 57
  • 71
  • `Config not declared by package gin` I am getting this error now. – Notation Oct 18 '21 at 15:42
  • 1
    It's `cors.Config` not `gin.Config`. That's why you also need the `"github.com/gin-contrib/cors"` import. – mkopriva Oct 18 '21 at 15:52
  • Listing `access-control-allow-origin` and `access-control-allow-headers` as allowed request headers is pointless, though, since those headers are _response_ headers. – jub0bs Feb 12 '23 at 15:16