Skip to content

Commit 203a26e

Browse files
committed
Use serde_json::from_str instead of from_reader when deserialize Json
`serde_json::from_reader` is considerably slow for some reason. serde-rs/json#160
1 parent 5a9d857 commit 203a26e

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

contrib/src/json.rs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use std::ops::{Deref, DerefMut};
2-
use std::io::Read;
2+
use std::io::{self, Read};
33

44
use rocket::outcome::{Outcome, IntoOutcome};
55
use rocket::request::Request;
@@ -88,18 +88,23 @@ impl<T> Json<T> {
8888
const LIMIT: u64 = 1 << 20;
8989

9090
impl<T: DeserializeOwned> FromData for Json<T> {
91-
type Error = SerdeError;
91+
type Error = io::Error;
9292

93-
fn from_data(request: &Request, data: Data) -> data::Outcome<Self, SerdeError> {
93+
fn from_data(request: &Request, data: Data) -> data::Outcome<Self, io::Error> {
9494
if !request.content_type().map_or(false, |ct| ct.is_json()) {
9595
error_!("Content-Type is not JSON.");
9696
return Outcome::Forward(data);
9797
}
9898

9999
let size_limit = request.limits().get("json").unwrap_or(LIMIT);
100-
serde_json::from_reader(data.open().take(size_limit))
100+
let mut buf = String::new();
101+
if let Err(e) = data.open().take(size_limit).read_to_string(&mut buf) {
102+
error_!("IO Error: {:?}", e);
103+
return Outcome::Failure((Status::BadRequest, e));
104+
}
105+
serde_json::from_str(&buf)
101106
.map(|val| Json(val))
102-
.map_err(|e| { error_!("Couldn't parse JSON body: {:?}", e); e })
107+
.map_err(|e| { error_!("Couldn't parse JSON body: {:?}", e); e.into() })
103108
.into_outcome(Status::BadRequest)
104109
}
105110
}

0 commit comments

Comments
 (0)