Files
shop10/internal/handlers/home.go
T
shop a3d3721724 Добавить установщик, проверку версий и инструкцию деплоя на сервер.
Интерактивная настройка домена и БД, эндпоинты /health и /version,
скрипты install/check для Linux и Windows.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-16 17:17:19 +03:00

66 lines
1.4 KiB
Go

package handlers
import (
"html/template"
"log"
"net/http"
"shop/internal/models"
"shop/internal/repository"
)
type HomeHandler struct {
products *repository.ProductRepository
templates *template.Template
}
func NewHomeHandler(products *repository.ProductRepository, templates *template.Template) *HomeHandler {
return &HomeHandler{products: products, templates: templates}
}
type homePageData struct {
Title string
Products []models.Product
Categories []string
TotalItems int
}
func (h *HomeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
ctx := r.Context()
featured, err := h.products.Featured(ctx, 8)
if err != nil {
log.Printf("featured products: %v", err)
http.Error(w, "Ошибка загрузки каталога", http.StatusInternalServerError)
return
}
categories, err := h.products.Categories(ctx)
if err != nil {
log.Printf("categories: %v", err)
categories = nil
}
total, err := h.products.Count(ctx)
if err != nil {
log.Printf("count: %v", err)
total = 0
}
data := homePageData{
Title: "Главная",
Products: featured,
Categories: categories,
TotalItems: total,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := h.templates.ExecuteTemplate(w, "home.html", data); err != nil {
log.Printf("render home: %v", err)
}
}