fix: harden platform runtime and menu navigation

This commit is contained in:
david
2026-07-29 18:38:01 +08:00
parent fa21507a68
commit 5af729326c
7 changed files with 131 additions and 12 deletions

View 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()
}
}

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