Defining a new middleware in Starberry is farily simple. By using #[middleware]
macro, starberry will automatically transfer your function into a middleware. The middleware will have the same struct name as the function.
Please write your function name in UpperCamelCase, not the normal sname_case
#[middleware]
pub async fn MyMiddleWare1(){
println!("Middleware: Received request for {}, start processing", req.path());
next(req)
}
The code above shows a most simple middleware, which has the functionality of printing the path of requests
Let’s break down line by line.
#[middleware]
pub async fn MyMiddleWare1(){
The first line gives the middleware name. It accepts one argument, Rc. The reason why we keep the parameter empty is that starberry automatically added mut req: Rc
in the parameter for us, so we don’t need to write it
If you really want to change the name, you may explicitly write this into the parameter, then you can use your custom name
println!("Middleware: Received request for {}, start processing", req.path());
Do the thing this middleware needed to do
next(req)
The next is a keyword in starberry middleware. You need to pass your current request context into it, then it will pass the Rc into the next middleware, the middleware chain continues
}
Closing the middleware function, and directly returns next(req)
#[middleware]
pub async fn MyMiddleWare2(){
let path = req.path().to_owned();
let a = next(req).await;
println!("Middleware: Received request for {}, end processing", path); // You cannot access to req here
a.boxed_future() // You must return a future
}
The middleware above prints a statement after the middleware chain.
Note that now you must use the boxed_future since async middleware expects you return a future
#[middleware]
pub async fn MyMiddleWare3(){
if req.path() == "/directly_return" {
req.response = text_response("Directly return");
req.boxed_future()
} else {
next(req)
}
}
This middleware checks whether the path is /directly_return
, if true it directly returns a text_response by setting the req’s response into a HttpResponse and not passing the Rc into the middleware chain
Please refer to the chapter of Request Context. In the middleware you may read and write in request contest’s locals and params for passing values