1
0
Fork 0
mirror of https://gitlab.com/msrd0/gotham-restful.git synced 2025-02-23 04:52:28 +00:00

doc & test for RequestBody

This commit is contained in:
Dominic 2020-05-05 19:50:23 +02:00
parent aa9fa0f457
commit e5f13792c6
Signed by: msrd0
GPG key ID: DCC8C247452E98F9
2 changed files with 72 additions and 4 deletions

View file

@ -93,12 +93,31 @@ impl<T : DeserializeOwned> FromBody for T
pub struct FromBodyNoError;
/// A type that can be used inside a request body. Implemented for every type that is
/// deserializable with serde. If the `openapi` feature is used, it must also be of type
/// `OpenapiType`.
/**
A type that can be used inside a request body. Implemented for every type that is deserializable
with serde. If the `openapi` feature is used, it must also be of type [`OpenapiType`].
If you want a non-deserializable type to be used as a request body, e.g. because you'd like to
get the raw data, you can derive it for your own type. All you need is to have a type implementing
[`FromBody`] and optionally a list of supported media types:
```rust
# #[macro_use] extern crate gotham_restful;
# use gotham_restful::*;
#[derive(FromBody, RequestBody)]
#[supported_types(mime::IMAGE_GIF, mime::IMAGE_JPEG, mime::IMAGE_PNG)]
struct RawImage {
content: Vec<u8>,
content_type: Mime
}
```
[`FromBody`]: trait.FromBody.html
[`OpenapiType`]: trait.OpenapiType.html
*/
pub trait RequestBody : ResourceType + FromBody
{
/// Return all types that are supported as content types.
/// Return all types that are supported as content types. Use `None` if all types are supported.
fn supported_types() -> Option<Vec<Mime>>
{
None

View file

@ -0,0 +1,49 @@
mod custom_request_body
{
use gotham::{
hyper::header::CONTENT_TYPE,
router::builder::*,
test::TestServer
};
use gotham_restful::*;
use mime::TEXT_PLAIN;
const RESPONSE : &[u8] = b"This is the only valid response.";
#[derive(Resource)]
#[resource(create)]
struct FooResource;
#[derive(FromBody, RequestBody)]
#[supported_types(TEXT_PLAIN)]
struct Foo {
content: Vec<u8>,
content_type: Mime
}
#[create(FooResource)]
fn create(body : Foo) -> Raw<Vec<u8>> {
Raw::new(body.content, body.content_type)
}
#[test]
fn test()
{
let server = TestServer::new(build_simple_router(|router| {
router.resource::<FooResource>("foo");
})).unwrap();
let res = server.client()
.post("http://localhost/foo", RESPONSE, TEXT_PLAIN)
.perform().unwrap();
assert_eq!(res.headers().get(CONTENT_TYPE).unwrap().to_str().unwrap(), "text/plain");
let res = res.read_body().unwrap();
let body : &[u8] = res.as_ref();
assert_eq!(body, RESPONSE);
}
}