From 4fbdfb6e4ab61c060ecd576316de92605dae147b Mon Sep 17 00:00:00 2001 From: Kharec Date: Sun, 23 Nov 2025 13:41:07 +0100 Subject: [PATCH] feat: add two helpers function to retrieve validated DTOs from request context and to apply validation middleware --- internal/handlers/common.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/internal/handlers/common.go b/internal/handlers/common.go index c587cea..f855ee1 100644 --- a/internal/handlers/common.go +++ b/internal/handlers/common.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "net/url" + "reflect" "strconv" "strings" "time" @@ -290,3 +291,24 @@ func HandleServiceError(w http.ResponseWriter, err error, defaultMsg string, def SendErrorResponse(w, defaultMsg, defaultCode) return false } + +func GetValidatedDTO[T any](r *http.Request) (*T, bool) { + dtoVal := middleware.GetValidatedDTOFromContext(r.Context()) + if dtoVal == nil { + return nil, false + } + dto, ok := dtoVal.(*T) + return dto, ok +} + +func WithValidation[T any](validationMiddleware func(http.Handler) http.Handler, handler http.HandlerFunc) http.HandlerFunc { + if validationMiddleware == nil { + return handler + } + var zero T + dtoType := reflect.TypeOf(zero) + return func(w http.ResponseWriter, r *http.Request) { + ctx := middleware.SetDTOTypeInContext(r.Context(), dtoType) + validationMiddleware(handler).ServeHTTP(w, r.WithContext(ctx)) + } +}