Skip to content

Serving static files

Mohammad Ali Chraghi edited this page Feb 8, 2021 · 3 revisions

In other frameworks, serving static files such as images, videos, and more is really easy by attaching a middleware to the server/instance. In the newer versions of Vex, this is not the case anymore as the framework does not provide a built-in function or middleware for serving static files for flexibility. It encourages to build custom routes by leveraging wildcard routes and send_file function instead. Below is a code you can use in order to serve files:

module main

import nedpals.vex.server
import nedpals.vex.ctx
import nedpals.vex.router

fn main() {
   mut app := router.new()
   app.route(.get, '/public/*filename', fn (req &ctx.Req, mut res ctx.Resp) {
       filename := req.params['filename']
       res.send_file('/public/$filename', 200)
   })
   server.serve(app, 8080)
}

send_file can automatically set the appropriate headers (such as Content-Type) to the files so no need to set up it manually.

Clone this wiki locally