How to Modify Request Parameters through Middleware
Before learning how to modify request parameters, please first understand some details about request parameter input: Request 🔥
Custom Parameter Overriding
The simplest way to modify request parameters is to override client-submitted parameters through custom parameters. Since custom parameters have the highest priority in parameter parsing, when fully retrieving request parameters (not through specific submission methods), custom parameters will override parameters submitted by other methods. This method of modification is common, especially when using standard routing, where parameters are received as a struct
object, and the underlying layer retrieves all parameters and then converts them to a struct
object.
However, if the user obtains parameters through r.GetQuery, r.GetForm
, custom parameter overriding will be ineffective. Methods like r.Get
or r.GetRequest
for parameter retrieval can also achieve parameter overriding effects.
Modifying Parameters for Specific Request Methods
It’s also possible to modify the original parameters in middleware by altering r.URL.RawQuery
or r.Body
, but after modification, it’s necessary to call r.ReloadParams()
to indicate that the request parameters will need to be re-parsed in the next retrieval.
Precautions for Modifying Request Body through Middleware
A common issue when modifying r.Body
through middleware is that r.Body
can only be read once, and subsequent reads will not retrieve the data, which is by the design of the standard library http.Request
. In the GoFrame
framework’s ghttp.Request
object, continuous reading of the Body
content is allowed using the framework’s ghttp.Request
GetBody
, GetBodyString
methods.
However, if you directly read r.Body
using the standard library’s http.Request
object within middleware, it is recommended to reassign r.Body
or wrap and reassign it using io.NopCloser
to facilitate further reading of Body
content by subsequent middleware or processes.