Static Files

naboris provides some helpers to make serving static files easy.

# Middleware

Naboris.ServerConfig has a sweet helper function to create a middleware which will map incoming requests to a local directory.

1/**
2 Creates a virtual path prefix [list(string)] and maps it to a local directory [string].
3
4 Middlewares are executed in the order they are added.  The final "middleware" is the [requestHandler].
5 */
6let addStaticMiddleware: (list(string), string, t('sessionData)) => t('sessionData);
1(**
2 Creates a virtual path prefix [string list] and maps it to a local directory [string].
3
4 Middlewares are executed in the order they are added.  The final "middleware" is the [requestHandler].
5*)
6val addStaticMiddleware: string list -> string -> 'sessionData t -> 'sessionData t
  • list(string) - Will match against the Route.path of each incoming request.
  • string - Path to a local directory which will have the rest of the path applied to.
  • t - Current Naboris.ServerConfig.

The rest of the incoming request will be applied to the local path e.g. given inputs ["static"], "/path/to/public" a request for /static/images/logo.png would map to /path/to/public/images/logo.png.

1let serverConfig = Naboris.ServerConfig.create()
2  |> Naboris.ServerConfig.addStaticMiddleware(["static"], Sys.getcwd("cur__root") ++ "/public/");
1let server_config = Naboris.ServerConfig.create ()
2  |> Naboris.ServerConfig.addStaticMiddleware
3    ["static"]
4    (Sys.getcwd () ^ "/public/") in

# Routing

For more fine grained control over serving static files there is also a helper function Res.static. The inputs are the same as the above middleware helper function.

1let publicDir = Sys.getcwd() ++ "/public/";
2let serverConfig = Naboris.ServerConfig.create()
3  |> Naboris.ServerConfig.setRequestHandler((route, req, res) => {
4    switch (Naboris.Route.meth(route), Naboris.Route.path(route)) {
5      | _ =>
6          Naboris.Res.status(404, res)
7          |> Naboris.Res.static(publicDir, ["not_found.html"], req);
8    }
9  });
1let public_dir = Sys.getcwd () ^ "/public/" in
2let server_config = Naboris.ServerConfig.create ()
3  |> Naboris.ServerConfig.setRequestHandler(fun route req res ->
4    match (Naboris.Route.meth route, Naboris.Route.path route) with
5      | _ ->
6        Naboris.Res.status 404 res
7          |> Naboris.Res.static
8            public_dir
9            ["not_found.html"]
10            req) in
Support us on GitHub

Star, follow, fork

Star Fork

Found a typo? a bug? or something that just doesn't make any sense? Help improve these docs by opening a github issue.

naboris source code is licensed MIT.
It can be used, copied, and modified free of charge. However, the software is provided "as is" without any warranties. Click the link above for more information.