Skip to content

Middlewares

Hayley edited this page Sep 12, 2020 · 1 revision

Middlewares are at the core of FireStorm as they provide a modular way of not only modifying routes but also deciding which route should be used to respond to a request. All middlewares must be children of the Middleware<R> object.

You'll see the R template a lot with middlewares as it represents a type which is a child of Route. This is required so that the middleware is able to know the various attributes of the route so that it can modify them without needing to know what the route type is in advance, enabling middlewares to be used with any route type one wishes to create.

All middlewares follow the same basic structure

template <typename R> class UserDefinedMiddleWare : public MiddleWare<R> {
// All methods and attributes which FireStorm needs to use/modify must be public
public:
  Outcome outcome(R &route, http_request request) {
    return Outcome::Success;
  }
};

Outcomes

The Outcome enum is used to specify whether or not a middleware has succeeded or failed.

enum Outcome {
  Success,
  Failure,
};

All middlewares must have a outcome() method which returns an Outcome. If the outcome() method returns Outcome::Failure then the current request will not be responded to by that particular route. This means that for a request to be responded to by a route, all of the route's middlewares must return Outcome::Success, if no route satisfies this then a 404 Not found will be returned. The outcome() method should have the following signature

Outcome outcome(R &route, http_request request);

where route is a reference to a route, so that a middleware can modify a route, and request is the current HTTP request. Middlewares are the only time where the request is available to the user. Routes respond to requests; Middlewares handle requests and determine which route should be used.

Note: Middlewares are able to throw http status codes which can allow a middleware indirectly return a response. This can be helpful if you have say an authentication middleware where you want it to return a 401 Unauthorised if the request is not authenticated.

Clone this wiki locally