Fix: Add CORS support for management API OPTIONS requests

This commit is contained in:
DullJZ
2025-11-05 01:20:49 +08:00
parent dbd566059b
commit c7e984aac2
2 changed files with 6 additions and 4 deletions

View File

@@ -137,8 +137,9 @@ func main() {
log.Println("Management API enabled")
adminHandler := api.NewAdminHandler(bucketManager, lb, cfg)
// 创建子路由器并应用Token认证中间件
// 创建子路由器并应用中间件
apiRouter := router.PathPrefix("/api").Subrouter()
apiRouter.Use(corsMiddleware) // 先应用 CORS 中间件,处理 OPTIONS 预检请求
apiRouter.Use(middleware.TokenAuthMiddleware(cfg.API.Token))
adminHandler.RegisterRoutes(apiRouter)

View File

@@ -73,9 +73,10 @@ type HealthResponse struct {
// RegisterRoutes 注册管理API路由
// 注意: router 参数应该是已经带有 /api 前缀的子路由器
func (h *AdminHandler) RegisterRoutes(router *mux.Router) {
router.HandleFunc("/buckets", h.ListBuckets).Methods(http.MethodGet)
router.HandleFunc("/buckets/{name}", h.GetBucketDetail).Methods(http.MethodGet)
router.HandleFunc("/health", h.GetHealth).Methods(http.MethodGet)
// 注册路由,同时支持 OPTIONS 方法用于 CORS 预检
router.HandleFunc("/buckets", h.ListBuckets).Methods(http.MethodGet, http.MethodOptions)
router.HandleFunc("/buckets/{name}", h.GetBucketDetail).Methods(http.MethodGet, http.MethodOptions)
router.HandleFunc("/health", h.GetHealth).Methods(http.MethodGet, http.MethodOptions)
}
// ListBuckets 获取存储桶列表