加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
cors_test.go 1.94 KB
一键复制 编辑 原始数据 按行查看 历史
aesoper 提交于 2020-05-19 21:00 . init
/**
* @Author: aesoper
* @Description:
* @File: cors_test
* @Version: 1.0.0
* @Date: 2020/5/19 19:24
*/
package gin_middleware
import (
"gitee.com/gin-ecosystem/gin-middleware/consts"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"
)
func TestNewCORS(t *testing.T) {
e := gin.New()
// Wildcard origin
e.GET("/", NewCORS(&CORSConfig{
AllowAllOrigins: true,
}), func(ctx *gin.Context) {
ctx.String(200, "success")
return
})
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(consts.HeaderOrigin, "my11sql.com")
resp := httptest.NewRecorder()
e.ServeHTTP(resp, req)
assert.Equal(t, "*", resp.Header().Get(consts.HeaderAccessControlAllowOrigin))
// Allow origins
e.GET("/allowOrigins", NewCORS(&CORSConfig{
AllowAllOrigins: false,
AllowOrigins: []string{"localhost"},
}), func(ctx *gin.Context) {
ctx.String(200, "success")
return
})
req = httptest.NewRequest(http.MethodGet, "/allowOrigins", nil)
req.Header.Set(consts.HeaderOrigin, "localhost")
resp = httptest.NewRecorder()
e.ServeHTTP(resp, req)
assert.Equal(t, "localhost", resp.Header().Get(consts.HeaderAccessControlAllowOrigin))
// Preflight request
e.Any("/preflight", NewCORS(&CORSConfig{
AllowAllOrigins: false,
AllowOrigins: []string{"localhost"},
AllowCredentials: true,
MaxAge: 3600,
}), func(ctx *gin.Context) {
ctx.String(200, "success")
return
})
req = httptest.NewRequest(http.MethodOptions, "/preflight", nil)
req.Header.Set(consts.HeaderOrigin, "localhost")
resp = httptest.NewRecorder()
e.ServeHTTP(resp, req)
assert.Equal(t, "localhost", resp.Header().Get(consts.HeaderAccessControlAllowOrigin))
assert.NotEmpty(t, resp.Header().Get(consts.HeaderAccessControlAllowMethods))
assert.Equal(t, "true", resp.Header().Get(consts.HeaderAccessControlAllowCredentials))
assert.Equal(t, "3600", resp.Header().Get(consts.HeaderAccessControlMaxAge))
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化