Skip to content

Middlewares

Ned Palacios edited this page Apr 16, 2021 · 2 revisions

This section only applies to the old versions of Vex. This will be revised soon.

Middlewares are special functions used for executing code, manipulating the flow or the request and response contexts before passing to the next handler. In short, if you have used middlewares inside your project, the flow will look like this:

Processing Requests -> Middleware -> Route Handler -> Write Response

Middlewares are especially used for logging requests, detecting sessions, and etc.

Creating a Middleware

Creating a middleware is as simple as creating routes for your app. In this example, we will print the request path and the processing time into the terminal. First we need to create a function:

fn log_request(req mut ctx.Req, res mut ctx.Resp) {
   path := req.path
   elapsed := res.time.elapsed().seconds()
   println('${path} -> ${elapsed}s')
}

Inside the function, we are using the req.path for getting the request path and res.time.elapsed() for getting the elapsed time. Now let us start using it.

Using a Middleware

Inside our instance, there is a method named use which we can use to connect our middleware into the server. Simply put s.use(log_request) after the s variable.

fn main() {
    mut s := server.new()
    s.use(log_request)
    // routes goes here
}

Start your server once again and any incoming request will print to your terminal.

Serving at port: 6789
/test -> 0.0006796s
/favicon.ico -> 0.0002799s

Execute middleware on a specific path

Middlewares does not have filters and it applies to all routes. However you can still be able to execute middlewares on specific paths by adding an if statement and return if the specific condition is false.

fn log_request(req mut ctx.Req, res mut ctx.Resp) {
   if req.path !in ['/user', '/baz'] { return } 

   path := req.path
   elapsed := res.time.elapsed().seconds()
   println('${path} -> ${elapsed}s')
}

Now log_request can only be executed either on /baz or /user routes.

Clone this wiki locally