1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-12-02 19:12:24 +01:00

Support custom content types in JsonConfig

This commit is contained in:
Phil Booth 2018-12-18 17:53:03 +00:00 committed by Douman
parent 1a940d4c18
commit e9fe3879df
3 changed files with 84 additions and 4 deletions

View File

@ -2,6 +2,10 @@
## [0.7.17] - 2018-xx-xx ## [0.7.17] - 2018-xx-xx
### Added
* Support for custom content types in `JsonConfig`. #637
### Fixed ### Fixed
* HTTP1 decoder should perform case-insentive comparison for client requests (e.g. `Keep-Alive`). #631 * HTTP1 decoder should perform case-insentive comparison for client requests (e.g. `Keep-Alive`). #631

View File

@ -200,7 +200,7 @@ pub trait HttpMessage: Sized {
/// # fn main() {} /// # fn main() {}
/// ``` /// ```
fn json<T: DeserializeOwned>(&self) -> JsonBody<Self, T> { fn json<T: DeserializeOwned>(&self) -> JsonBody<Self, T> {
JsonBody::new(self) JsonBody::new::<()>(self, None)
} }
/// Return stream to http payload processes as multipart. /// Return stream to http payload processes as multipart.

View File

@ -143,7 +143,7 @@ where
let req2 = req.clone(); let req2 = req.clone();
let err = Rc::clone(&cfg.ehandler); let err = Rc::clone(&cfg.ehandler);
Box::new( Box::new(
JsonBody::new(req) JsonBody::new(req, Some(cfg))
.limit(cfg.limit) .limit(cfg.limit)
.map_err(move |e| (*err)(e, &req2)) .map_err(move |e| (*err)(e, &req2))
.map(Json), .map(Json),
@ -155,6 +155,7 @@ where
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// extern crate mime;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// use actix_web::{error, http, App, HttpResponse, Json, Result}; /// use actix_web::{error, http, App, HttpResponse, Json, Result};
/// ///
@ -173,6 +174,9 @@ where
/// r.method(http::Method::POST) /// r.method(http::Method::POST)
/// .with_config(index, |cfg| { /// .with_config(index, |cfg| {
/// cfg.0.limit(4096) // <- change json extractor configuration /// cfg.0.limit(4096) // <- change json extractor configuration
/// .content_type(|mime| { // <- accept text/plain content type
/// mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
/// })
/// .error_handler(|err, req| { // <- create custom error response /// .error_handler(|err, req| { // <- create custom error response
/// error::InternalError::from_response( /// error::InternalError::from_response(
/// err, HttpResponse::Conflict().finish()).into() /// err, HttpResponse::Conflict().finish()).into()
@ -184,6 +188,7 @@ where
pub struct JsonConfig<S> { pub struct JsonConfig<S> {
limit: usize, limit: usize,
ehandler: Rc<Fn(JsonPayloadError, &HttpRequest<S>) -> Error>, ehandler: Rc<Fn(JsonPayloadError, &HttpRequest<S>) -> Error>,
content_type: Option<Box<Fn(mime::Mime) -> bool>>,
} }
impl<S> JsonConfig<S> { impl<S> JsonConfig<S> {
@ -201,6 +206,15 @@ impl<S> JsonConfig<S> {
self.ehandler = Rc::new(f); self.ehandler = Rc::new(f);
self self
} }
/// Set predicate for allowed content types
pub fn content_type<F>(&mut self, predicate: F) -> &mut Self
where
F: Fn(mime::Mime) -> bool + 'static,
{
self.content_type = Some(Box::new(predicate));
self
}
} }
impl<S> Default for JsonConfig<S> { impl<S> Default for JsonConfig<S> {
@ -208,6 +222,7 @@ impl<S> Default for JsonConfig<S> {
JsonConfig { JsonConfig {
limit: 262_144, limit: 262_144,
ehandler: Rc::new(|e, _| e.into()), ehandler: Rc::new(|e, _| e.into()),
content_type: None,
} }
} }
} }
@ -217,6 +232,7 @@ impl<S> Default for JsonConfig<S> {
/// Returns error: /// Returns error:
/// ///
/// * content type is not `application/json` /// * content type is not `application/json`
/// (unless specified in [`JsonConfig`](struct.JsonConfig.html))
/// * content length is greater than 256k /// * content length is greater than 256k
/// ///
/// # Server example /// # Server example
@ -253,10 +269,13 @@ pub struct JsonBody<T: HttpMessage, U: DeserializeOwned> {
impl<T: HttpMessage, U: DeserializeOwned> JsonBody<T, U> { impl<T: HttpMessage, U: DeserializeOwned> JsonBody<T, U> {
/// Create `JsonBody` for request. /// Create `JsonBody` for request.
pub fn new(req: &T) -> Self { pub fn new<S>(req: &T, cfg: Option<&JsonConfig<S>>) -> Self {
// check content-type // check content-type
let json = if let Ok(Some(mime)) = req.mime_type() { let json = if let Ok(Some(mime)) = req.mime_type() {
mime.subtype() == mime::JSON || mime.suffix() == Some(mime::JSON) mime.subtype() == mime::JSON || mime.suffix() == Some(mime::JSON) ||
cfg.map_or(false, |cfg| {
cfg.content_type.as_ref().map_or(false, |predicate| predicate(mime))
})
} else { } else {
false false
}; };
@ -440,4 +459,61 @@ mod tests {
.finish(); .finish();
assert!(handler.handle(&req).as_err().is_none()) assert!(handler.handle(&req).as_err().is_none())
} }
#[test]
fn test_with_json_and_bad_content_type() {
let mut cfg = JsonConfig::default();
cfg.limit(4096);
let handler = With::new(|data: Json<MyObject>| data, cfg);
let req = TestRequest::with_header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/plain"),
).header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
).set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.finish();
assert!(handler.handle(&req).as_err().is_some())
}
#[test]
fn test_with_json_and_good_custom_content_type() {
let mut cfg = JsonConfig::default();
cfg.limit(4096);
cfg.content_type(|mime: mime::Mime| {
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
});
let handler = With::new(|data: Json<MyObject>| data, cfg);
let req = TestRequest::with_header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/plain"),
).header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
).set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.finish();
assert!(handler.handle(&req).as_err().is_none())
}
#[test]
fn test_with_json_and_bad_custom_content_type() {
let mut cfg = JsonConfig::default();
cfg.limit(4096);
cfg.content_type(|mime: mime::Mime| {
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
});
let handler = With::new(|data: Json<MyObject>| data, cfg);
let req = TestRequest::with_header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/html"),
).header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
).set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.finish();
assert!(handler.handle(&req).as_err().is_some())
}
} }