Перевести API на PostgreSQL и сохраняемые Bearer-сессии

This commit is contained in:
Dima
2026-09-23 21:38:55 +03:00
parent a858d3325b
commit c3840181f1
22 changed files with 682 additions and 903 deletions
+41 -8
View File
@@ -6,6 +6,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
"github.com/jackc/pgx/v5/pgxpool"
"log"
"net"
"net/http"
@@ -75,6 +76,25 @@ func healthHandler(w http.ResponseWriter, r *http.Request) {
}
}
func readyHandler(db *pgxpool.Pool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
requestID := newRequestID()
w.Header().Set("X-Request-Id", requestID)
if r.Method != http.MethodGet {
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := db.Ping(ctx); err != nil {
writeError(w, 503, "unavailable", "database unavailable", requestID)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(healthResponse{"ok"})
}
}
func serverAddress() string {
host := os.Getenv("APP_HOST")
if host == "" {
@@ -90,27 +110,40 @@ func serverAddress() string {
}
func main() {
userStore := newUserStore()
chatStore := newChatStore()
messageStore := newMessageStore()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
db, err := openDatabase(ctx)
cancel()
if err != nil {
log.Fatalf("database initialization failed: %v", err)
}
defer db.Close()
userStore := newUserStore(db)
chatStore := newChatStore(db)
messageStore := newMessageStore(db)
sessions, err := newSessionStore(db)
if err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
mux.HandleFunc("/health/live", healthHandler)
mux.HandleFunc("/health/ready", healthHandler)
mux.HandleFunc("/health/ready", readyHandler(db))
mux.Handle("/api/v1/users", createUserHandler(userStore))
mux.Handle("/api/v1/users/me", currentUserHandler(userStore))
mux.Handle("/api/v1/auth/sessions", sessionHandler(userStore, sessions))
mux.Handle("/api/v1/auth/sessions/current", authRequired(sessions, logoutHandler(sessions)))
mux.Handle("/api/v1/users/me", authRequired(sessions, currentUserHandler(userStore)))
mux.Handle(
"/api/v1/chats",
chatCollectionHandler(userStore, chatStore),
authRequired(sessions, chatCollectionHandler(userStore, chatStore)),
)
mux.Handle(
"/api/v1/chats/",
chatSubresourceHandler(
authRequired(sessions, chatSubresourceHandler(
userStore,
chatStore,
messageStore,
),
)),
)
server := &http.Server{