fix: harden platform runtime and menu navigation
This commit is contained in:
27
backend/api/internal/middleware/cors.go
Normal file
27
backend/api/internal/middleware/cors.go
Normal file
@@ -0,0 +1,27 @@
|
||||
// Package middleware 定义平台 API 自有的 HTTP 中间件。
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
allowedHeaders = "Origin, Content-Length, Content-Type, Workspace, Request-Id, Authorization, Token"
|
||||
allowedMethods = "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS"
|
||||
)
|
||||
|
||||
// Cors 允许平台前端跨域调用 API,包括状态更新使用的 PATCH 方法。
|
||||
func Cors() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
ctx.Header("Access-Control-Allow-Origin", "*")
|
||||
ctx.Header("Access-Control-Allow-Headers", allowedHeaders)
|
||||
ctx.Header("Access-Control-Allow-Methods", allowedMethods)
|
||||
if ctx.Request.Method == http.MethodOptions {
|
||||
ctx.AbortWithStatus(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
||||
32
backend/api/internal/middleware/cors_test.go
Normal file
32
backend/api/internal/middleware/cors_test.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestCorsAllowsPatchPreflight(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
engine := gin.New()
|
||||
engine.Use(Cors())
|
||||
engine.PATCH("/resource/:identity/status", func(ctx *gin.Context) {
|
||||
ctx.Status(http.StatusNoContent)
|
||||
})
|
||||
|
||||
request := httptest.NewRequest(http.MethodOptions, "/resource/example/status", nil)
|
||||
request.Header.Set("Origin", "http://localhost:5173")
|
||||
request.Header.Set("Access-Control-Request-Method", http.MethodPatch)
|
||||
recorder := httptest.NewRecorder()
|
||||
engine.ServeHTTP(recorder, request)
|
||||
|
||||
if recorder.Code != http.StatusNoContent {
|
||||
t.Fatalf("preflight status = %d, want %d", recorder.Code, http.StatusNoContent)
|
||||
}
|
||||
if methods := recorder.Header().Get("Access-Control-Allow-Methods"); !strings.Contains(methods, http.MethodPatch) {
|
||||
t.Fatalf("allowed methods %q do not include PATCH", methods)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user