aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/lib.rs3
-rw-r--r--src/main.rs25
-rw-r--r--src/models.rs2
3 files changed, 22 insertions, 8 deletions
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,