Skip to content

Commit

Permalink
Merge pull request #523 from jbr/json-literals
Browse files Browse the repository at this point in the history
adds initial support for json literals, adds "json" feature
  • Loading branch information
yoshuawuyts authored May 31, 2020
2 parents afe9124 + 338c371 commit c7a9d50
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 2 deletions.
14 changes: 12 additions & 2 deletions examples/json.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use async_std::io;
use async_std::task;
use serde::{Deserialize, Serialize};
use tide::prelude::*;
use tide::{Request, Response, StatusCode};

#[derive(Deserialize, Serialize)]
struct Cat {
name: String,
}

fn main() -> io::Result<()> {
fn main() -> tide::Result<()> {
task::block_on(async {
let mut app = tide::new();

Expand All @@ -23,6 +23,16 @@ fn main() -> io::Result<()> {
Ok(Response::new(StatusCode::Ok).body_json(&cat)?)
});

app.at("/animals").get(|_| async {
Ok(json!({
"meta": { "count": 2 },
"animals": [
{ "type": "cat", "name": "chashu" },
{ "type": "cat", "name": "nori" }
]
}))
});

app.listen("127.0.0.1:8080").await?;
Ok(())
})
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ pub use redirect::Redirect;
pub use request::Request;
pub use response::Response;
pub use route::Route;
pub use serde_json;
pub use server::Server;

#[doc(inline)]
Expand Down
1 change: 1 addition & 0 deletions src/prelude.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
//! The Tide prelude.
pub use http_types::Status;
pub use serde_json::json;
8 changes: 8 additions & 0 deletions src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,14 @@ impl Into<http::Response> for Response {
}
}

impl From<serde_json::Value> for Response {
fn from(json_value: serde_json::Value) -> Self {
Response::new(StatusCode::Ok)
.body_json(&json_value)
.unwrap_or_else(|_| Response::new(StatusCode::InternalServerError))
}
}

impl From<http::Response> for Response {
fn from(res: http::Response) -> Self {
Self {
Expand Down

0 comments on commit c7a9d50

Please sign in to comment.