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
Json<T> renders one complete JSON document. In Salvo 0.94 and later, rendering Json replaces any body bytes already buffered on the Response instead of appending to them. To emit multiple JSON records, serialize each record yourself and append it with write_body, for example when producing NDJSON.
-
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.