In a Handler
, the Response
is passed as a parameter:
Response
struct encapsulates all components of an HTTP response, providing a comprehensive API to construct and manipulate HTTP responsesres.status_code(200).body("Hello")
) for streamlined response building&mut self
, enabling handlers to conveniently construct and customize HTTP responses to meet various web service requirementsAfter the server receives a client request, any matched Handler
or middleware can write data to the Response
. In certain cases, such as when middleware wants to prevent subsequent middleware and Handler
execution, you can use FlowCtrl
:
Writing data to Response
is straightforward:
Writing plain text data
Writing JSON serialized data
If the render
method is called multiple times to write JSON data, these data fragments will not be merged into a single JSON object. Instead, they will be concatenated as independent text segments, 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 handled through custom logic.
Writing HTML
Use render
to write detailed error information to Response
.
If custom error messages are unnecessary, you can directly call set_http_code
.
render
method can write a redirect response to Response
, navigating to a new URL. When calling Redirect::found
, it sets the HTTP status code to 302 (Found), indicating a temporary redirect.
The body type returned by Response is ResBody
, an enum that is set to ResBody::Error
in case of errors. This contains error information for deferred error handling. Note that StatusError
does not implement Writer
, allowing you to customize display methods in Catcher
.
Category | Method | Description |
---|---|---|
Creation | new() / with_cookies() | Create new response |
Status Code | status_code() | Set status code |
Headers | headers()/headers_mut() | Get headers |
set_headers()/add_header() | Set/add headers | |
content_type() | Get content type | |
HTTP Version | version()/version_mut() | Get/modify HTTP version |
Response Body | body()/body_mut() | Set/get response body |
replace_body()/take_body() | Replace/extract response body | |
write_body() | Write data to response body | |
stream()/channel() | Streaming response/create send channel | |
Cookie Handling | cookies()/cookie() | Get cookies/specific cookie |
add_cookie()/remove_cookie() | Add/remove cookie | |
Content Response | render() | Render content |
stuff() | Set status code and render content | |
send_file() | Send file | |
Status Check | is_stamped() | Check if response is ready to be written back |