Serve static files
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 |
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 |
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:
-
serve
returns immediately with a procedure you call to shut down the server. -
You’ll need to implement your own version of
serve/servlet
conveniences: -
Print messages like,
Your Web application is running at http://localhost:8080/.
Stop this program at any time to terminate the Web Server.
. -
Call send-url to launch the browser.
-
Wait for the user to press
CTRL-C
, and call the shutdown procedure given to you byserve
.
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”.