aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Cargo.toml5
-rw-r--r--src/main.rs43
2 files changed, 26 insertions, 22 deletions
diff --git a/Cargo.toml b/Cargo.toml
index 7202391..762ce89 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -16,3 +16,8 @@ bart_derive = "0.1.4"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
+
+[dependencies.rocket_contrib]
+version = "0.3.3"
+default-features = false
+features = ["json"]
diff --git a/src/main.rs b/src/main.rs
index 1794722..1d20cb0 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -4,16 +4,16 @@
extern crate diesel;
extern crate rocket;
extern crate rocket_blog;
+extern crate rocket_contrib;
#[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_contrib::Json;
use rocket::response::{Response, Responder};
use rocket::request::Request;
-use rocket::http::{ContentType, MediaType, Status};
+use rocket::http::{ContentType, Status};
use std::io::Cursor;
#[derive(BartDisplay, Serialize)]
@@ -24,36 +24,35 @@ struct IndexTemplate<'a> {
}
impl<'a> Responder<'a> for IndexTemplate<'a> {
- 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()
- }
+ fn respond_to(self, _: &Request) -> Result<Response<'static>, Status> {
+ Response::build()
+ .header(ContentType::HTML)
+ .sized_body(Cursor::new(format!("{}", &self)))
+ .ok()
}
}
-#[get("/")]
-fn index<'a>(conn: rocket_blog::DbConn) -> IndexTemplate<'a> {
+fn get_posts(conn: rocket_blog::DbConn) -> Vec<models::Post> {
use schema::posts::dsl::*;
- let results = posts.filter(published.eq(false))
+ posts.filter(published.eq(false))
.limit(5)
.load::<models::Post>(&*conn)
- .expect("Error loading posts");
+ .expect("Error loading posts")
+}
+
+#[get("/", format = "text/html")]
+fn index<'a>(conn: rocket_blog::DbConn) -> IndexTemplate<'a> {
+ IndexTemplate { title: "Bloggen", posts: get_posts(conn) }
+}
- IndexTemplate { title: "Bloggen", posts: results }
+#[get("/", format = "application/json")]
+fn index_json(conn: rocket_blog::DbConn) -> Json<Vec<models::Post>> {
+ Json(get_posts(conn))
}
fn main() {
rocket::ignite()
.manage(rocket_blog::init_db_pool())
- .mount("/", routes![index])
+ .mount("/", routes![index, index_json])
.launch();
}