- 配置 slog JSON 输出和日志级别 - 添加请求 ID、访问日志及上下文日志工具 - 拆分启动初始化并统一启动失败处理 BREAKING CHANGE: 配置文件必须提供 log.level,缺失或非法将导致启动失败
70 lines
1.9 KiB
Go
70 lines
1.9 KiB
Go
package handler
|
|
|
|
import (
|
|
"fmt"
|
|
"lyra/internal/api"
|
|
"lyra/internal/cache"
|
|
"lyra/internal/httpx"
|
|
"lyra/internal/model"
|
|
"lyra/internal/util"
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type TestHandler struct {
|
|
categoryModel model.CategoryModel
|
|
cache *cache.Cache
|
|
}
|
|
|
|
func NewTestHandler(categoryModel model.CategoryModel, cache *cache.Cache) *TestHandler {
|
|
return &TestHandler{categoryModel: categoryModel, cache: cache}
|
|
}
|
|
|
|
func (h *TestHandler) Hello() gin.HandlerFunc {
|
|
return func(ctx *gin.Context) {
|
|
categories, err := h.categoryModel.FindAll(ctx.Request.Context())
|
|
if err != nil {
|
|
httpx.Fail(ctx, http.StatusInternalServerError, api.CodeInternalError, "获取分类列表失败")
|
|
return
|
|
}
|
|
if err := h.cache.Set(ctx.Request.Context(), cache.Entry[[]*model.Category]{
|
|
Key: "test:categories",
|
|
Value: categories,
|
|
TTL: 5 * time.Minute,
|
|
}); err != nil {
|
|
util.Logger(ctx.Request.Context()).Error("设置缓存分类列表失败")
|
|
return
|
|
}
|
|
testResult, _, err := h.cache.Get[[]*model.Category](ctx.Request.Context(), "test:categories")
|
|
if err != nil {
|
|
util.Logger(ctx.Request.Context()).Error("获取缓存分类列表失败")
|
|
}
|
|
if len(testResult) == 0 {
|
|
util.Logger(ctx.Request.Context()).Error("缓存分类列表为空")
|
|
} else {
|
|
for _, v := range testResult {
|
|
fmt.Printf("%+v\n", v)
|
|
}
|
|
}
|
|
util.Logger(ctx.Request.Context()).Info("success")
|
|
httpx.OK(ctx, 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
|
|
}
|