Skip to content

Add body cache middleware to restore request body after Bind()#4

Open
elevasyncsolutions-jpg wants to merge 1 commit into
RoseMark45:mainfrom
elevasyncsolutions-jpg:main
Open

Add body cache middleware to restore request body after Bind()#4
elevasyncsolutions-jpg wants to merge 1 commit into
RoseMark45:mainfrom
elevasyncsolutions-jpg:main

Conversation

@elevasyncsolutions-jpg

Copy link
Copy Markdown

Problem

When using c.Bind(), echo consumes the request body stream. After binding, c.Request().Body returns an empty stream, making it impossible to read the raw body for logging, validation signatures, or replay.

Solution

Added a BodyCacheMiddleware that reads the request body into a buffer before any handler runs, then replaces c.Request().Body with a reusable io.NopCloser. The cached body is stored in the echo context under the "cachedBody" key and can be retrieved via GetCachedBody(c).

Components

  • BodyCacheMiddleware: Drop-in echo middleware. Usage: e.Use(BodyCacheMiddleware)
  • GetCachedBody(c echo.Context) ([]byte, bool): Retrieves cached body after Bind()
  • Example in main.go demonstrates body preserved after binding JSON to struct

Testing

Manual test via go run main.go: binds JSON body to User struct, then reads cached raw body from context. Both are available.

When echo's c.Bind() consumes the request body, subsequent reads from
c.Request().Body return empty. This middleware reads the body before
binding and caches it, making it available via GetCachedBody() after
Bind() has been called.

Key components:
- BodyCacheMiddleware: echo middleware that reads and caches body
- WrapBody: helper to make request.Body re-readable
- GetCachedBody: retrieves the cached body bytes
- Example usage demonstrating body preservation after Bind()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant