Files
mtusi2026lab2/internal/httpapi/postgres.go
T

81 lines
2.2 KiB
Go

package httpapi
import (
"context"
"net/http"
"strings"
"sync/atomic"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
)
func NewPostgresHandler(db *store.PostgresStore, stopping *atomic.Bool, ttl int64) (http.Handler, error) {
registration := service.NewRegistration(db)
sessions, err := service.NewSessions(db, registration, ttl)
if err != nil {
return nil, err
}
chats := &persistentAPI{messenger: service.NewPersistentMessenger(db)}
return withRequestID(withAccessLog(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if stopping.Load() && r.URL.Path != "/health/live" {
writeAppError(w, store.ErrUnavailable)
return
}
if r.URL.Path == "/api/v1/chats" || strings.HasPrefix(r.URL.Path, "/api/v1/chats/") {
token, err := bearerToken(r)
if err != nil {
sessionError(w, err, false)
return
}
user, err := sessions.CurrentUser(r.Context(), token)
if err != nil {
sessionError(w, err, false)
return
}
ctx := context.WithValue(r.Context(), userContextKey{}, user)
chats.chatRoutes(w, r.WithContext(ctx))
return
}
switch r.URL.Path {
case "/api/v1/auth/sessions":
loginSession(w, r, sessions)
case "/api/v1/auth/sessions/current":
currentSession(w, r, sessions, true)
case "/api/v1/users/me":
currentSession(w, r, sessions, false)
case "/health/live":
handleHealth(w, r)
case "/health/ready":
if !requireMethod(w, r, http.MethodGet) {
return
}
if err := db.Ping(r.Context()); err != nil {
writeAppError(w, err)
return
}
handleHealth(w, r)
case "/api/v1/users":
if !requireMethod(w, r, http.MethodPost) {
return
}
var body struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
if !readJSON(w, r, &body, "username", "display_name", "password") {
return
}
user, err := registration.Register(r.Context(), body.Username, body.DisplayName, body.Password)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusCreated, user)
default:
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
}
}))), nil
}