feat(db): connect to PostgreSQL and check it in /health/ready

This commit is contained in:
kk10
2026-10-03 12:36:05 +03:00
parent 60fad0fca7
commit 492e0be15c
6 changed files with 138 additions and 4 deletions
+9
View File
@@ -5,5 +5,14 @@ go 1.25.0
require (
github.com/go-chi/chi/v5 v5.3.2
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.11.0
github.com/joho/godotenv v1.5.1
)
require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
golang.org/x/sync v0.17.0 // indirect
golang.org/x/text v0.29.0 // indirect
)
+26
View File
@@ -1,6 +1,32 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+22 -1
View File
@@ -11,6 +11,7 @@ import (
"github.com/joho/godotenv"
"mtusi2026-messenger/internal/config"
"mtusi2026-messenger/internal/db"
"mtusi2026-messenger/internal/logger"
"mtusi2026-messenger/internal/service"
"mtusi2026-messenger/internal/store"
@@ -25,13 +26,33 @@ func Run() error {
log := logger.New(cfg.Logging.Level)
dbURL, err := cfg.Database.URL()
if err != nil {
log.Error("read database url", "error", err)
return err
}
pool, err := db.New(context.Background(), dbURL)
if err != nil {
log.Error("connect to database", "error", err)
return err
}
defer pool.Close()
memory := store.New()
userService := service.NewUserService(memory)
chatService := service.NewChatService(memory)
messageService := service.NewMessageService(memory)
router := NewRouter(log, cfg.Server.MaxInflightRequests, userService, chatService, messageService)
router := NewRouter(
log,
cfg.Server.MaxInflightRequests,
pool,
userService,
chatService,
messageService,
)
server := &http.Server{
Addr: cfg.Server.Host + ":" + cfg.Server.Port,
+4 -2
View File
@@ -14,12 +14,14 @@ import (
func NewRouter(
log *slog.Logger,
maxInflightRequests int,
db handler.Pinger,
userService *service.UserService,
chatService *service.ChatService,
messageService *service.MessageService,
) http.Handler {
router := chi.NewRouter()
healthHandler := handler.NewHealthHandler(log, db)
userHandler := handler.NewUserHandler(userService)
chatHandler := handler.NewChatHandler(chatService)
messageHandler := handler.NewMessageHandler(messageService)
@@ -28,8 +30,8 @@ func NewRouter(
router.Use(middleware.Logging(log))
router.Use(middleware.ConcurrencyLimit(maxInflightRequests))
router.Get("/health/live", handler.Health)
router.Get("/health/ready", handler.Health)
router.Get("/health/live", healthHandler.Live)
router.Get("/health/ready", healthHandler.Ready)
router.Post("/api/v1/users", userHandler.Create)
+34
View File
@@ -0,0 +1,34 @@
package db
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
func New(ctx context.Context, url string) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(url)
if err != nil {
return nil, fmt.Errorf("parse database url: %w", err)
}
cfg.MaxConns = 10
cfg.ConnConfig.ConnectTimeout = 5 * time.Second
cfg.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("create pool: %w", err)
}
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := pool.Ping(pingCtx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping database: %w", err)
}
return pool, nil
}
+43 -1
View File
@@ -1,13 +1,55 @@
package handler
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"time"
"mtusi2026-messenger/internal/dto"
)
func Health(w http.ResponseWriter, r *http.Request) {
const readyPingTimeout = 2 * time.Second
type Pinger interface {
Ping(ctx context.Context) error
}
type HealthHandler struct {
log *slog.Logger
db Pinger
}
func NewHealthHandler(log *slog.Logger, db Pinger) *HealthHandler {
return &HealthHandler{log: log, db: db}
}
func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(dto.HealthResponse{
Status: "ok",
})
}
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), readyPingTimeout)
defer cancel()
if err := h.db.Ping(ctx); err != nil {
h.log.ErrorContext(r.Context(), "readiness check failed", "error", err)
WriteError(
w,
http.StatusServiceUnavailable,
dto.ErrorCodeUnavailable,
"service unavailable",
w.Header().Get("X-Request-Id"),
)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)