feat: add two helpers function to retrieve validated DTOs from request context and to apply validation middleware
This commit is contained in:
@@ -6,6 +6,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"reflect"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -290,3 +291,24 @@ func HandleServiceError(w http.ResponseWriter, err error, defaultMsg string, def
|
|||||||
SendErrorResponse(w, defaultMsg, defaultCode)
|
SendErrorResponse(w, defaultMsg, defaultCode)
|
||||||
return false
|
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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user