channel.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package handler
  2. import (
  3. "spider/internal/model"
  4. "github.com/gin-gonic/gin"
  5. "gorm.io/gorm"
  6. )
  7. // ChannelHandler handles channel queries.
  8. type ChannelHandler struct {
  9. db *gorm.DB
  10. }
  11. // List returns channels with optional filters and pagination.
  12. // GET /channels?status=&source=&page=&page_size=
  13. func (h *ChannelHandler) List(c *gin.Context) {
  14. page, pageSize, offset := parsePage(c)
  15. query := h.db.Model(&model.Channel{})
  16. if status := c.Query("status"); status != "" {
  17. query = query.Where("status = ?", status)
  18. }
  19. if source := c.Query("source"); source != "" {
  20. query = query.Where("source = ?", source)
  21. }
  22. var total int64
  23. if err := query.Count(&total).Error; err != nil {
  24. Fail(c, 500, err.Error())
  25. return
  26. }
  27. var items []model.Channel
  28. if err := query.Order("id DESC").Limit(pageSize).Offset(offset).Find(&items).Error; err != nil {
  29. Fail(c, 500, err.Error())
  30. return
  31. }
  32. PageOK(c, items, total, page, pageSize)
  33. }
  34. // Stats returns channel counts grouped by status and source.
  35. // GET /channels/stats
  36. func (h *ChannelHandler) Stats(c *gin.Context) {
  37. var statusRows []struct {
  38. Status string `json:"status"`
  39. Cnt int64 `json:"count"`
  40. }
  41. h.db.Model(&model.Channel{}).
  42. Select("status, count(*) as cnt").
  43. Group("status").
  44. Scan(&statusRows)
  45. byStatus := map[string]int64{}
  46. for _, r := range statusRows {
  47. byStatus[r.Status] = r.Cnt
  48. }
  49. var sourceRows []struct {
  50. Source string `json:"source"`
  51. Cnt int64 `json:"count"`
  52. }
  53. h.db.Model(&model.Channel{}).
  54. Select("source, count(*) as cnt").
  55. Group("source").
  56. Scan(&sourceRows)
  57. bySource := map[string]int64{}
  58. for _, r := range sourceRows {
  59. bySource[r.Source] = r.Cnt
  60. }
  61. var total int64
  62. h.db.Model(&model.Channel{}).Count(&total)
  63. OK(c, gin.H{
  64. "total": total,
  65. "by_status": byStatus,
  66. "by_source": bySource,
  67. })
  68. }