mirror of
https://github.com/actix/actix-extras.git
synced 2024-11-28 09:42:40 +01:00
add String and Bytes extractor
This commit is contained in:
parent
ef6f310060
commit
d292c5023f
@ -265,7 +265,6 @@ a error in several cases:
|
|||||||
* content-length is greater than 256k
|
* content-length is greater than 256k
|
||||||
* payload terminates with error.
|
* payload terminates with error.
|
||||||
|
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
# extern crate actix_web;
|
# extern crate actix_web;
|
||||||
# extern crate futures;
|
# extern crate futures;
|
||||||
|
@ -115,6 +115,13 @@ impl ResponseError for DeError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Return `BAD_REQUEST` for `Utf8Error`
|
||||||
|
impl ResponseError for Utf8Error {
|
||||||
|
fn error_response(&self) -> HttpResponse {
|
||||||
|
HttpResponse::new(StatusCode::BAD_REQUEST)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Return `InternalServerError` for `HttpError`,
|
/// Return `InternalServerError` for `HttpError`,
|
||||||
/// Response generation can return `HttpError`, so it is internal error
|
/// Response generation can return `HttpError`, so it is internal error
|
||||||
impl ResponseError for HttpError {}
|
impl ResponseError for HttpError {}
|
||||||
|
117
src/extractor.rs
117
src/extractor.rs
@ -1,14 +1,17 @@
|
|||||||
|
use std::str;
|
||||||
use std::ops::{Deref, DerefMut};
|
use std::ops::{Deref, DerefMut};
|
||||||
|
|
||||||
|
use bytes::Bytes;
|
||||||
use serde_urlencoded;
|
use serde_urlencoded;
|
||||||
use serde::de::{self, DeserializeOwned};
|
use serde::de::{self, DeserializeOwned};
|
||||||
use futures::future::{Future, FutureResult, result};
|
use futures::future::{Future, FutureResult, result};
|
||||||
|
use encoding::all::UTF_8;
|
||||||
|
use encoding::types::{Encoding, DecoderTrap};
|
||||||
|
|
||||||
use body::Binary;
|
use error::{Error, ErrorBadRequest};
|
||||||
use error::Error;
|
use handler::{Either, FromRequest};
|
||||||
use handler::FromRequest;
|
|
||||||
use httprequest::HttpRequest;
|
use httprequest::HttpRequest;
|
||||||
use httpmessage::{MessageBody, UrlEncoded};
|
use httpmessage::{HttpMessage, MessageBody, UrlEncoded};
|
||||||
use de::PathDeserializer;
|
use de::PathDeserializer;
|
||||||
|
|
||||||
/// Extract typed information from the request's path.
|
/// Extract typed information from the request's path.
|
||||||
@ -173,20 +176,6 @@ impl<T, S> FromRequest<S> for Query<T>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Request payload extractor.
|
|
||||||
///
|
|
||||||
/// Loads request's payload and construct Binary instance.
|
|
||||||
impl<S: 'static> FromRequest<S> for Binary
|
|
||||||
{
|
|
||||||
type Result = Box<Future<Item=Self, Error=Error>>;
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn from_request(req: &HttpRequest<S>) -> Self::Result {
|
|
||||||
Box::new(
|
|
||||||
MessageBody::new(req.clone()).from_err().map(|b| b.into()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extract typed information from the request's body.
|
/// Extract typed information from the request's body.
|
||||||
///
|
///
|
||||||
/// To extract typed information from request's body, the type `T` must implement the
|
/// To extract typed information from request's body, the type `T` must implement the
|
||||||
@ -242,6 +231,79 @@ impl<T, S> FromRequest<S> for Form<T>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Request payload extractor.
|
||||||
|
///
|
||||||
|
/// Loads request's payload and construct Bytes instance.
|
||||||
|
///
|
||||||
|
/// ## Example
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// extern crate bytes;
|
||||||
|
/// # extern crate actix_web;
|
||||||
|
/// use actix_web::{App, Result};
|
||||||
|
///
|
||||||
|
/// /// extract text data from request
|
||||||
|
/// fn index(body: bytes::Bytes) -> Result<String> {
|
||||||
|
/// Ok(format!("Body {:?}!", body))
|
||||||
|
/// }
|
||||||
|
/// # fn main() {}
|
||||||
|
/// ```
|
||||||
|
impl<S: 'static> FromRequest<S> for Bytes
|
||||||
|
{
|
||||||
|
type Result = Box<Future<Item=Self, Error=Error>>;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn from_request(req: &HttpRequest<S>) -> Self::Result {
|
||||||
|
Box::new(MessageBody::new(req.clone()).from_err())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract text information from the request's body.
|
||||||
|
///
|
||||||
|
/// Text extractor automatically decode body according to the request's charset.
|
||||||
|
///
|
||||||
|
/// ## Example
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// # extern crate actix_web;
|
||||||
|
/// use actix_web::{App, Result};
|
||||||
|
///
|
||||||
|
/// /// extract text data from request
|
||||||
|
/// fn index(body: String) -> Result<String> {
|
||||||
|
/// Ok(format!("Body {}!", body))
|
||||||
|
/// }
|
||||||
|
/// # fn main() {}
|
||||||
|
/// ```
|
||||||
|
impl<S: 'static> FromRequest<S> for String
|
||||||
|
{
|
||||||
|
type Result = Either<FutureResult<String, Error>,
|
||||||
|
Box<Future<Item=String, Error=Error>>>;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn from_request(req: &HttpRequest<S>) -> Self::Result {
|
||||||
|
let encoding = match req.encoding() {
|
||||||
|
Err(_) => return Either::A(
|
||||||
|
result(Err(ErrorBadRequest("Unknown request charset")))),
|
||||||
|
Ok(encoding) => encoding,
|
||||||
|
};
|
||||||
|
|
||||||
|
Either::B(Box::new(
|
||||||
|
MessageBody::new(req.clone())
|
||||||
|
.from_err()
|
||||||
|
.and_then(move |body| {
|
||||||
|
let enc: *const Encoding = encoding as *const Encoding;
|
||||||
|
if enc == UTF_8 {
|
||||||
|
Ok(str::from_utf8(body.as_ref())
|
||||||
|
.map_err(|_| ErrorBadRequest("Can not decode body"))?
|
||||||
|
.to_owned())
|
||||||
|
} else {
|
||||||
|
Ok(encoding.decode(&body, DecoderTrap::Strict)
|
||||||
|
.map_err(|_| ErrorBadRequest("Can not decode body"))?)
|
||||||
|
}
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@ -259,13 +321,26 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_binary() {
|
fn test_bytes() {
|
||||||
let mut req = TestRequest::with_header(header::CONTENT_LENGTH, "11").finish();
|
let mut req = TestRequest::with_header(header::CONTENT_LENGTH, "11").finish();
|
||||||
req.payload_mut().unread_data(Bytes::from_static(b"hello=world"));
|
req.payload_mut().unread_data(Bytes::from_static(b"hello=world"));
|
||||||
|
|
||||||
match Binary::from_request(&req).poll().unwrap() {
|
match Bytes::from_request(&req).poll().unwrap() {
|
||||||
Async::Ready(s) => {
|
Async::Ready(s) => {
|
||||||
assert_eq!(s, Binary::from(Bytes::from_static(b"hello=world")));
|
assert_eq!(s, Bytes::from_static(b"hello=world"));
|
||||||
|
},
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_string() {
|
||||||
|
let mut req = TestRequest::with_header(header::CONTENT_LENGTH, "11").finish();
|
||||||
|
req.payload_mut().unread_data(Bytes::from_static(b"hello=world"));
|
||||||
|
|
||||||
|
match String::from_request(&req).poll().unwrap() {
|
||||||
|
Async::Ready(s) => {
|
||||||
|
assert_eq!(s, "hello=world");
|
||||||
},
|
},
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
use futures::Poll;
|
||||||
use futures::future::{Future, FutureResult, ok, err};
|
use futures::future::{Future, FutureResult, ok, err};
|
||||||
|
|
||||||
use error::Error;
|
use error::Error;
|
||||||
@ -96,6 +97,21 @@ impl<A, B> Responder for Either<A, B>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<A, B, I, E> Future for Either<A, B>
|
||||||
|
where A: Future<Item=I, Error=E>,
|
||||||
|
B: Future<Item=I, Error=E>,
|
||||||
|
{
|
||||||
|
type Item = I;
|
||||||
|
type Error = E;
|
||||||
|
|
||||||
|
fn poll(&mut self) -> Poll<I, E> {
|
||||||
|
match *self {
|
||||||
|
Either::A(ref mut fut) => fut.poll(),
|
||||||
|
Either::B(ref mut fut) => fut.poll(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Convenience trait that converts `Future` object to a `Boxed` future
|
/// Convenience trait that converts `Future` object to a `Boxed` future
|
||||||
///
|
///
|
||||||
/// For example loading json from request's body is async operation.
|
/// For example loading json from request's body is async operation.
|
||||||
|
94
src/json.rs
94
src/json.rs
@ -19,54 +19,6 @@ use httpresponse::HttpResponse;
|
|||||||
///
|
///
|
||||||
/// Json can be used for two different purpose. First is for json response generation
|
/// Json can be used for two different purpose. First is for json response generation
|
||||||
/// and second is for extracting typed information from request's payload.
|
/// and second is for extracting typed information from request's payload.
|
||||||
///
|
|
||||||
/// 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() {}
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// To extract typed information from request's body, the type `T` must implement the
|
|
||||||
/// `Deserialize` trait from *serde*.
|
|
||||||
///
|
|
||||||
/// ## Example
|
|
||||||
///
|
|
||||||
/// ```rust
|
|
||||||
/// # extern crate actix_web;
|
|
||||||
/// #[macro_use] extern crate serde_derive;
|
|
||||||
/// use actix_web::{App, Json, Result, http};
|
|
||||||
///
|
|
||||||
/// #[derive(Deserialize)]
|
|
||||||
/// struct Info {
|
|
||||||
/// username: String,
|
|
||||||
/// }
|
|
||||||
///
|
|
||||||
/// /// deserialize `Info` from request's body
|
|
||||||
/// 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
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
pub struct Json<T>(pub T);
|
pub struct Json<T>(pub T);
|
||||||
|
|
||||||
impl<T> Deref for Json<T> {
|
impl<T> Deref for Json<T> {
|
||||||
@ -95,6 +47,26 @@ impl<T> fmt::Display for Json<T> where T: fmt::Display {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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() {}
|
||||||
|
/// ```
|
||||||
impl<T: Serialize> Responder for Json<T> {
|
impl<T: Serialize> Responder for Json<T> {
|
||||||
type Item = HttpResponse;
|
type Item = HttpResponse;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
@ -108,6 +80,32 @@ impl<T: Serialize> Responder for Json<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// To extract typed information from request's body, the type `T` must implement the
|
||||||
|
/// `Deserialize` trait from *serde*.
|
||||||
|
///
|
||||||
|
/// ## Example
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// # extern crate actix_web;
|
||||||
|
/// #[macro_use] extern crate serde_derive;
|
||||||
|
/// use actix_web::{App, Json, Result, http};
|
||||||
|
///
|
||||||
|
/// #[derive(Deserialize)]
|
||||||
|
/// struct Info {
|
||||||
|
/// username: String,
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// /// deserialize `Info` from request's body
|
||||||
|
/// 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
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
impl<T, S> FromRequest<S> for Json<T>
|
impl<T, S> FromRequest<S> for Json<T>
|
||||||
where T: DeserializeOwned + 'static, S: 'static
|
where T: DeserializeOwned + 'static, S: 'static
|
||||||
{
|
{
|
||||||
|
@ -143,7 +143,7 @@ pub use application::App;
|
|||||||
pub use httpmessage::HttpMessage;
|
pub use httpmessage::HttpMessage;
|
||||||
pub use httprequest::HttpRequest;
|
pub use httprequest::HttpRequest;
|
||||||
pub use httpresponse::HttpResponse;
|
pub use httpresponse::HttpResponse;
|
||||||
pub use handler::{Either, Responder, AsyncResponder, FutureResponse, State};
|
pub use handler::{Either, Responder, AsyncResponder, FromRequest, FutureResponse, State};
|
||||||
pub use context::HttpContext;
|
pub use context::HttpContext;
|
||||||
pub use server::HttpServer;
|
pub use server::HttpServer;
|
||||||
|
|
||||||
@ -179,7 +179,7 @@ pub mod dev {
|
|||||||
pub use context::Drain;
|
pub use context::Drain;
|
||||||
pub use json::JsonBody;
|
pub use json::JsonBody;
|
||||||
pub use info::ConnectionInfo;
|
pub use info::ConnectionInfo;
|
||||||
pub use handler::{Handler, Reply, FromRequest};
|
pub use handler::{Handler, Reply};
|
||||||
pub use route::Route;
|
pub use route::Route;
|
||||||
pub use router::{Router, Resource, ResourceType};
|
pub use router::{Router, Resource, ResourceType};
|
||||||
pub use resource::ResourceHandler;
|
pub use resource::ResourceHandler;
|
||||||
|
Loading…
Reference in New Issue
Block a user