4.4 File Server

The following example implements a file server which will serve files from the docroot document root set to the current working directory in this example. Four helper functions are used; ws-in-directory-p is used to check if the requested path is within the document root. If not then ws-send-404 is used to send a default “File Not Found”. If so then the file is served with ws-send-file (which appropriately sets the mime-type of the response based on the extension of the file) if it is a file or is served with ws-send-directory-list if it is a directory.

;;; file-server.el --- serve any files using Emacs Web Server (lexical-let ((docroot default-directory)) (ws-start (lambda (request) (with-slots (process headers) request (let ((path (substring (cdr (assoc :GET headers)) 1))) (if (ws-in-directory-p docroot path) (if (file-directory-p path) (ws-send-directory-list process (expand-file-name path docroot) "^[^\.]") (ws-send-file process (expand-file-name path docroot))) (ws-send-404 process))))) 9003))