传递关键词缓存信息

This commit is contained in:
2026-04-10 21:29:12 +08:00
parent 1b88ca1efb
commit e3a6d18a8c
6 changed files with 42 additions and 6 deletions
+36
View File
@@ -98,6 +98,13 @@ func (c *urlKeywordsCache) Get(url string) ([]urlKeywordInfo, bool) {
return nil, false
}
// Stats 返回缓存统计信息
func (c *urlKeywordsCache) Stats() (size int, maxSize int) {
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.items), c.maxSize
}
// Server 是搜索 HTTP 服务器,同时内嵌收获服务(统一在同一端口)。
type Server struct {
db *storage.DB
@@ -209,6 +216,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("/admin/backlink", s.handleAdminBacklink)
mux.HandleFunc("/admin/crawl/status", s.handleAdminCrawlStatus)
mux.HandleFunc("/admin/url/keywords", s.handleUrlKeywords)
mux.HandleFunc("/admin/url/keywords/stats", s.handleUrlKeywordsStats)
// 静态文件(SPA fallback
mux.Handle("/", spaHandler{dist: "dist"})
return mux
@@ -847,6 +855,34 @@ func (s *Server) handleUrlKeywords(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(resp)
}
// handleUrlKeywordsStats 返回 URL 关键词缓存的统计信息
func (s *Server) handleUrlKeywordsStats(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if r.Method != http.MethodGet && r.Method != http.MethodOptions {
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
return
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
size, maxSize := s.urlKeywords.Stats()
resp := struct {
Size int `json:"size"` // 当前缓存的 URL 数量
MaxSize int `json:"max_size"` // 缓存容量上限
Usage float64 `json:"usage"` // 使用率 (0-1)
}{
Size: size,
MaxSize: maxSize,
Usage: float64(size) / float64(maxSize),
}
json.NewEncoder(w).Encode(resp)
}
// ---- 搜索处理器 ----
// searchResponse 是搜索 API 的 JSON 响应结构。