feat: simplify SOP to immediate-effect configuration
This commit is contained in:
@@ -13,6 +13,22 @@ import (
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// CORS 完全开放跨域访问:允许所有来源、方法和请求头,并直接响应预检请求。
|
||||
func CORS() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||
c.Header("Access-Control-Allow-Headers", "*")
|
||||
c.Header("Access-Control-Expose-Headers", "X-Request-ID, Content-Length")
|
||||
c.Header("Access-Control-Max-Age", "86400")
|
||||
if c.Request.Method == http.MethodOptions {
|
||||
c.AbortWithStatus(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func RequestLogger(log *zap.Logger) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
started := time.Now()
|
||||
|
||||
@@ -30,3 +30,34 @@ func TestRequestLoggerUsesStatusLevelAndDurationMilliseconds(t *testing.T) {
|
||||
t.Fatalf("duration_ms is missing from request log")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCORSAllowsAllOriginsAndAnswersPreflight(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
router.Use(CORS())
|
||||
router.GET("/ping", func(c *gin.Context) { c.Status(http.StatusOK) })
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/ping", nil)
|
||||
req.Header.Set("Origin", "https://crm.example.com")
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "*" {
|
||||
t.Fatalf("Access-Control-Allow-Origin = %q, want *", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Headers"); got != "*" {
|
||||
t.Fatalf("Access-Control-Allow-Headers = %q, want *", got)
|
||||
}
|
||||
|
||||
preflight := httptest.NewRequest(http.MethodOptions, "/ping", nil)
|
||||
preflight.Header.Set("Origin", "https://crm.example.com")
|
||||
preflightRec := httptest.NewRecorder()
|
||||
router.ServeHTTP(preflightRec, preflight)
|
||||
|
||||
if preflightRec.Code != http.StatusNoContent {
|
||||
t.Fatalf("preflight status = %d, want %d", preflightRec.Code, http.StatusNoContent)
|
||||
}
|
||||
if got := preflightRec.Header().Get("Access-Control-Allow-Origin"); got != "*" {
|
||||
t.Fatalf("preflight Access-Control-Allow-Origin = %q, want *", got)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user