Skip to content

Commit 338c371

Browse files
committed
initial support for json literals
1 parent afe9124 commit 338c371

File tree

4 files changed

+22
-2
lines changed

4 files changed

+22
-2
lines changed

examples/json.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
use async_std::io;
21
use async_std::task;
32
use serde::{Deserialize, Serialize};
3+
use tide::prelude::*;
44
use tide::{Request, Response, StatusCode};
55

66
#[derive(Deserialize, Serialize)]
77
struct Cat {
88
name: String,
99
}
1010

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

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

26+
app.at("/animals").get(|_| async {
27+
Ok(json!({
28+
"meta": { "count": 2 },
29+
"animals": [
30+
{ "type": "cat", "name": "chashu" },
31+
{ "type": "cat", "name": "nori" }
32+
]
33+
}))
34+
});
35+
2636
app.listen("127.0.0.1:8080").await?;
2737
Ok(())
2838
})

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,7 @@ pub use redirect::Redirect;
216216
pub use request::Request;
217217
pub use response::Response;
218218
pub use route::Route;
219+
pub use serde_json;
219220
pub use server::Server;
220221

221222
#[doc(inline)]

src/prelude.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
//! The Tide prelude.
22
pub use http_types::Status;
3+
pub use serde_json::json;

src/response.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,14 @@ impl Into<http::Response> for Response {
335335
}
336336
}
337337

338+
impl From<serde_json::Value> for Response {
339+
fn from(json_value: serde_json::Value) -> Self {
340+
Response::new(StatusCode::Ok)
341+
.body_json(&json_value)
342+
.unwrap_or_else(|_| Response::new(StatusCode::InternalServerError))
343+
}
344+
}
345+
338346
impl From<http::Response> for Response {
339347
fn from(res: http::Response) -> Self {
340348
Self {

0 commit comments

Comments
 (0)