Files
lab/go/projects/lyra/internal/handler/test.go
T
labmem 759bc3fc35 feat(lyra)!: 接入 Redis 并添加缓存连通性实验
- 封装缓存读写、JSON 编解码、过期时间与操作超时
- 集中组装 Redis 依赖,在测试接口验证分类缓存读写
- 更新依赖并移除原 handler 测试

BREAKING CHANGE: 配置节由 redis 改为 cache,新增 db 和 timeout 配置项
2026-10-19 23:12:49 +08:00

70 lines
1.9 KiB
Go

package handler
import (
"fmt"
"log/slog"
"lyra/internal/api"
"lyra/internal/cache"
"lyra/internal/httpx"
"lyra/internal/model"
"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 {
slog.ErrorContext(ctx.Request.Context(), "缓存分类列表失败")
return
}
testResult, _, err := h.cache.Get[[]*model.Category](ctx.Request.Context(), "test:categories")
if err != nil {
slog.ErrorContext(ctx.Request.Context(), "获取缓存分类列表失败")
}
if len(testResult) == 0 {
slog.ErrorContext(ctx.Request.Context(), "缓存分类列表为空")
} else {
for _, v := range testResult {
fmt.Printf("%+v\n", v)
}
}
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
}