46 lines
1.2 KiB
Go
46 lines
1.2 KiB
Go
package router
|
|
|
|
import (
|
|
"log/slog"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/CubeCraft-Creations/Extrudex/backend/internal/config"
|
|
"github.com/CubeCraft-Creations/Extrudex/backend/internal/handlers"
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/go-chi/chi/v5/middleware"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// New creates and configures a Chi router with all middleware and handlers mounted.
|
|
func New(cfg *config.Config, dbPool *pgxpool.Pool) chi.Router {
|
|
r := chi.NewRouter()
|
|
|
|
// Middleware
|
|
r.Use(middleware.RequestID)
|
|
r.Use(middleware.RealIP)
|
|
r.Use(middleware.Logger)
|
|
r.Use(middleware.Recoverer)
|
|
r.Use(middleware.Timeout(60 * time.Second))
|
|
|
|
// CORS
|
|
r.Use(func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Access-Control-Allow-Origin", cfg.CorsOrigin)
|
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
|
if r.Method == http.MethodOptions {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
})
|
|
|
|
// Health check
|
|
healthHandler := handlers.NewHealthHandler(dbPool)
|
|
r.Get("/health", healthHandler.ServeHTTP)
|
|
|
|
return r
|
|
}
|