ron-example/cmd/middleware.go

39 lines
990 B
Go

package main
import (
"context"
"log/slog"
"net/http"
"ron-pets/internal/sqlc"
)
func someMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
slog.Info("triggered middleware")
next.ServeHTTP(w, r)
})
}
func anotherMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
slog.Info("triggered another middleware")
next.ServeHTTP(w, r)
})
}
func UserSessionMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Simula la extracción de la sesión (en un caso real sería de cookies o tokens)
session := &sqlc.SessionData{
UserID: "12345",
Role: "admin",
}
// Almacena los datos de sesión en el contexto
ctx := context.WithValue(r.Context(), "session", session)
// Pasa el contexto actualizado al siguiente handler
next.ServeHTTP(w, r.WithContext(ctx))
})
}