From eda8d39ee77ffd9019f0aca351ac2ad3e9ec458f Mon Sep 17 00:00:00 2001 From: EwenQuim Date: Thu, 26 Dec 2024 00:32:33 +0100 Subject: [PATCH] Transform and Validate Gin input --- deserialization.go | 53 +++++++++++++++------------------------ extra/fuegogin/context.go | 7 ++++-- 2 files changed, 25 insertions(+), 35 deletions(-) diff --git a/deserialization.go b/deserialization.go index 30e1520a..1f4c8b25 100644 --- a/deserialization.go +++ b/deserialization.go @@ -104,21 +104,7 @@ func read[B any](context context.Context, dec decoder) (B, error) { } slog.Debug("Decoded body", "body", body) - body, err = transform(context, body) - if err != nil { - return body, BadRequestError{ - Title: "Transformation Failed", - Err: err, - Detail: "cannot transform request body: " + err.Error(), - } - } - - err = validate(body) - if err != nil { - return body, err - } - - return body, nil + return TransformAndValidate(context, body) } // ReadString reads the request body as string. @@ -199,24 +185,7 @@ func readURLEncoded[B any](r *http.Request, options readOptions) (B, error) { } slog.Debug("Decoded body", "body", body) - body, err = transform(r.Context(), body) - if err != nil { - return body, BadRequestError{ - Title: "Transformation Failed", - Detail: "cannot transform x-www-form-urlencoded request body: " + err.Error(), - Err: err, - Errors: []ErrorItem{ - {Name: "transformation", Reason: "transformation failed"}, - }, - } - } - - err = validate(body) - if err != nil { - return body, fmt.Errorf("cannot validate request body: %w", err) - } - - return body, nil + return TransformAndValidate(r.Context(), body) } // transforms the input if possible. @@ -225,8 +194,12 @@ func transform[B any](ctx context.Context, body B) (B, error) { err := inTransformerBody.InTransform(ctx) if err != nil { return body, BadRequestError{ + Title: "Transformation Failed", Err: err, Detail: "cannot transform request body: " + err.Error(), + Errors: []ErrorItem{ + {Name: "transformation", Reason: "transformation failed"}, + }, } } body = *any(inTransformerBody).(*B) @@ -236,3 +209,17 @@ func transform[B any](ctx context.Context, body B) (B, error) { return body, nil } + +func TransformAndValidate[B any](context context.Context, body B) (B, error) { + body, err := transform(context, body) + if err != nil { + return body, err + } + + err = validate(body) + if err != nil { + return body, err + } + + return body, nil +} diff --git a/extra/fuegogin/context.go b/extra/fuegogin/context.go index 7cdaa57d..933a03aa 100644 --- a/extra/fuegogin/context.go +++ b/extra/fuegogin/context.go @@ -23,8 +23,11 @@ var ( func (c ginContext[B]) Body() (B, error) { var body B - err := c.ginCtx.BindJSON(&body) - return body, err + err := c.ginCtx.Bind(&body) + if err != nil { + return body, err + } + return fuego.TransformAndValidate(c, body) } func (c ginContext[B]) Context() context.Context {