Add body cache middleware to restore request body after Bind()#4
Open
elevasyncsolutions-jpg wants to merge 1 commit into
Open
Add body cache middleware to restore request body after Bind()#4elevasyncsolutions-jpg wants to merge 1 commit into
elevasyncsolutions-jpg wants to merge 1 commit into
Conversation
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()
5 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
When using
c.Bind(), echo consumes the request body stream. After binding,c.Request().Bodyreturns an empty stream, making it impossible to read the raw body for logging, validation signatures, or replay.Solution
Added a
BodyCacheMiddlewarethat reads the request body into a buffer before any handler runs, then replacesc.Request().Bodywith a reusableio.NopCloser. The cached body is stored in the echo context under the"cachedBody"key and can be retrieved viaGetCachedBody(c).Components
BodyCacheMiddleware: Drop-in echo middleware. Usage:e.Use(BodyCacheMiddleware)GetCachedBody(c echo.Context) ([]byte, bool): Retrieves cached body after Bind()main.godemonstrates body preserved after binding JSON to structTesting
Manual test via
go run main.go: binds JSON body to User struct, then reads cached raw body from context. Both are available.