Skip to main content

Middlewares

What is a Middleware?​

Middlewares are one of the core features of the framework. They are the functions that are called when a request is received. They are responsible for processing the request and returning a response.

Typically, middleware is involved in the following actions:

  • Pre-process the Request
  • Post-process a Response
  • Modify application state
  • Access external services (Redis, Logging, Sessions)

How to create a Middleware?​

Middleware is created by implementing a function that has two parameters, one with type Req and the second one with type Next. These functions can be loaded in the instance of Graphul using the function middleware and calling the module function middleware::from_fn.

Something to understand it's that the order of loading of the middleware affects how the framework works.

For example:

use graphul::{http::{Methods, response::Redirect, response::Response}, Graphul, middleware::{self, Next}, Req, IntoResponse};

async fn my_middleware( request: Req, next: Next ) -> Response {
let Some(token) = request.headers().get("token") else {
return Redirect::to("/login").into_response();
};
next.run(request).await
}

#[tokio::main]
async fn main() {
let mut app = Graphul::new();

app.get("/", || async {
"hello world!"
});
app.middleware(middleware::from_fn(my_middleware));

// routes out of the scope of the middleware
app.get("/login", || async {
"Login page"
});

app.run("127.0.0.1:8000").await;
}

This middleware only affects the first route, all routes added after loading the middleware on line 17 don't apply the middleware logic to them.

Examples​

Here is a list of examples: