1
0
mirror of https://github.com/kataras/iris.git synced 2026-01-10 13:35:59 +00:00

Add new x/errors/validation package to make your life even more easier (using Generics)

This commit is contained in:
Gerasimos (Makis) Maropoulos
2024-01-07 15:08:03 +02:00
parent 8f2deb6873
commit 104bea0a58
14 changed files with 443 additions and 282 deletions

View File

@@ -115,6 +115,12 @@ type ResponseOnlyErrorFunc[T any] interface {
func(stdContext.Context, T) error
}
// ContextValidator is an interface which can be implemented by a request payload struct
// in order to validate the context before calling a service function.
type ContextValidator interface {
ValidateContext(*context.Context) error
}
func bindResponse[T, R any, F ResponseFunc[T, R]](ctx *context.Context, fn F, fnInput ...T) (R, bool) {
var req T
switch len(fnInput) {
@@ -131,6 +137,16 @@ func bindResponse[T, R any, F ResponseFunc[T, R]](ctx *context.Context, fn F, fn
panic("invalid number of arguments")
}
if contextValidator, ok := any(&req).(ContextValidator); ok {
err := contextValidator.ValidateContext(ctx)
if err != nil {
if HandleError(ctx, err) {
var resp R
return resp, false
}
}
}
resp, err := fn(ctx, req)
return resp, !HandleError(ctx, err)
}
@@ -208,14 +224,7 @@ func ReadPayload[T any](ctx *context.Context) (T, bool) {
return payload, false
}
if !handleJSONError(ctx, err) {
if vErrs, ok := AsValidationErrors(err); ok {
InvalidArgument.Data(ctx, "validation failure", vErrs)
} else {
InvalidArgument.Details(ctx, "unable to parse body", err.Error())
}
}
HandleError(ctx, err)
return payload, false
}
@@ -229,11 +238,7 @@ func ReadQuery[T any](ctx *context.Context) (T, bool) {
var payload T
err := ctx.ReadQuery(&payload)
if err != nil {
if vErrs, ok := AsValidationErrors(err); ok {
InvalidArgument.Data(ctx, "validation failure", vErrs)
} else {
InvalidArgument.Details(ctx, "unable to parse query", err.Error())
}
HandleError(ctx, err)
return payload, false
}