mirror of
https://github.com/actix/actix-extras.git
synced 2025-06-25 01:51:23 +02:00
json request example
This commit is contained in:
@ -55,7 +55,46 @@ fn index(req: HttpRequest) -> HttpResponse {
|
||||
}
|
||||
# fn main() {}
|
||||
```
|
||||
|
||||
|
||||
|
||||
## JSON Request
|
||||
|
||||
Unfortunately, because of async nature of actix web framework, deserializing json
|
||||
requests is not very ergonomic process. First you need to load whole body into
|
||||
temporal storage and only then you can deserialize it.
|
||||
|
||||
Here is simple example. We will deserialize *MyObj* struct.
|
||||
|
||||
```rust,ignore
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct MyObj {
|
||||
name: String,
|
||||
number: i32,
|
||||
}
|
||||
```
|
||||
|
||||
We need to load request body first.
|
||||
|
||||
```rust,ignore
|
||||
fn index(mut req: HttpRequest) -> Future<Item=HttpResponse, Error=Error> {
|
||||
|
||||
req.payload_mut().readany()
|
||||
.fold(BytesMut::new(), |mut body, chunk| { // <- load request body
|
||||
body.extend(chunk);
|
||||
result::<_, error::PayloadError>(Ok(body))
|
||||
})
|
||||
.and_then(|body| { // <- body is loaded, now we can deserialize json
|
||||
let obj = serde_json::from_slice::<MyObj>(&body).unwrap();
|
||||
println!("MODEL: {:?}", obj); // <- do something with payload
|
||||
ok(httpcodes::HTTPOk.response()) // <- send response
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
Full example is available in
|
||||
[examples directory](https://github.com/actix/actix-web/tree/master/examples/json/).
|
||||
|
||||
|
||||
## JSON Response
|
||||
|
||||
The `Json` type allows you to respond with well-formed JSON data: simply return a value of
|
||||
|
Reference in New Issue
Block a user