Skip to content

Instantly share code, notes, and snippets.

@mmstick
Created May 23, 2017 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmstick/eede6103e830efe4a1d99d2f90bd823b to your computer and use it in GitHub Desktop.
Save mmstick/eede6103e830efe4a1d99d2f90bd823b to your computer and use it in GitHub Desktop.
Source code for the software projects route of my web server
use accept_encoding::AcceptEncoding;
use cacher::{CachedContent, Page, PageCache};
use database::DBConnection;
use horrorshow::prelude::*;
use horrorshow::Template;
use rocket::State;
use rocket_contrib::Template as HandlebarTemplate;
macro_rules! request_content {
($cache:ident, $url:ident, $encoding:ident, $closure:expr) => {
match $cache.request_content($url.clone(), $encoding) {
Ok(content) => Ok(content),
Err(action) => $cache.update_cache($url, action, $encoding, $closure)
}
}
}
#[get("/projects")]
pub fn software_projects (
cache: State<PageCache>,
conn: DBConnection,
encoding: AcceptEncoding
) -> Result<CachedContent, String> {
let url = String::from("/projects");
request_content!(cache, url, encoding, || {
let context = get_software_projects(&conn)?;
Ok(Page::new(HandlebarTemplate::render("software_index", &context), encoding).into())
})
}
#[derive(Serialize)]
pub struct PageContext {
page: String
}
#[derive(FromForm, Serialize)]
pub struct SoftwareProject {
pub name: String,
pub repo: String,
pub description: String,
pub image: Option<String>,
}
const GET_PROJECTS: &'static str = "SELECT
name, repo, description, image
FROM software ORDER BY ranking";
pub fn get_software_projects(conn: &DBConnection) -> Result<PageContext, String> {
let iterator = conn.get().query(GET_PROJECTS, &[]).map_err(|why| why.to_string())?;
let iterator = iterator.iter()
.map(|project| SoftwareProject {
name: project.get(0),
repo: project.get(1),
description: project.get(2),
image: project.get(3),
});
let html = html! {
@ for project in iterator {
article {
header {
@ if let Some(ref image) = project.image {
@ if !image.is_empty() {
img(src = image);
}
}
div(class = "name") {
: Raw(&project.name)
}
div(class = "repo") {
a(href = &project.repo) {
: Raw(&project.repo)
}
}
}
section {
p {
: Raw(&project.description)
}
}
}
}
};
Ok(PageContext { page: html.into_string().unwrap_or_default() })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment