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.
This commit is contained in:
wood chen 2024-11-30 23:56:21 +08:00
parent 1b2fd3ea85
commit fd9c616aa2
2 changed files with 23 additions and 5 deletions

View File

@ -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) {

View File

@ -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)