Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Port of net::server::request_body to RequestParams #51

Merged
merged 1 commit into from
Jul 25, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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