forked from mtusi2026/mtusi2026lab2
Implement lab2 messenger API with PostgreSQL Redis and Docker
This commit is contained in:
@@ -0,0 +1,191 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/handler"
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
func main() {
|
||||
databaseURL := os.Getenv("DATABASE_URL")
|
||||
if databaseURL == "" {
|
||||
log.Fatal("DATABASE_URL is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
pool, err := storage.NewPostgresPool(ctx, databaseURL)
|
||||
if err != nil {
|
||||
log.Fatalf("PostgreSQL connection failed: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
if err := storage.ApplyMigrations(ctx, pool); err != nil {
|
||||
log.Fatalf("database migrations failed: %v", err)
|
||||
}
|
||||
log.Println("database migrations applied")
|
||||
|
||||
var cache *storage.SessionCache
|
||||
|
||||
redisURL := os.Getenv("REDIS_URL")
|
||||
if redisURL != "" {
|
||||
cache, err = storage.NewSessionCache(redisURL)
|
||||
if err != nil {
|
||||
log.Printf("Redis configuration error: %v", err)
|
||||
} else {
|
||||
defer cache.Close()
|
||||
|
||||
pingCtx, pingCancel := context.WithTimeout(
|
||||
context.Background(), 2*time.Second,
|
||||
)
|
||||
pingErr := cache.Ping(pingCtx)
|
||||
pingCancel()
|
||||
|
||||
if pingErr != nil {
|
||||
log.Printf("Redis unavailable, PostgreSQL fallback: %v", pingErr)
|
||||
} else {
|
||||
log.Println("Redis connected")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
authStore := storage.NewAuthStore(pool)
|
||||
sessionService := storage.NewSessionService(authStore, cache)
|
||||
chatStore := storage.NewChatStore(pool)
|
||||
messageStore := storage.NewMessageStore(pool)
|
||||
|
||||
userHandler := handler.NewUserHandler(authStore)
|
||||
sessionHandler := handler.NewSessionHandler(authStore, sessionService)
|
||||
chatHandler := handler.NewChatHandler(chatStore)
|
||||
messageHandler := handler.NewMessageHandler(chatStore, messageStore)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
mux.HandleFunc("GET /health/live", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeHealthOK(w)
|
||||
})
|
||||
|
||||
mux.HandleFunc("GET /health/ready", func(w http.ResponseWriter, r *http.Request) {
|
||||
pingCtx, pingCancel := context.WithTimeout(
|
||||
r.Context(), 2*time.Second,
|
||||
)
|
||||
defer pingCancel()
|
||||
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"error": map[string]string{
|
||||
"code": "unavailable",
|
||||
"message": "database unavailable",
|
||||
"request_id": middleware.GetRequestID(r.Context()),
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
writeHealthOK(w)
|
||||
})
|
||||
|
||||
// Public routes.
|
||||
mux.HandleFunc("POST /api/v1/users", userHandler.Create)
|
||||
mux.HandleFunc("POST /api/v1/auth/sessions", sessionHandler.Create)
|
||||
|
||||
// Protected routes.
|
||||
auth := middleware.Auth(sessionService)
|
||||
|
||||
mux.Handle(
|
||||
"DELETE /api/v1/auth/sessions/current",
|
||||
auth(http.HandlerFunc(sessionHandler.Delete)),
|
||||
)
|
||||
mux.Handle(
|
||||
"GET /api/v1/users/me",
|
||||
auth(http.HandlerFunc(userHandler.Me)),
|
||||
)
|
||||
mux.Handle(
|
||||
"POST /api/v1/chats",
|
||||
auth(http.HandlerFunc(chatHandler.Create)),
|
||||
)
|
||||
mux.Handle(
|
||||
"GET /api/v1/chats",
|
||||
auth(http.HandlerFunc(chatHandler.List)),
|
||||
)
|
||||
mux.Handle(
|
||||
"GET /api/v1/chats/{chat_id}",
|
||||
auth(http.HandlerFunc(chatHandler.Get)),
|
||||
)
|
||||
mux.Handle(
|
||||
"POST /api/v1/chats/{chat_id}/messages",
|
||||
auth(http.HandlerFunc(messageHandler.Create)),
|
||||
)
|
||||
mux.Handle(
|
||||
"GET /api/v1/chats/{chat_id}/messages",
|
||||
auth(http.HandlerFunc(messageHandler.List)),
|
||||
)
|
||||
|
||||
host := os.Getenv("APP_HOST")
|
||||
if host == "" {
|
||||
host = "0.0.0.0"
|
||||
}
|
||||
|
||||
port := os.Getenv("APP_PORT")
|
||||
if port == "" {
|
||||
port = "8080"
|
||||
}
|
||||
|
||||
server := &http.Server{
|
||||
Addr: host + ":" + port,
|
||||
Handler: middleware.RequestID(mux),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
|
||||
defer signal.Stop(stop)
|
||||
|
||||
go func() {
|
||||
log.Printf("server started on %s", server.Addr)
|
||||
|
||||
if err := server.ListenAndServe(); err != nil &&
|
||||
!errors.Is(err, http.ErrServerClosed) {
|
||||
log.Printf("server error: %v", err)
|
||||
stop <- syscall.SIGTERM
|
||||
}
|
||||
}()
|
||||
|
||||
sig := <-stop
|
||||
log.Printf("shutdown signal received: %s", sig)
|
||||
|
||||
shutdownCtx, shutdownCancel := context.WithTimeout(
|
||||
context.Background(), 8*time.Second,
|
||||
)
|
||||
defer shutdownCancel()
|
||||
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
log.Printf("graceful shutdown failed: %v", err)
|
||||
_ = server.Close()
|
||||
}
|
||||
|
||||
log.Println("server stopped")
|
||||
}
|
||||
|
||||
func writeHealthOK(w http.ResponseWriter) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"status":"ok"}`))
|
||||
}
|
||||
Reference in New Issue
Block a user