- 使用 Squirrel 与 sqlx 实现分类查询 - 集中组装依赖并向 handler 注入 model 接口 - 显式转换分类响应 DTO,统一空列表输出 - 补充路由与 handler 测试,同步架构文档 BREAKING CHANGE: 将 GET /hello 替换为 GET /test,响应由问候字符串改为分类列表
44 lines
1.1 KiB
Go
44 lines
1.1 KiB
Go
package handler
|
|
|
|
import (
|
|
"lyra/internal/api"
|
|
"lyra/internal/httpx"
|
|
"lyra/internal/model"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type TestHandler struct {
|
|
categoryModel model.CategoryModel
|
|
}
|
|
|
|
func NewTestHandler(categoryModel model.CategoryModel) *TestHandler {
|
|
return &TestHandler{categoryModel: categoryModel}
|
|
}
|
|
|
|
func (h *TestHandler) Hello() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
categories, err := h.categoryModel.FindAll(c.Request.Context())
|
|
if err != nil {
|
|
httpx.Fail(c, http.StatusInternalServerError, api.CodeInternalError, "获取分类列表失败")
|
|
return
|
|
}
|
|
httpx.OK(c, toCategoryResponses(categories))
|
|
}
|
|
}
|
|
|
|
// toCategoryResponses 显式把内部模型转换为响应 DTO;make 保证空结果输出 data:[] 而非 null。
|
|
func toCategoryResponses(categories []*model.Category) []api.CategoryResponse {
|
|
responses := make([]api.CategoryResponse, 0, len(categories))
|
|
for _, category := range categories {
|
|
responses = append(responses, api.CategoryResponse{
|
|
ID: category.ID,
|
|
Slug: category.Slug,
|
|
Title: category.Title,
|
|
Sort: category.Sort,
|
|
})
|
|
}
|
|
return responses
|
|
}
|