Интернет-магазин: Go, PostgreSQL 17 SSL, Caddy, Docker Compose

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
shop
2026-05-16 17:09:27 +03:00
commit 448cf2a465
21 changed files with 1208 additions and 0 deletions
+70
View File
@@ -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"}`))
}