From b4256b072621aba6b4b9ce9deb624d09b17a18f0 Mon Sep 17 00:00:00 2001 From: Nathan F Yospe Date: Mon, 25 Jul 2022 15:24:51 -0400 Subject: [PATCH] Port of net::server::request_body to RequestParams --- src/request.rs | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/request.rs b/src/request.rs index ba625c7f..0fbc6e2b 100644 --- a/src/request.rs +++ b/src/request.rs @@ -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. @@ -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(&self) -> Result + 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)]