| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- package handler
- import (
- "net/http"
- "strconv"
- "spider/internal/model"
- "github.com/gin-gonic/gin"
- "gorm.io/gorm"
- )
- // SeedHandler handles managed seed CRUD.
- type SeedHandler struct {
- db *gorm.DB
- }
- // List returns seeds with optional status filter and pagination.
- // GET /seeds?page=1&page_size=20&status=active
- func (h *SeedHandler) List(c *gin.Context) {
- page, pageSize, offset := parsePage(c)
- query := h.db.Model(&model.ManagedSeed{})
- if status := c.Query("status"); status != "" {
- query = query.Where("status = ?", status)
- }
- var total int64
- if err := query.Count(&total).Error; err != nil {
- Fail(c, 500, err.Error())
- return
- }
- var seeds []model.ManagedSeed
- if err := query.Order("id DESC").Limit(pageSize).Offset(offset).Find(&seeds).Error; err != nil {
- Fail(c, 500, err.Error())
- return
- }
- PageOK(c, seeds, total, page, pageSize)
- }
- // Create creates a new seed.
- // POST /seeds body: {channel_name, note}
- func (h *SeedHandler) Create(c *gin.Context) {
- var body struct {
- ChannelName string `json:"channel_name" binding:"required"`
- Note string `json:"note"`
- }
- if err := c.ShouldBindJSON(&body); err != nil {
- Fail(c, http.StatusBadRequest, err.Error())
- return
- }
- seed := model.ManagedSeed{
- ChannelName: body.ChannelName,
- Note: body.Note,
- Status: "active",
- }
- if err := h.db.Create(&seed).Error; err != nil {
- Fail(c, 500, err.Error())
- return
- }
- OK(c, seed)
- }
- // Update modifies a seed's status and/or note.
- // PUT /seeds/:id body: {status, note}
- func (h *SeedHandler) 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 {
- Status string `json:"status"`
- Note string `json:"note"`
- }
- if err := c.ShouldBindJSON(&body); err != nil {
- Fail(c, http.StatusBadRequest, err.Error())
- return
- }
- var seed model.ManagedSeed
- if err := h.db.First(&seed, id).Error; err != nil {
- Fail(c, 404, "seed not found")
- return
- }
- updates := map[string]interface{}{}
- if body.Status != "" {
- updates["status"] = body.Status
- }
- updates["note"] = body.Note
- if err := h.db.Model(&seed).Updates(updates).Error; err != nil {
- Fail(c, 500, err.Error())
- return
- }
- h.db.First(&seed, id)
- OK(c, seed)
- }
- // Delete removes a seed by ID.
- // DELETE /seeds/:id
- func (h *SeedHandler) 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.db.Delete(&model.ManagedSeed{}, id).Error; err != nil {
- Fail(c, 500, err.Error())
- return
- }
- OK(c, nil)
- }
|