Skip to content

Commit

Permalink
gate all serde_json use on a new "json" feature
Browse files Browse the repository at this point in the history
  • Loading branch information
jbr committed May 24, 2020
1 parent fa9e6b5 commit 78ca237
Show file tree
Hide file tree
Showing 4 changed files with 8 additions and 2 deletions.
5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,11 @@ features = ["docs"]
rustdoc-args = ["--cfg", "feature=\"docs\""]

[features]
default = ["h1-server"]
default = ["h1-server", "json"]
h1-server = ["async-h1"]
docs = ["unstable"]
unstable = []
json = ["serde_json"]
# DO NOT USE. Only exists to expose internals so they can be benchmarked.
__internal__bench = []

Expand All @@ -42,7 +43,7 @@ mime = "0.3.14"
mime_guess = "2.0.3"
route-recognizer = "0.1.13"
serde = "1.0.102"
serde_json = "1.0.41"
serde_json = { version = "1.0.41", optional = true }
serde_qs = "0.5.0"

[dev-dependencies]
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ pub use redirect::Redirect;
pub use request::Request;
pub use response::Response;
pub use route::Route;
#[cfg(feature = "json")]
pub use serde_json;
pub use server::Server;

Expand Down
1 change: 1 addition & 0 deletions src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ impl<State> Request<State> {
///
/// If the body cannot be interpreted as valid json for the target type `T`,
/// an `Err` is returned.
#[cfg(feature = "json")]
pub async fn body_json<T: serde::de::DeserializeOwned>(&mut self) -> std::io::Result<T> {
let body_bytes = self.body_bytes().await?;
Ok(serde_json::from_slice(&body_bytes).map_err(|_| std::io::ErrorKind::InvalidData)?)
Expand Down
3 changes: 3 additions & 0 deletions src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,11 +175,13 @@ impl Response {
.set_mime(mime::APPLICATION_WWW_FORM_URLENCODED))
}


/// Encode a struct as a form and set as the response body.
///
/// # Mime
///
/// The encoding is set to `application/json`.
#[cfg(feature = "json")]
pub fn body_json(mut self, json: &impl Serialize) -> serde_json::Result<Self> {
self.res.set_body(serde_json::to_vec(json)?);
Ok(self.set_mime(mime::APPLICATION_JSON))
Expand Down Expand Up @@ -282,6 +284,7 @@ impl Into<http::Response> for Response {
}
}

#[cfg(feature = "json")]
impl From<serde_json::Value> for Response {
fn from(json_value: serde_json::Value) -> Self {
Response::new(StatusCode::Ok)
Expand Down

0 comments on commit 78ca237

Please sign in to comment.