Files
mtusi2026lab2/internal/api/server.go
T

87 lines
1.9 KiB
Go

package api
import (
"context"
"log/slog"
"net/http"
"sync/atomic"
"time"
"messenger/internal/store"
)
type ctxKey struct{}
type API struct {
store *store.Store
log *slog.Logger
shutting atomic.Bool
}
// Создает Api
func New(st *store.Store, log *slog.Logger) *API {
if log == nil {
log = slog.Default()
}
return &API{
store: st,
log: log,
}
}
// BeginShutdown переводит /health/ready в 503 и говорит новым бизнес-запросам
// отказать до закрытия слушателя. Уже принятые обработчики дорабатывают.
func (a *API) BeginShutdown() {
a.shutting.Store(true)
a.log.Info("shutdown started")
}
// Точка входа
func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) {
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
start := time.Now()
id := requestID(r)
sw.Header().Set("X-Request-Id", id)
r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, id))
defer func() {
if p := recover(); p != nil {
a.log.Error("panic", "request_id", id)
if !sw.wrote {
a.fail(sw, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
}
}
a.log.Info("request",
"request_id", id,
"method", r.Method,
"path", r.URL.Path,
"status", sw.status,
"duration_ms", time.Since(start).Milliseconds(),
"bytes_in", r.ContentLength,
)
}()
switch {
case r.Method == http.MethodGet && r.URL.Path == "/health/live":
a.live(sw, r)
return
case r.Method == http.MethodGet && r.URL.Path == "/health/ready":
a.ready(sw, r)
return
}
if a.shutting.Load() {
a.fail(sw, r, http.StatusServiceUnavailable, "unavailable", "Сервер останавливается", 1)
return
}
a.route(sw, r)
}
func requestIDFrom(r *http.Request) string {
id, _ := r.Context().Value(ctxKey{}).(string)
if id == "" {
return "unknown"
}
return id
}