Интернет-магазин: Go, PostgreSQL 17 SSL, Caddy, Docker Compose
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func Health(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"status":"ok"}`))
|
||||
}
|
||||
Reference in New Issue
Block a user