Skip to content

Commit

Permalink
register request body in echo context
Browse files Browse the repository at this point in the history
  • Loading branch information
juancwu committed Nov 17, 2024
1 parent ebd2843 commit 51b286d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
7 changes: 6 additions & 1 deletion internal/middleware/req_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
}
Expand Down
17 changes: 11 additions & 6 deletions internal/middleware/req_validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
}

0 comments on commit 51b286d

Please sign in to comment.