From fd9c616aa23d2e34880cc44bbad1ab0d988d4b6c Mon Sep 17 00:00:00 2001 From: wood chen Date: Sat, 30 Nov 2024 23:56:21 +0800 Subject: [PATCH] feat(main, handlers): initialize random number generator and enhance URL stats response format - Added initialization of a random number generator in main.go to support future features. - Refactored HandleURLStats in handlers.go to return URL statistics in a structured format, improving API response clarity and usability. --- handlers/handlers.go | 23 ++++++++++++++++++----- main.go | 5 +++++ 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/handlers/handlers.go b/handlers/handlers.go index 5f72f2e..4daed9d 100644 --- a/handlers/handlers.go +++ b/handlers/handlers.go @@ -144,12 +144,25 @@ func (h *Handlers) HandleStats(w http.ResponseWriter, r *http.Request) { func (h *Handlers) HandleURLStats(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") - services.Mu.RLock() - response := map[string]interface{}{ - "paths": services.CSVPathsCache, + stats := services.GetURLCounts() + + // 转换为前端期望的格式 + response := make(map[string]struct { + TotalURLs int `json:"total_urls"` + }) + + for endpoint, stat := range stats { + response[endpoint] = struct { + TotalURLs int `json:"total_urls"` + }{ + TotalURLs: stat.TotalURLs, + } + } + + if err := json.NewEncoder(w).Encode(response); err != nil { + http.Error(w, "Error encoding response", http.StatusInternalServerError) + return } - services.Mu.RUnlock() - json.NewEncoder(w).Encode(response) } func (h *Handlers) HandleMetrics(w http.ResponseWriter, r *http.Request) { diff --git a/main.go b/main.go index 0c223da..04348a3 100644 --- a/main.go +++ b/main.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "log" + "math/rand" "net/http" "os" "os/signal" @@ -35,6 +36,10 @@ func (a *App) Initialize() error { return err } + // 初始化随机数生成器 + source := rand.NewSource(time.Now().UnixNano()) + config.InitRNG(rand.New(source)) + // 然后创建必要的目录 if err := os.MkdirAll(config.Get().Storage.DataDir, 0755); err != nil { return fmt.Errorf("failed to create data directory: %w", err)