Response
In a Handler, the Response is passed as a parameter:
- The
Responsestruct encapsulates all components of an HTTP response, providing a comprehensive API for constructing and manipulating HTTP responses. - It supports a fluent, chainable style (e.g.,
res.status_code(200).body("Hello")), facilitating the smooth construction of responses. - Core functionalities include:
- Setting status codes and headers
- Manipulating the response body (supporting strings, bytes, files, and streaming data)
- Managing Cookies
- Multiple content rendering methods
- This struct employs a mutable reference pattern, returning a reference to itself via
&mut self, allowing handlers to conveniently build and customize HTTP responses to meet various web service requirements.
After the server receives a client request, any matched Handler or middleware can write data into the Response. In certain scenarios, such as when a middleware wishes to prevent the execution of subsequent middleware and Handlers, you can use FlowCtrl:
Writing Content
Writing data to a Response is straightforward:
-
Writing plain text data
-
Writing JSON serialized data
If the render method is called multiple times to write JSON data, these pieces of data will not be merged into a single JSON object. Instead, they will be concatenated sequentially as independent text fragments, potentially resulting in invalid JSON format. If multiple data items need to be returned, they should be combined into a single object before serialization, or the logic should be handled manually.
-
Writing HTML
Writing HTTP Errors
-
Using
renderallows writing detailed error information to theResponse. -
If custom error information is not needed, you can directly call
set_http_code.
Redirecting to Another URL
- Using the
rendermethod, you can write a redirect response to theResponse, navigating to a new URL. When you callRedirect::found, it sets the HTTP status code to 302 (Found), indicating a temporary redirect.
ResBody
The Body type returned by Response is ResBody, which is an enum. In case of an error, it is set to ResBody::Error, containing error information for deferred error handling. Notably, StatusError does not implement Writer; this design allows you to customize its display in the Catcher.