package handler import ( "net/http" "strconv" "spider/internal/model" "spider/internal/store" "github.com/gin-gonic/gin" ) // KeywordHandler handles unified keyword + seed CRUD. type KeywordHandler struct { store *store.Store } // List returns keywords with optional filters and pagination. // GET /keywords?page=1&page_size=20&industry_tag= func (h *KeywordHandler) List(c *gin.Context) { page, pageSize, offset := parsePage(c) industryTag := c.Query("industry_tag") query := h.store.DB.Model(&model.Keyword{}) if industryTag != "" { query = query.Where("industry_tag = ?", industryTag) } var total int64 query.Count(&total) var keywords []model.Keyword if err := query.Order("id DESC").Limit(pageSize).Offset(offset).Find(&keywords).Error; err != nil { Fail(c, 500, err.Error()) return } PageOK(c, keywords, total, page, pageSize) } // Create creates one or more keywords in batch. // POST /keywords body: {keywords:["k1","k2"], industry_tag:"机场"} func (h *KeywordHandler) Create(c *gin.Context) { var body struct { Keywords []string `json:"keywords" binding:"required,min=1"` IndustryTag string `json:"industry_tag"` } if err := c.ShouldBindJSON(&body); err != nil { Fail(c, http.StatusBadRequest, err.Error()) return } var created []model.Keyword for _, kw := range body.Keywords { if kw == "" { continue } k := model.Keyword{ Keyword: kw, IndustryTag: body.IndustryTag, Enabled: true, } if err := h.store.DB.Where(model.Keyword{Keyword: kw}).FirstOrCreate(&k).Error; err != nil { Fail(c, 500, err.Error()) return } created = append(created, k) } OK(c, created) } // Update modifies a keyword. // PUT /keywords/:id func (h *KeywordHandler) Update(c *gin.Context) { id, err := strconv.ParseUint(c.Param("id"), 10, 64) if err != nil { Fail(c, http.StatusBadRequest, "invalid id") return } var body struct { Keyword string `json:"keyword"` IndustryTag string `json:"industry_tag"` Enabled *bool `json:"enabled"` } if err := c.ShouldBindJSON(&body); err != nil { Fail(c, http.StatusBadRequest, err.Error()) return } var kw model.Keyword if err := h.store.DB.First(&kw, id).Error; err != nil { Fail(c, 404, "keyword not found") return } updates := map[string]any{} if body.Keyword != "" { updates["keyword"] = body.Keyword } if body.IndustryTag != "" { updates["industry_tag"] = body.IndustryTag } if body.Enabled != nil { updates["enabled"] = *body.Enabled } if err := h.store.DB.Model(&kw).Updates(updates).Error; err != nil { Fail(c, 500, err.Error()) return } h.store.DB.First(&kw, id) OK(c, kw) } // Delete removes a keyword by ID. // DELETE /keywords/:id func (h *KeywordHandler) Delete(c *gin.Context) { id, err := strconv.ParseUint(c.Param("id"), 10, 64) if err != nil { Fail(c, http.StatusBadRequest, "invalid id") return } if err := h.store.DB.Delete(&model.Keyword{}, id).Error; err != nil { Fail(c, 500, err.Error()) return } OK(c, nil) }