Интернет-магазин: 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
+48
View File
@@ -0,0 +1,48 @@
package config
import (
"fmt"
"os"
"strconv"
"time"
)
type Config struct {
HTTPAddr string
DatabaseURL string
ReadTimeout time.Duration
WriteTimeout time.Duration
}
func Load() (Config, error) {
port := env("APP_PORT", "8080")
cfg := Config{
HTTPAddr: ":" + port,
DatabaseURL: os.Getenv("DATABASE_URL"),
ReadTimeout: durationEnv("HTTP_READ_TIMEOUT", 10*time.Second),
WriteTimeout: durationEnv("HTTP_WRITE_TIMEOUT", 30*time.Second),
}
if cfg.DatabaseURL == "" {
return cfg, fmt.Errorf("DATABASE_URL is required")
}
return cfg, nil
}
func env(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
func durationEnv(key string, fallback time.Duration) time.Duration {
v := os.Getenv(key)
if v == "" {
return fallback
}
sec, err := strconv.Atoi(v)
if err != nil || sec <= 0 {
return fallback
}
return time.Duration(sec) * time.Second
}
+36
View File
@@ -0,0 +1,36 @@
package database
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
func Connect(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(databaseURL)
if err != nil {
return nil, fmt.Errorf("parse database url: %w", err)
}
cfg.MaxConns = 10
cfg.MinConns = 2
cfg.MaxConnLifetime = time.Hour
cfg.HealthCheckPeriod = 30 * time.Second
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("create pool: %w", err)
}
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping database: %w", err)
}
return pool, nil
}
+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"}`))
}
+11
View File
@@ -0,0 +1,11 @@
package models
type Product struct {
ID int
Name string
Description string
Price float64
ImageURL string
Category string
Featured bool
}
+65
View File
@@ -0,0 +1,65 @@
package repository
import (
"context"
"github.com/jackc/pgx/v5/pgxpool"
"shop/internal/models"
)
type ProductRepository struct {
pool *pgxpool.Pool
}
func NewProductRepository(pool *pgxpool.Pool) *ProductRepository {
return &ProductRepository{pool: pool}
}
func (r *ProductRepository) Featured(ctx context.Context, limit int) ([]models.Product, error) {
rows, err := r.pool.Query(ctx, `
SELECT id, name, description, price, image_url, category, featured
FROM products
WHERE featured = true
ORDER BY id
LIMIT $1`, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []models.Product
for rows.Next() {
var p models.Product
if err := rows.Scan(&p.ID, &p.Name, &p.Description, &p.Price, &p.ImageURL, &p.Category, &p.Featured); err != nil {
return nil, err
}
items = append(items, p)
}
return items, rows.Err()
}
func (r *ProductRepository) Categories(ctx context.Context) ([]string, error) {
rows, err := r.pool.Query(ctx, `
SELECT DISTINCT category FROM products ORDER BY category`)
if err != nil {
return nil, err
}
defer rows.Close()
var cats []string
for rows.Next() {
var c string
if err := rows.Scan(&c); err != nil {
return nil, err
}
cats = append(cats, c)
}
return cats, rows.Err()
}
func (r *ProductRepository) Count(ctx context.Context) (int, error) {
var n int
err := r.pool.QueryRow(ctx, `SELECT COUNT(*) FROM products`).Scan(&n)
return n, err
}
+9
View File
@@ -0,0 +1,9 @@
package web
import "embed"
//go:embed templates/*
var TemplatesFS embed.FS
//go:embed static/*
var StaticFS embed.FS
+399
View File
@@ -0,0 +1,399 @@
:root {
--bg: #0f0f12;
--bg-elevated: #1a1a21;
--surface: #23232d;
--text: #f4f4f6;
--text-muted: #9b9bab;
--accent: #e8c547;
--accent-hover: #f5d76a;
--border: rgba(255, 255, 255, 0.08);
--radius: 14px;
--shadow: 0 24px 48px rgba(0, 0, 0, 0.45);
--font: "DM Sans", system-ui, sans-serif;
--font-display: "Instrument Serif", Georgia, serif;
}
*,
*::before,
*::after {
box-sizing: border-box;
}
html {
scroll-behavior: smooth;
}
body {
margin: 0;
font-family: var(--font);
background: var(--bg);
color: var(--text);
line-height: 1.6;
min-height: 100vh;
}
.container {
width: min(1120px, 92vw);
margin-inline: auto;
}
a {
color: inherit;
text-decoration: none;
}
/* Header */
.site-header {
position: sticky;
top: 0;
z-index: 100;
backdrop-filter: blur(12px);
background: rgba(15, 15, 18, 0.85);
border-bottom: 1px solid var(--border);
}
.header-inner {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1.5rem;
padding: 1rem 0;
}
.logo {
font-family: var(--font-display);
font-size: 1.5rem;
font-weight: 400;
letter-spacing: -0.02em;
}
.logo span {
color: var(--accent);
}
.nav {
display: flex;
gap: 1.75rem;
}
.nav-link {
font-size: 0.95rem;
color: var(--text-muted);
transition: color 0.2s;
}
.nav-link:hover,
.nav-link.active {
color: var(--text);
}
.header-actions {
display: flex;
gap: 0.75rem;
}
/* Buttons */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.55rem 1.1rem;
font-family: inherit;
font-size: 0.9rem;
font-weight: 500;
border-radius: 999px;
border: none;
cursor: pointer;
transition: background 0.2s, transform 0.15s;
}
.btn:active {
transform: scale(0.98);
}
.btn-primary {
background: var(--accent);
color: #1a1508;
}
.btn-primary:hover {
background: var(--accent-hover);
}
.btn-ghost {
background: transparent;
color: var(--text);
border: 1px solid var(--border);
}
.btn-ghost:hover {
background: var(--surface);
}
.btn-lg {
padding: 0.85rem 1.5rem;
font-size: 1rem;
}
.btn-sm {
padding: 0.4rem 0.85rem;
font-size: 0.82rem;
}
/* Hero */
.hero {
padding: 4rem 0 5rem;
background:
radial-gradient(ellipse 80% 60% at 70% 20%, rgba(232, 197, 71, 0.12), transparent),
var(--bg);
}
.hero-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 3rem;
align-items: center;
}
.eyebrow {
text-transform: uppercase;
letter-spacing: 0.14em;
font-size: 0.75rem;
color: var(--accent);
margin: 0 0 1rem;
}
.hero-title {
font-family: var(--font-display);
font-size: clamp(2.5rem, 5vw, 3.75rem);
font-weight: 400;
line-height: 1.1;
margin: 0 0 1.25rem;
}
.hero-title em {
font-style: italic;
color: var(--accent);
}
.hero-lead {
color: var(--text-muted);
font-size: 1.1rem;
max-width: 28ch;
margin: 0 0 2rem;
}
.hero-cta {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.hero-visual {
position: relative;
min-height: 320px;
}
.hero-card {
position: absolute;
border-radius: var(--radius);
box-shadow: var(--shadow);
}
.hero-card-a {
inset: 10% 20% 25% 0;
background: linear-gradient(145deg, #3d3d4a, #23232d);
border: 1px solid var(--border);
}
.hero-card-b {
inset: 35% 0 0 25%;
background: linear-gradient(145deg, rgba(232, 197, 71, 0.35), #2a2820);
border: 1px solid rgba(232, 197, 71, 0.25);
}
/* Sections */
.section {
padding: 4rem 0;
}
.section-title {
font-family: var(--font-display);
font-size: 2rem;
font-weight: 400;
margin: 0 0 0.5rem;
}
.section-sub {
color: var(--text-muted);
margin: 0 0 2rem;
}
.section-head {
margin-bottom: 2rem;
}
/* Categories */
.category-list {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
list-style: none;
padding: 0;
margin: 0;
}
.category-chip {
display: inline-block;
padding: 0.5rem 1rem;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 999px;
font-size: 0.9rem;
transition: border-color 0.2s, background 0.2s;
}
.category-chip:hover {
border-color: var(--accent);
background: var(--bg-elevated);
}
/* Products */
.product-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 1.5rem;
}
.product-card {
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: var(--radius);
overflow: hidden;
transition: transform 0.25s, box-shadow 0.25s;
}
.product-card:hover {
transform: translateY(-4px);
box-shadow: var(--shadow);
}
.product-image {
aspect-ratio: 4 / 3;
background-size: cover;
background-position: center;
background-color: var(--surface);
}
.product-body {
padding: 1.25rem;
}
.product-category {
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--accent);
}
.product-name {
font-size: 1.1rem;
margin: 0.35rem 0 0.5rem;
}
.product-desc {
font-size: 0.88rem;
color: var(--text-muted);
margin: 0 0 1rem;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.product-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
}
.product-price {
font-weight: 600;
font-size: 1.05rem;
}
.empty-state {
text-align: center;
color: var(--text-muted);
padding: 3rem;
background: var(--bg-elevated);
border-radius: var(--radius);
border: 1px dashed var(--border);
}
/* Features */
.features {
background: var(--bg-elevated);
border-block: 1px solid var(--border);
}
.features-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 2rem;
}
.feature h3 {
margin: 0 0 0.5rem;
font-size: 1.1rem;
}
.feature p {
margin: 0;
color: var(--text-muted);
font-size: 0.95rem;
}
/* Footer */
.site-footer {
padding: 2.5rem 0;
border-top: 1px solid var(--border);
}
.footer-inner {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 1rem;
}
.footer-brand {
font-family: var(--font-display);
font-size: 1.25rem;
margin: 0;
}
.footer-copy {
margin: 0;
color: var(--text-muted);
font-size: 0.9rem;
}
@media (max-width: 768px) {
.nav {
display: none;
}
.hero-grid {
grid-template-columns: 1fr;
}
.hero-visual {
min-height: 200px;
}
.features-grid {
grid-template-columns: 1fr;
}
}
+82
View File
@@ -0,0 +1,82 @@
{{define "home.html"}}
{{template "layout" .}}
{{end}}
{{define "content"}}
<section class="hero">
<div class="container hero-grid">
<div class="hero-copy">
<p class="eyebrow">Новая коллекция 2026</p>
<h1 class="hero-title">Стиль, который<br><em>остаётся с вами</em></h1>
<p class="hero-lead">Качественные товары с быстрой доставкой. В каталоге уже {{.TotalItems}} позиций.</p>
<div class="hero-cta">
<a href="#catalog" class="btn btn-primary btn-lg">Смотреть каталог</a>
<a href="#categories" class="btn btn-ghost btn-lg">Категории</a>
</div>
</div>
<div class="hero-visual" aria-hidden="true">
<div class="hero-card hero-card-a"></div>
<div class="hero-card hero-card-b"></div>
</div>
</div>
</section>
{{if .Categories}}
<section id="categories" class="section categories">
<div class="container">
<h2 class="section-title">Категории</h2>
<ul class="category-list">
{{range .Categories}}
<li><a href="#catalog" class="category-chip">{{.}}</a></li>
{{end}}
</ul>
</div>
</section>
{{end}}
<section id="catalog" class="section catalog">
<div class="container">
<div class="section-head">
<h2 class="section-title">Популярные товары</h2>
<p class="section-sub">Избранное из нашего ассортимента</p>
</div>
{{if .Products}}
<div class="product-grid">
{{range .Products}}
<article class="product-card">
<div class="product-image" style="background-image: url('{{.ImageURL}}')"></div>
<div class="product-body">
<span class="product-category">{{.Category}}</span>
<h3 class="product-name">{{.Name}}</h3>
<p class="product-desc">{{.Description}}</p>
<div class="product-footer">
<span class="product-price">{{formatPrice .Price}}</span>
<button type="button" class="btn btn-primary btn-sm">В корзину</button>
</div>
</div>
</article>
{{end}}
</div>
{{else}}
<p class="empty-state">Товары скоро появятся. Проверьте подключение к базе данных.</p>
{{end}}
</div>
</section>
<section class="section features">
<div class="container features-grid">
<div class="feature">
<h3>Быстрая доставка</h3>
<p>Отправка в день заказа по всей России.</p>
</div>
<div class="feature">
<h3>Гарантия качества</h3>
<p>14 дней на возврат без лишних вопросов.</p>
</div>
<div class="feature">
<h3>Безопасная оплата</h3>
<p>Шифрование данных и защищённые платежи.</p>
</div>
</div>
</section>
{{end}}
+39
View File
@@ -0,0 +1,39 @@
{{define "layout"}}
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{.Title}} — ShopNova</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700;1,9..40,400&family=Instrument+Serif:ital@0;1&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<header class="site-header">
<div class="container header-inner">
<a href="/" class="logo">Shop<span>Nova</span></a>
<nav class="nav">
<a href="/" class="nav-link active">Главная</a>
<a href="#catalog" class="nav-link">Каталог</a>
<a href="#categories" class="nav-link">Категории</a>
</nav>
<div class="header-actions">
<button type="button" class="btn btn-ghost" aria-label="Поиск">Поиск</button>
<button type="button" class="btn btn-primary">Корзина</button>
</div>
</div>
</header>
<main>
{{template "content" .}}
</main>
<footer class="site-footer">
<div class="container footer-inner">
<p class="footer-brand">ShopNova</p>
<p class="footer-copy">© 2026 Интернет-магазин. Go + PostgreSQL + Caddy.</p>
</div>
</footer>
</body>
</html>
{{end}}