2018-10-08

Making a website in Rust with Rocket (WIP)

Basics

Templating

Using hoedown and markdown to write content

Serving static files for development

A naive implementation would be

#[get("/static/<path..>")]
fn static_serving(path: PathBuf) -> Option<NamedFile> {
    NamedFile::open(Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/static")).join(path)).ok()
}

This is good enough for development purpose. However, I cannot guarantee this is safe to put this on production. In production, I use nginx's static serving features.

How I made it polyglot

Working with cookies

let has_lang_cookie = cookies.get("lang").is_some();
let lang = if has_lang_cookie {
    cookies.get("lang").unwrap().value().to_string()
} else {
    cookies.add(
        Cookie::build("lang", data.info.lang.clone())
            .path("/")
            .finish(),
    );
    data.info.lang.clone()
};

I think this could be improved into something similar to what one can do with Option's get_or_insert. Maybe

let cookie = cookies.get_or_insert_with(
                        "lang",
                        || Cookie::build("lang", data.info.lang.clone())
                               .path("/")
                               .finish()
                    );
let lang = cookie.value().to_string();

This isn't an ideal solution either though. More thoughts need to be put into it.

Closing words