Introducing iron-middlefiddle: Route specific middleware made easy in Iron

Route specific middleware is a fairly common need in web apps. As soon as you introduce something like authentication into the mix, you’ll probably want a way to apply middleware to routes you only want users to be able to access if they’re logged in.

As things stand, route specific middleware in Iron is a repetitive and messy business, which is where iron_middlefiddle comes in. It provides a macro which turns the tricky into the trivial, allowing you to add middleware to any number of routes within a Router easily.

let mut frontend_router = Router::new();

// Add some `frontend_router` routes and the middleware they should use:

middlefiddle! {
    router => frontend_router,
    routes => {
        lorem: get "/lorem" => controllers::lorem::index,
        ipsum: get "/ipsum" => controllers::ipsum::index,
        dolor: get "/dolor" => controllers::dolor::index,
    },
    middleware => {
        Middleware::BeforeMiddleware => middleware::auth::TokenValidity,
    },
};

// Add some more `frontend_router` routes that aren't going to need the middleware:

frontend_router.get("/amet", controllers::amet::index, "amet");

iron_middlefiddle is well documented and available on crates.io. Naturally, you’ll find its source code in the repo on GitHub.

Setting Iron’s response MIME type with middleware

If your JSON API is powered by Iron, you may well have a lot of duplicate code that sets the MIME type of each Response. Something like this:

use iron::mime::Mime;

pub fn example_handler(req: &mut Request) -> IronResult<Response> {
    let mime = "application/json".parse::<Mime>().unwrap();

    // …

    Ok(Response::with((mime, status::Ok, some_json)))
}

As we can see above, the code for setting a MIME type is generic and doesn’t need anything except a Response to modify. It is therefore a prime AfterMiddleware candidate, which once implemented will remove the need for the code repetition in each and every one of our routes’ handlers. Here’s a very brief AfterMiddleware description from the docs:

AfterMiddleware receive both a Request and a Response and are responsible for doing any response post-processing.

Read on, there’s more »

How to set up environment varying code in your Rust web app

There are times when you’ll want your app to run different code depending on which environment it’s in: development, production, etc.

For example: You provide your templating engine with a baseurl variable. In production, you want it to point to https://my-app.com, but in development you want it to point to http://localhost:8888.

We can accomplish this in Rust-y web apps with environment variables and the dotenv crate, as demonstrated in the following post.

Read on, there’s more »