* chore: add VS Code extension recommendations * Update image URLs in README and documentation files * chore: disable no-inline-html rule * chore: use standard md/mdx syntax, and use .jsx for react components * chore: fix email links in Code of Conduct The commit message suggests fixing the email links in the Code of Conduct file to use the correct `mailto:` syntax. * chore: update actix-web error helper links Update the links to the `actix-web` error helper traits in the `databases.md` and `errors.md` files to use the correct URLs. * chore: restore unused actix-web error helper links * Update src/pages/community/coc.md Co-authored-by: Rob Ede <robjtede@icloud.com> * Update docs/getting-started.md Co-authored-by: Rob Ede <robjtede@icloud.com> --------- Co-authored-by: Rob Ede <robjtede@icloud.com>
2.4 KiB
title |
---|
Responses |
import CodeBlock from "@site/src/components/code_block";
Response
A builder-like pattern is used to construct an instance of HttpResponse
. HttpResponse
provides several methods that return a HttpResponseBuilder
instance, which implements various convenience methods for building responses.
Check the documentation for type descriptions.
The methods .body
, .finish
, and .json
finalize response creation and return a constructed HttpResponse instance. If this methods is called on the same builder instance multiple times, the builder will panic.
JSON Response
The Json
type allows to respond with well-formed JSON data: simply return a value of type Json<T>
where T
is the type of a structure to serialize into JSON. The type T
must implement the Serialize
trait from serde.
For the following example to work, you need to add serde
to your dependencies in Cargo.toml
:
[dependencies]
serde = { version = "1.0", features = ["derive"] }
Using the Json
type this way instead of calling the .json
method on a HttpResponse
makes it immediately clear that the function returns JSON and not any other type of response.
Content encoding
Actix Web can automatically compress payloads with the Compress middleware. The following codecs are supported:
- Brotli
- Gzip
- Deflate
- Identity
A response's Content-Encoding
header defaults to ContentEncoding::Auto
, which performs automatic content compression negotiation based on the request's Accept-Encoding
header.
Explicitly disable content compression on a handler by setting Content-Encoding
to an Identity
value:
When dealing with an already compressed body (for example, when serving pre-compressed assets), set the Content-Encoding
header on the response manually to bypass the middleware: