Serve static files

:: Racket

I wanted Frog to provide a “preview” feature: Launch a local web server with a version of the site, and open a web browser.

This local web server simply needs to serve static files. No server-side applications. (Not even features you’d likely want in a production static file server like gzip compression or If-Modified handling.) It just needs to start quickly, and preferably not be a lot of work to code.

At first glance, the Racket web server’s serve/servlet function has a somewhat overwhelming set of options—approximately 25 keyword arguments. Fortunately only a few apply to this situation. If you want to start a web server that only serves static files, it’s simply this:

1
2
3
4
5
6
7
8
(require web-server/servlet-env
         web-server/http
         web-server/dispatchers/dispatch)
(serve/servlet (lambda (_) (next-dispatcher))
               #:servlet-path "/"
               #:extra-files-paths (list path/to/files)
               #:port 8080
               #:launch-browser? #t)

Easy.


Just as I was finishing this post, Jay McCarthy pointed out to me that the docs have an example of a more direct way:

1
2
3
4
5
(require web-server/web-server)
(serve #:dispatch (files:make #:url->path (make-url->path path/to/files)
                              #:path->mime-type (lambda (_)
                                                  #"application/octet-stream"))
       #:port 8080)

This handles requests more directly, as well as not requiring modules that are hardly utilized, since we’re not using any servlets.

Just keep in mind a few wrinkles:

For example, here’s how serve/servlet does these things.

Using serve is more efficient and flexible. You can use it for a variety of web server scenarios. On the other hand it looks like serve/servlet is probably more convenient for the specific use case of “preview this in a local web server and browser”.