aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorHarald Eilertsen <haraldei@anduin.net>2017-11-20 15:41:48 +0100
committerHarald Eilertsen <haraldei@anduin.net>2017-11-20 15:41:48 +0100
commitba6d64efd3facfbe3865780292bf85ea0003ace6 (patch)
treeb246f64905599cbac2ed5b1f9026c628d579d905
parent48a517335bdaa6d8e72eb0d0fe6512033b83d43e (diff)
downloadrocket-blog-ba6d64efd3facfbe3865780292bf85ea0003ace6.tar.gz
rocket-blog-ba6d64efd3facfbe3865780292bf85ea0003ace6.tar.bz2
rocket-blog-ba6d64efd3facfbe3865780292bf85ea0003ace6.zip
Use serde_json to create json response when requested by client.
-rw-r--r--Cargo.toml3
-rw-r--r--src/lib.rs3
-rw-r--r--src/main.rs25
-rw-r--r--src/models.rs2
4 files changed, 25 insertions, 8 deletions
diff --git a/Cargo.toml b/Cargo.toml
index 1e69352..7202391 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,3 +13,6 @@ r2d2 = "0.7.4"
r2d2-diesel = "0.16.0"
bart = "0.1.4"
bart_derive = "0.1.4"
+serde = "1.0"
+serde_derive = "1.0"
+serde_json = "1.0"
diff --git a/src/lib.rs b/src/lib.rs
index 8f51d10..097dc66 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -10,6 +10,9 @@ extern crate r2d2_diesel;
extern crate r2d2;
extern crate rocket;
+#[macro_use]
+extern crate serde_derive;
+
use diesel::pg::PgConnection;
use r2d2_diesel::ConnectionManager;
use dotenv::dotenv;
diff --git a/src/main.rs b/src/main.rs
index 03c34df..1794722 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -5,15 +5,18 @@ extern crate diesel;
extern crate rocket;
extern crate rocket_blog;
#[macro_use] extern crate bart_derive;
+extern crate serde;
+extern crate serde_json;
+#[macro_use] extern crate serde_derive;
use self::diesel::prelude::*;
use self::rocket_blog::{schema, models};
use rocket::response::{Response, Responder};
use rocket::request::Request;
-use rocket::http::{ContentType, Status};
+use rocket::http::{ContentType, MediaType, Status};
use std::io::Cursor;
-#[derive(BartDisplay)]
+#[derive(BartDisplay, Serialize)]
#[template = "templates/index.html"]
struct IndexTemplate<'a> {
title: &'a str,
@@ -21,11 +24,19 @@ struct IndexTemplate<'a> {
}
impl<'a> Responder<'a> for IndexTemplate<'a> {
- fn respond_to(self, _: &Request) -> Result<Response<'static>, Status> {
- Response::build()
- .header(ContentType::HTML)
- .sized_body(Cursor::new(format!("{}", &self)))
- .ok()
+ fn respond_to(self, req: &Request) -> Result<Response<'static>, Status> {
+ if req.format().unwrap().is_json() {
+ Response::build()
+ .header(ContentType::JSON)
+ .sized_body(Cursor::new(format!("{}", serde_json::to_string(&self).unwrap())))
+ .ok()
+ }
+ else {
+ Response::build()
+ .header(ContentType::HTML)
+ .sized_body(Cursor::new(format!("{}", &self)))
+ .ok()
+ }
}
}
diff --git a/src/models.rs b/src/models.rs
index 110cabe..bebb321 100644
--- a/src/models.rs
+++ b/src/models.rs
@@ -1,4 +1,4 @@
-#[derive(Queryable)]
+#[derive(Serialize, Queryable)]
pub struct Post {
pub id: i32,
pub title: String,