package middleware import ( "context" "database/sql" "encoding/json" "log" "net/http" "time" ) // middlewareKey is a custom type for context keys to avoid collisions. type middlewareKey string // DbKey is the context key for the database connection. // Handlers use this to retrieve the *sql.DB from the request context. var DbKey middlewareKey = "db" // WithDB wraps a handler to inject the database into the request context. func WithDB(db *sql.DB) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := context.WithValue(r.Context(), DbKey, db) r = r.WithContext(ctx) next.ServeHTTP(w, r) }) } } // Logging returns a middleware that logs HTTP request details. func Logging(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() // Wrap the ResponseWriter to capture the status code wrapped := &statusResponseWriter{ResponseWriter: w, statusCode: http.StatusOK} next.ServeHTTP(wrapped, r) duration := time.Since(start) log.Printf("[%s] %s %s %d %v", r.Method, r.URL.Path, time.Now().Format("2006-01-02T15:04:05"), wrapped.statusCode, duration, ) }) } // CORS returns a middleware that adds CORS headers to all responses. func CORS(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") w.Header().Set("Access-Control-Max-Age", "86400") // Handle preflight OPTIONS requests if r.Method == "OPTIONS" { w.WriteHeader(http.StatusOK) return } next.ServeHTTP(w, r) }) } // WriteJSON writes a JSON response with the given status code. func WriteJSON(w http.ResponseWriter, status int, data interface{}) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) if err := json.NewEncoder(w).Encode(data); err != nil { log.Printf("error encoding JSON response: %v", err) } } // WriteError writes a JSON error response with the given status code. func WriteError(w http.ResponseWriter, status int, message string) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) json.NewEncoder(w).Encode(map[string]string{ "error": message, }) } // statusResponseWriter wraps http.ResponseWriter to capture the status code. type statusResponseWriter struct { http.ResponseWriter statusCode int } func (sw *statusResponseWriter) WriteHeader(code int) { sw.statusCode = code sw.ResponseWriter.WriteHeader(code) }