From 51b286dfe9237faea701604cd27c08a79a7ec0d9 Mon Sep 17 00:00:00 2001 From: jc <46619361+juancwu@users.noreply.github.com> Date: Sun, 17 Nov 2024 02:06:48 -0500 Subject: [PATCH] register request body in echo context --- internal/middleware/req_validator.go | 7 ++++++- internal/middleware/req_validator_test.go | 17 +++++++++++------ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/internal/middleware/req_validator.go b/internal/middleware/req_validator.go index feef71c..fe16cf2 100644 --- a/internal/middleware/req_validator.go +++ b/internal/middleware/req_validator.go @@ -10,13 +10,14 @@ import ( "github.com/rs/zerolog/log" ) +const REQUEST_BODY_KEY = "MIDDLEWARE_REQUEST_BODY" + // Struct solely exists to comply with Echo's interface to add a custom validator... type RequestBodyValidator struct { validator *validator.Validate } func (rv *RequestBodyValidator) Validate(i interface{}) error { - log.Info().Msgf("Validating struct: %+v\n", i) if err := rv.validator.Struct(i); err != nil { log.Error().Err(err).Msg("Validation error") return err @@ -48,6 +49,10 @@ func ValidateRequestBody(structType reflect.Type) echo.MiddlewareFunc { return err } + // allow the remaining handlers in the chain gain access to + // the request body. + c.Set(REQUEST_BODY_KEY, reqStruct.Interface()) + return next(c) } } diff --git a/internal/middleware/req_validator_test.go b/internal/middleware/req_validator_test.go index 9f232e2..b78d685 100644 --- a/internal/middleware/req_validator_test.go +++ b/internal/middleware/req_validator_test.go @@ -19,7 +19,16 @@ func TestRequestBodyValidator(t *testing.T) { e := echo.New() e.Validator = NewRequestBodyValidator() - e.POST("/", handler, ValidateRequestBody(reflect.TypeOf(testStruct{}))) + e.POST("/", func(c echo.Context) error { + // check that the request body is the correct interface + i, ok := c.Get(REQUEST_BODY_KEY).(*testStruct) + if !ok { + return echo.NewHTTPError(http.StatusInternalServerError) + } + + // echo back + return c.JSON(http.StatusOK, i) + }, ValidateRequestBody(reflect.TypeOf(testStruct{}))) tests := []struct { name string @@ -92,12 +101,8 @@ func TestRequestBodyValidator(t *testing.T) { rec := httptest.NewRecorder() e.ServeHTTP(rec, req) + t.Log(rec.Body.String()) assert.Equal(t, tc.expectedCode, rec.Code) }) } } - -// test handler -func handler(c echo.Context) error { - return c.String(http.StatusOK, "pass") -}