1
0
mirror of https://github.com/actix/actix-extras.git synced 2025-06-25 18:09:22 +02:00

add extractors info to guide

This commit is contained in:
Nikolay Kim
2018-03-31 09:18:25 -07:00
parent 3ee228005d
commit 16c212f853
7 changed files with 64 additions and 9 deletions

View File

@ -329,9 +329,7 @@ It uses *serde* package as a deserialization library.
has to implement *serde's *`Deserialize` trait.
```rust
# extern crate bytes;
# extern crate actix_web;
# extern crate futures;
#[macro_use] extern crate serde_derive;
use actix_web::{App, Path, Result, http::Method};
@ -352,6 +350,27 @@ fn main() {
}
```
It also possible to extract path information to a tuple, in this case you don't need
to define extra type, just use tuple for as a `Path` generic type.
Here is previous example re-written using tuple instead of specific type.
```rust
# extern crate actix_web;
use actix_web::{App, Path, Result, http::Method};
// extract path info using serde
fn index(info: Path<(String, u32)>) -> Result<String> {
Ok(format!("Welcome {}! id: {}", info.0, info.1))
}
fn main() {
let app = App::new()
.resource("/{username}/{id}/index.html", // <- define path parameters
|r| r.method(Method::GET).with(index));
}
```
[Query](../actix_web/struct.Query.html) provides similar functionality for
request query parameters.

View File

@ -58,9 +58,36 @@ fn index(req: HttpRequest) -> HttpResponse {
## JSON Request
There are two options for json body deserialization.
There are several options for json body deserialization.
The first option is to use *HttpResponse::json()*. This method returns a
The first option is to use *Json* extractor. You define handler function
that accepts `Json<T>` as a parameter and use `.with()` method for registering
this handler. It is also possible to accept arbitrary valid json object by
using `serde_json::Value` as a type `T`
```rust
# extern crate actix_web;
#[macro_use] extern crate serde_derive;
use actix_web::{App, Json, Result, http};
#[derive(Deserialize)]
struct Info {
username: String,
}
/// extract `Info` using serde
fn index(info: Json<Info>) -> Result<String> {
Ok(format!("Welcome {}!", info.username))
}
fn main() {
let app = App::new().resource(
"/index.html",
|r| r.method(http::Method::POST).with(index)); // <- use `with` extractor
}
```
The second option is to use *HttpResponse::json()*. This method returns a
[*JsonBody*](../actix_web/dev/struct.JsonBody.html) object which resolves into
the deserialized value.
@ -128,7 +155,7 @@ A complete example for both options is available in
## JSON Response
The `Json` type allows you to respond with well-formed JSON data: simply return a value of
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*.