buhapp-backend/cmd/server/main.go
ga 4533ceaf2d Sprint 3: chat with WebSocket
- POST /api/v1/chats (ensure chat between users, normalized pair)
- GET  /api/v1/chats (list with last message + unread)
- GET  /api/v1/chats/:id/messages
- POST /api/v1/chats/:id/messages (send text/photo, push via WS)
- PUT  /api/v1/chats/:id/read (mark all read)
- PUT  /api/v1/messages/:msgId (edit, owner only)
- DELETE /api/v1/messages/:msgId (soft delete)
- POST /api/v1/blocks, DELETE /api/v1/blocks/:id
- POST /api/v1/reports
- WS   /ws?token= (real-time message push, ping/pong)
- migrations 0003: chats, messages, blocks, reports
2026-08-20 15:51:05 +00:00

166 lines
4.8 KiB
Go

package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/buhapp/backend/internal/audit"
"github.com/buhapp/backend/internal/auth"
"github.com/buhapp/backend/internal/chat"
"github.com/buhapp/backend/internal/config"
"github.com/buhapp/backend/internal/consent"
"github.com/buhapp/backend/internal/db"
"github.com/buhapp/backend/internal/handlers"
"github.com/buhapp/backend/internal/locations"
"github.com/buhapp/backend/internal/preferences"
"github.com/buhapp/backend/internal/redis"
"github.com/buhapp/backend/internal/storage"
"github.com/buhapp/backend/internal/users"
"github.com/buhapp/backend/internal/ws"
)
func main() {
cfg, err := config.Load()
if err != nil {
log.Fatalf("config: %v", err)
}
ctx := context.Background()
pg, err := db.New(ctx, cfg.PostgresDSN())
if err != nil {
log.Fatalf("postgres: %v", err)
}
defer pg.Close()
log.Println("postgres: connected")
migDir := os.Getenv("MIGRATIONS_DIR")
if migDir == "" {
migDir = "./migrations"
}
if err := db.RunMigrations(ctx, pg, migDir); err != nil {
log.Fatalf("migrations: %v", err)
}
rdb, err := redis.New(ctx, cfg.RedisAddr(), cfg.RedisPassword, cfg.RedisDB)
if err != nil {
log.Printf("redis warning: %v", err)
} else {
log.Println("redis: connected")
}
st, err := storage.New(ctx, cfg.MinIOEndpoint, cfg.MinIOAccessKey, cfg.MinIOSecretKey, cfg.MinIOBucket, cfg.MinIOUseSSL)
if err != nil {
log.Printf("minio warning: %v", err)
} else {
log.Println("minio: connected")
}
usersRepo := users.NewRepo(pg.Pool)
consentRepo := consent.NewRepo(pg.Pool)
auditRepo := audit.NewRepo(pg.Pool)
prefsRepo := preferences.NewRepo(pg.Pool)
locsRepo := locations.NewRepo(pg.Pool)
chatRepo := chat.NewRepo(pg.Pool)
authSvc := auth.NewService(cfg.JWTSecret, cfg.JwTAccessTTL(), cfg.JwtRefreshTTL())
hub := ws.NewHub()
authH := handlers.NewAuthHandler(cfg, usersRepo, consentRepo, auditRepo, authSvc)
h := handlers.New(cfg, usersRepo, prefsRepo, locsRepo, consentRepo, auditRepo, authSvc)
chatH := handlers.NewChatHandlers(chatRepo, auditRepo, hub)
_ = rdb
_ = st
app := fiber.New(fiber.Config{
AppName: "buhapp-api",
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
})
app.Use(recover.New())
app.Use(logger.New())
app.Use(cors.New(cors.Config{
AllowOrigins: "*",
AllowHeaders: "Origin, Content-Type, Accept, Authorization",
AllowMethods: "GET, POST, PUT, DELETE, OPTIONS",
}))
app.Get("/health", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{
"status": "ok",
"time": time.Now().UTC().Format(time.RFC3339),
"version": "0.3.0",
"db": pg.Pool != nil,
"redis": rdb != nil,
"storage": st != nil,
})
})
app.Get("/api/v1/legal/terms", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"version": cfg.TermsVersion, "url": "/legal/TERMS.md"})
})
app.Get("/api/v1/legal/privacy", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"version": cfg.PrivacyVersion, "url": "/legal/PRIVACY.md"})
})
app.Get("/api/v1/legal/disclaimer", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"version": cfg.DisclaimerVersion, "url": "/legal/DISCLAIMER.md"})
})
api := app.Group("/api/v1")
api.Post("/auth/register", authH.Register)
api.Post("/auth/login", authH.Login)
protected := api.Group("", auth.Middleware(authSvc))
protected.Get("/me", h.GetMe)
protected.Put("/me", h.UpdateMe)
protected.Get("/me/prefs", h.GetPrefs)
protected.Put("/me/prefs", h.UpdatePrefs)
protected.Put("/me/location", h.UpdateLocation)
protected.Put("/me/visibility", h.SetVisibility)
protected.Get("/search/nearby", h.SearchNearby)
protected.Get("/users/:id", h.GetUserPublic)
// Chat
protected.Post("/chats", chatH.EnsureChat)
protected.Get("/chats", chatH.ListChats)
protected.Get("/chats/:id/messages", chatH.ListMessages)
protected.Post("/chats/:id/messages", chatH.SendMessage)
protected.Put("/chats/:id/read", chatH.MarkRead)
protected.Put("/messages/:msgId", chatH.EditMessage)
protected.Delete("/messages/:msgId", chatH.DeleteMessage)
protected.Post("/blocks", chatH.Block)
protected.Delete("/blocks/:id", chatH.Unblock)
protected.Post("/reports", chatH.Report)
// WebSocket — авторизация по ?token=
app.Get("/ws", ws.AuthMiddleware(authSvc), ws.Upgrade, ws.Handler(hub))
go func() {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
<-sigCh
log.Println("shutdown...")
_ = app.ShutdownWithTimeout(10 * time.Second)
}()
addr := fmt.Sprintf(":%d", cfg.AppPort)
log.Printf("listening on %s", addr)
if err := app.Listen(addr); err != nil {
log.Fatalf("listen: %v", err)
}
}