package handler import ( "database/sql" "errors" "git.dmitriygnatenko.ru/dima/go-common/logger" "github.com/gofiber/fiber/v2" "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/mapper" ) const ( ArticleCacheKey = "article" maxArticlesCount = 3 articleParam = "article" ) func ArticleHandler( cacheService CacheService, articleRepository ArticleRepository, tagRepository TagRepository, ) fiber.Handler { return func(fctx *fiber.Ctx) error { ctx := fctx.Context() url := fctx.Params(articleParam) renderData, found := cacheService.Get(ArticleCacheKey + url) if !found { article, err := articleRepository.GetByURL(ctx, url) if err != nil { if errors.Is(err, sql.ErrNoRows) { return fiber.ErrNotFound } logger.Error(ctx, err.Error()) return err } if !article.IsActive { return fiber.ErrNotFound } articleDTO := mapper.ToArticleDTO(*article) // All used tags tags, err := tagRepository.GetAllUsed(ctx) if err != nil { logger.Error(ctx, err.Error()) return err } tagsDTO := mapper.ToTagDTOList(tags) // Last articles articles, err := articleRepository.GetAllPreview(ctx) if err != nil { logger.Error(ctx, err.Error()) return err } if len(articles) > maxArticlesCount { articles = articles[:maxArticlesCount] } renderData = fiber.Map{ "headTitle": "От слона к суслику - статьи про PHP, Go, алгоритмы", "headDescription": articleDTO.MetaDescription, "headKeywords": articleDTO.MetaKeywords, "pageTitle": "Статья
" + articleDTO.Title, "article": articleDTO, "sidebarArticles": mapper.ToArticlePreviewDTOList(articles), "sidebarTags": tagsDTO, } cacheService.Set(ArticleCacheKey+url, renderData, nil) } return fctx.Render("article", renderData, "_layout") } }