Skip to content

Commit

Permalink
Merge pull request #51 from EspressoSystems/request_body
Browse files Browse the repository at this point in the history
Port of net::server::request_body to RequestParams
  • Loading branch information
nyospe authored Jul 25, 2022
2 parents dfde010 + b4256b0 commit 6a80f2e
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,14 @@ pub enum RequestError {
expected: String,
},

#[snafu(display("Unable to compose JSON"))]
#[snafu(display("Unable to deserialize from JSON"))]
Json,

#[snafu(display("Unable to deserialize from bincode"))]
Bincode,

#[snafu(display("Body type not specified or type not supported"))]
UnsupportedBody,
}

/// Parameters passed to a route handler.
Expand Down Expand Up @@ -242,6 +248,27 @@ impl RequestParams {
{
serde_json::from_slice(&self.post_data.clone()).map_err(|_| RequestError::Json {})
}

/// Deserialize the body of a request.
///
/// The Content-Type header is used to determine the serialization format.
pub fn body_auto<T>(&self) -> Result<T, RequestError>
where
T: serde::de::DeserializeOwned,
{
if let Some(content_type) = self.headers.get("Content-Type") {
match content_type.as_str() {
"application/json" => self.body_json(),
"application/octet-stream" => {
let bytes = self.body_bytes();
bincode::deserialize(&bytes).map_err(|_err| RequestError::Bincode {})
}
_content_type => Err(RequestError::UnsupportedBody {}),
}
} else {
Err(RequestError::UnsupportedBody {})
}
}
}

#[derive(Clone, Debug)]
Expand Down

0 comments on commit 6a80f2e

Please sign in to comment.