登录
首页 >  Golang >  Go问答

测试 Gin 中的 CORS 中间件

来源:stackoverflow

时间:2024-03-09 23:00:21 391浏览 收藏

本篇文章给大家分享《测试 Gin 中的 CORS 中间件》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我正在尝试编写一个测试来验证我的 api 的 cors 是否设置正确。该api是用go编写的并使用gin。根据路由器组的不同,我有不同的 cors 设置。它看起来像:

router := gin.New()
router.Use(gin.Recovery())

domainOneCORS := cors.New(cors.Config{
  AllowOrigins:  []string{"https://domainone.com"},
  AllowMethods:  []string{"GET", "POST", "PUT", "DELETE", "PATCH"},
  AllowHeaders:  []string{"Authorization", "Content-Length", "Content-Type", "Origin"},
  ExposeHeaders: []string{"Content-Length"},
  MaxAge:        12 * time.Hour,
})
domainTwoCORS := cors.New(cors.Config{
  AllowOrigins:  []string{"https://domaintwo.com"},
  AllowMethods:  []string{"GET", "POST", "PUT", "DELETE", "PATCH"},
  AllowHeaders:  []string{"Authorization", "Content-Length", "Content-Type", "Origin"},
  ExposeHeaders: []string{"Content-Length"},
  MaxAge:        12 * time.Hour,
})

domainOneAPI := router.Group("/one")
domainOneAPI.Use(domainOneCORS)
{
  domainOneAPI.GET("", handler.DomainOneHealth)
}

domainTwoAPI := router.Group("/two")
domainTwoAPI.Use(domainTwoCORS)
{
  domainTwoAPI.GET("", handler.DomainTwoHealth)
}

我正在尝试找出测试我的配置的最佳方法。我发现的大多数测试都使用处理程序并跳过路由器中间件部分。测试一下有意义吗?即使我可以模拟路由器和响应,它也只是确认 http 客户端可以到达端点。不在不同域上验证 web 应用程序就能够访问 api。 我发现这个问题与 echo 类似。


解决方案


要测试 cors 配置,您只需创建一个 http.client 并检查标头即可。由于 gin.engine 实现了 http.handler,因此您可以利用 httptest.server 和类似的东西:

func TestCors(t *testing.T) {
    r := // create your GIN router with middleware config here
    origin := // The allowed origin that you want to check

    server := httptest.NewServer(r)
    defer server.Close()

    client := &http.Client{}
    req, _ := http.NewRequest(
        "GET",
        "http://"+server.Listener.Addr().String()+"/api",
        nil,
    )
    req.Header.Add("Origin", origin)

    get, err := client.Do(req)
    if err != nil {
        t.Fatal(err)
    }

    // You should get your origin (or a * depending on your config) if the
    // passed origin is allowed.
    o := get.Header.Get("Access-Control-Allow-Origin")
    if o != origin {
        t.Errorf("Got '%s' ; expecting origin '%s'", o, origin)
    }
}

保持类似的测试策略作为基础,您甚至可以编写一个表测试来检查多个来源和 access-control-allow-origin 的预期值。

以上就是《测试 Gin 中的 CORS 中间件》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>