在Golang中启用CORS策略。

huangapple go评论91阅读模式
英文:

Enable Cors policy in golang

问题

在使用Golang的服务器端如何启用CORS策略?

你可以使用以下代码在Golang中实现CORS策略:

func CorsMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type,access-control-allow-origin, access-control-allow-headers")
        c.Next()
    }
}

func main() {
    defer config.CloseDatabaseConnection(db)
    r := gin.Default()
    r.Use(CorsMiddleware()) // 添加CORS中间件
    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() 
}

在上面的代码中,我们定义了一个名为CorsMiddleware的中间件函数,该函数设置了CORS相关的响应头。然后,在main函数中使用r.Use(CorsMiddleware())将该中间件应用到所有的路由上。

这样就可以在Golang中实现CORS策略了。希望对你有帮助!

英文:

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.

答案1

得分: 1

如果你正在使用gin-gonic,你可以像下面的示例中所示,使用CORS中间件

如果你需要设置其他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() 
}
英文:

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

huangapple
  • 本文由 发表于 2021年10月18日 04:56:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/69608544.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定