Adding UseFinal Middleware to Ensure Consistent HTTP Response Management #101
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.
We have a situation where the Before middleware is returning an HTTP response.
Additionally, in the same service, we have an After middleware that we use to manage a metric of HTTP response status codes.
The current design does not support this case because the middleware chain is interrupted since the Before middleware returned an HTTP response, and we could not call
ctx.next
in this case.In our implementation, we initially assumed that the after middleware would always be called.
For this case, and many others, we believe it is important to add middleware that will be called just before sending the HTTP response, without relying on what happened in the before, view, or after stages.
We decided not to use the existing middleware interface because it does not make sense for logic that runs at this stage to return an error since we did not want to change the
ctx.Response
based on these functions.These functions should have logic that is separate from the existing logic for handling the request.
To solve the issue of HTTP responses being returned by Before middleware, we propose defining a new middleware method called
UseFinal
.Any logic added to this middleware will be executed regardless of what happened in the before, view, or after stages, and will be called just before sending the HTTP response.
This approach will allow us to properly manage HTTP response status codes in all scenarios, without relying on the behavior of other middleware in the chain.
We believe this is a clean and effective solution that will improve the maintainability and scalability of our codebase.