| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- package handler
- import (
- "spider/internal/model"
- "github.com/gin-gonic/gin"
- "gorm.io/gorm"
- )
- // ChannelHandler handles channel queries.
- type ChannelHandler struct {
- db *gorm.DB
- }
- // List returns channels with optional filters and pagination.
- // GET /channels?status=&source=&page=&page_size=
- func (h *ChannelHandler) List(c *gin.Context) {
- page, pageSize, offset := parsePage(c)
- query := h.db.Model(&model.Channel{})
- if status := c.Query("status"); status != "" {
- query = query.Where("status = ?", status)
- }
- if source := c.Query("source"); source != "" {
- query = query.Where("source = ?", source)
- }
- var total int64
- if err := query.Count(&total).Error; err != nil {
- Fail(c, 500, err.Error())
- return
- }
- var items []model.Channel
- if err := query.Order("id DESC").Limit(pageSize).Offset(offset).Find(&items).Error; err != nil {
- Fail(c, 500, err.Error())
- return
- }
- PageOK(c, items, total, page, pageSize)
- }
- // Stats returns channel counts grouped by status and source.
- // GET /channels/stats
- func (h *ChannelHandler) Stats(c *gin.Context) {
- var statusRows []struct {
- Status string `json:"status"`
- Cnt int64 `json:"count"`
- }
- h.db.Model(&model.Channel{}).
- Select("status, count(*) as cnt").
- Group("status").
- Scan(&statusRows)
- byStatus := map[string]int64{}
- for _, r := range statusRows {
- byStatus[r.Status] = r.Cnt
- }
- var sourceRows []struct {
- Source string `json:"source"`
- Cnt int64 `json:"count"`
- }
- h.db.Model(&model.Channel{}).
- Select("source, count(*) as cnt").
- Group("source").
- Scan(&sourceRows)
- bySource := map[string]int64{}
- for _, r := range sourceRows {
- bySource[r.Source] = r.Cnt
- }
- var total int64
- h.db.Model(&model.Channel{}).Count(&total)
- OK(c, gin.H{
- "total": total,
- "by_status": byStatus,
- "by_source": bySource,
- })
- }
|