【问题标题】:Enable Cors policy in golang在 golang 中启用 Cors 策略
【发布时间】:2021-12-05 01:33:02
【问题描述】:

我们如何使用 golang 在服务器端启用 cors 策略? 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() 
}

我找到了

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")
    }
  

但我不确定我们如何在 golang 中实现?我在处理c# 时使用了上面的代码,但在实现它时我被困在golang 中。

【问题讨论】:

标签: go routes cors


【解决方案1】:

如果您使用的是gin-gonic,那么您可以使用CORS middleware,如下例所示。

如果您需要设置其他 CORS 特定标头,请参阅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() 
}

【讨论】:

  • Config not declared by package gin 我现在收到此错误。
  • 这是cors.Config 不是gin.Config。这就是为什么您还需要 "github.com/gin-contrib/cors" 导入。
猜你喜欢
  • 2017-01-23
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
  • 2021-07-04
  • 2021-07-20
  • 2021-11-13
  • 1970-01-01
  • 2018-08-03
相关资源
最近更新 更多