78 lines
2.6 KiB
Go
78 lines
2.6 KiB
Go
package rest
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gorilla/mux"
|
|
"github.com/igodwin/notifier/internal/auth"
|
|
"github.com/igodwin/notifier/internal/domain"
|
|
"github.com/igodwin/notifier/internal/logging"
|
|
)
|
|
|
|
// NewRouter creates a new HTTP router with all routes configured
|
|
func NewRouter(service domain.NotificationService, logger *logging.Logger) *mux.Router {
|
|
return NewRouterWithAuth(service, logger, nil)
|
|
}
|
|
|
|
// NewRouterWithAuth creates a new HTTP router with optional authentication
|
|
func NewRouterWithAuth(service domain.NotificationService, logger *logging.Logger, authStore *auth.APIKeyStore) *mux.Router {
|
|
handler := NewHandler(service, logger)
|
|
router := mux.NewRouter()
|
|
|
|
// API v1 routes
|
|
v1 := router.PathPrefix("/api/v1").Subrouter()
|
|
|
|
// Apply authentication middleware if auth store is provided
|
|
if authStore != nil {
|
|
authMiddleware := auth.NewRESTAuthMiddleware(authStore, logger)
|
|
v1.Use(authMiddleware.Middleware)
|
|
}
|
|
|
|
// Notification routes
|
|
v1.HandleFunc("/notifications", handler.SendNotification).Methods(http.MethodPost)
|
|
v1.HandleFunc("/notifications/batch", handler.SendBatchNotifications).Methods(http.MethodPost)
|
|
v1.HandleFunc("/notifications", handler.ListNotifications).Methods(http.MethodGet)
|
|
v1.HandleFunc("/notifications/{id}", handler.GetNotification).Methods(http.MethodGet)
|
|
v1.HandleFunc("/notifications/{id}", handler.CancelNotification).Methods(http.MethodDelete)
|
|
v1.HandleFunc("/notifications/{id}/retry", handler.RetryNotification).Methods(http.MethodPost)
|
|
|
|
// Stats route
|
|
v1.HandleFunc("/stats", handler.GetStats).Methods(http.MethodGet)
|
|
|
|
// Notifiers route
|
|
v1.HandleFunc("/notifiers", handler.GetNotifiers).Methods(http.MethodGet)
|
|
|
|
// Health check route (no auth required)
|
|
router.HandleFunc("/health", handler.HealthCheck).Methods(http.MethodGet)
|
|
|
|
// Middleware
|
|
router.Use(loggingMiddleware)
|
|
router.Use(corsMiddleware)
|
|
|
|
return router
|
|
}
|
|
|
|
// loggingMiddleware logs incoming requests
|
|
func loggingMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// You can add structured logging here
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
// corsMiddleware adds CORS headers
|
|
func corsMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
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.StatusOK)
|
|
return
|
|
}
|
|
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|