1 回答
TA贡献1712条经验 获得超3个赞
要测试 CORS 配置,您可以简单地创建http.Client并检查标头。由于gin.Engineimplements 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.
- 1 回答
- 0 关注
- 110 浏览
添加回答
举报