What would Pierre Bourdieu say ?

18 Mar 2019 - Prague

Born from a silly discussion, I tried to code a page in Rust displaying random quotes by Pierre Bourdieu.
Nothing complicated, a json file for database, random selection of a quote, and that's it.

About tests

It's easier to start by including test in your main.rs file. You can do it like this :

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn my_test() {
    // ...
    }
}

Including tests in a mod{} tag allows you to easily export it later by copy/pasting if you need to.
The term use super::* allows the use of functions declared in the same main.rs file.

About the page itself

I've used Rocket to code and serve this page, and Serde to read and deserialize json.

Reading from a json file is quite straightforward (after you've spent an hour looking it up on the internet)

let file = File::open("./data/fr.json")?;

Note that the operator ? can only be used if the function using it returns a Result or Option. In my case, I've defined a structure Quote mirroring my json, and used it like this:

fn get_rand_quote() -> Result<Quote, io::Error> {
    // Opening the file
    let file = File::open("./data/fr.json")?;
    // Reading json and converting it
    // into an array of my Quote structure
    let mut coll: Vec<Quote> = serde_json::from_reader(file)?;
    // Chosing a random index
    let index = rand::thread_rng().gen_range(0, coll.len()); 
    // Returning the random quote
    Ok(coll.remove(index))
}

This is bad in many ways, particularly because I load this file again and again for every request. I should probably load it in memory when the server starts, and use it from there.

Rocket templating capacity is then used to display everything.

I have Apache running of my server, so there's a proxy pass to configure before my rust app can be accessible (at least in a clean way).
Serving it from a subfolder, I just added a line to my VirtualHost declaration:

  <Location "/whatwouldpierrebourdieusay">
    ProxyPass http://localhost:{your app port}/
  </Location>

The result

... is available at What would Pierre Bourdieu say ?.
Unless it crashed :D.

What's next