Add stats API handler and fix CORS support

This commit is contained in:
DullJZ
2025-11-06 18:21:28 +08:00
parent 291c327477
commit dfd38e592e
2 changed files with 9 additions and 5 deletions
+4 -1
View File
@@ -136,11 +136,14 @@ func main() {
if cfg.API.Enabled { if cfg.API.Enabled {
log.Println("Management API enabled") log.Println("Management API enabled")
adminHandler := api.NewAdminHandler(bucketManager, lb, cfg, configManager) adminHandler := api.NewAdminHandler(bucketManager, lb, cfg, configManager)
statsHandler := api.NewStatsHandler(storageService)
// 创建子路由器并应用Token认证中间件 // 创建子路由器并应用中间件
apiRouter := router.PathPrefix("/api").Subrouter() apiRouter := router.PathPrefix("/api").Subrouter()
apiRouter.Use(corsMiddleware) // 先应用 CORS 中间件,处理 OPTIONS 预检请求
apiRouter.Use(middleware.TokenAuthMiddleware(cfg.API.Token)) apiRouter.Use(middleware.TokenAuthMiddleware(cfg.API.Token))
adminHandler.RegisterRoutes(apiRouter) adminHandler.RegisterRoutes(apiRouter)
statsHandler.RegisterRoutes(apiRouter)
log.Printf("Management API endpoints available at /api/*") log.Printf("Management API endpoints available at /api/*")
} }
+5 -4
View File
@@ -25,10 +25,11 @@ func NewStatsHandler(storage *storage.Service) *StatsHandler {
// RegisterRoutes 注册统计API路由 // RegisterRoutes 注册统计API路由
func (h *StatsHandler) RegisterRoutes(router *mux.Router) { func (h *StatsHandler) RegisterRoutes(router *mux.Router) {
router.HandleFunc("/api/stats/monthly", h.GetCurrentMonthStats).Methods("GET") // 注意: router 参数应该是已经带有 /api 前缀的子路由器
router.HandleFunc("/api/stats/monthly/{year}/{month}", h.GetMonthlyStats).Methods("GET") router.HandleFunc("/stats/monthly", h.GetCurrentMonthStats).Methods(http.MethodGet, http.MethodOptions)
router.HandleFunc("/api/stats/monthly/range", h.GetMonthlyStatsRange).Methods("GET") router.HandleFunc("/stats/monthly/{year}/{month}", h.GetMonthlyStats).Methods(http.MethodGet, http.MethodOptions)
router.HandleFunc("/api/stats/bucket/{bucket}/history", h.GetBucketHistory).Methods("GET") router.HandleFunc("/stats/monthly/range", h.GetMonthlyStatsRange).Methods(http.MethodGet, http.MethodOptions)
router.HandleFunc("/stats/bucket/{bucket}/history", h.GetBucketHistory).Methods(http.MethodGet, http.MethodOptions)
} }
// MonthlyStatsResponse 月度统计响应 // MonthlyStatsResponse 月度统计响应