feat: simplify SOP to immediate-effect configuration

This commit is contained in:
Eric 1549169735@qq.com
2026-08-18 16:27:02 +08:00
parent c5ab886b70
commit 8de48fb05e
150 changed files with 6764 additions and 1626 deletions

View File

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

View File

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