1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-25 00:12:59 +01:00
actix-extras/guide/src/qs_7.md

61 lines
1.7 KiB
Markdown
Raw Normal View History

2017-12-02 20:41:20 +01:00
# HttpRequest & HttpResponse
## Content encoding
Actix automatically *compress*/*decompress* payload.
2017-12-04 05:09:46 +01:00
Following codecs are supported:
2017-12-02 20:41:20 +01:00
* Brotli
* Gzip
* Deflate
* Identity
If request headers contains `Content-Encoding` header, request payload get decompressed
according to header value. Multiple codecs are not supported, i.e: `Content-Encoding: br, gzip`.
2017-12-04 05:09:46 +01:00
Response payload get compressed based on *content_encoding* parameter.
By default `ContentEncoding::Auto` is used. If `ContentEncoding::Auto` is selected
then compression depends on request's `Accept-Encoding` header.
`ContentEncoding::Identity` could be used to disable compression.
If other content encoding is selected the compression is enforced for this codec. For example,
to enable `brotli` response's body compression use `ContentEncoding::Br`:
```rust
extern crate actix_web;
use actix_web::*;
2017-12-04 03:58:15 +01:00
fn index(req: HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.content_encoding(ContentEncoding::Br)
2017-12-04 05:09:46 +01:00
.body("data").unwrap()
2017-12-04 03:58:15 +01:00
}
2017-12-04 05:09:46 +01:00
# fn main() {}
2017-12-04 03:58:15 +01:00
```
2017-12-04 03:51:52 +01:00
## JSON Response
The `Json` type allows you 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*.
```rust
extern crate actix_web;
#[macro_use] extern crate serde_derive;
use actix_web::*;
#[derive(Serialize)]
struct MyObj {
name: String,
}
fn index(req: HttpRequest) -> Result<Json<MyObj>> {
Ok(Json(MyObj{name: req.match_info().query("name")?}))
}
fn main() {
Application::default("/")
2017-12-04 22:32:05 +01:00
.resource(r"/a/{name}", |r| r.method(Method::GET).handler(index))
2017-12-04 03:51:52 +01:00
.finish();
}
```