There are several solutions for running a webserver in Emacs like Elnode from Nic Ferrier, httpd.el from Joe Schafer, simple-httpd from Christopher Wellons or Emacs Web Server from Eric Schulte.

For this howto I will use simple-httpd so you will have to install it with M-x package-list-packages as well as mustache as templating engine.

Simple-httpd can be used together with impatient-mode for live serving a Emacs HTML buffer, but it can also used standalone to program a web application in style of Python Flask.

For the start let’s try the famous hello world.



(require 'simple-httpd)

(defservlet hello-world text/plain (path)

(insert “Hello world!”))

Point your browser to localhost:8080/hello-world and it should display the string “Hello world!”

If you want to get your hello world as index you have to evaluate the following snippet



(defun httpd/ (proc path &rest args)

(with-httpd-buffer proc "text/plain"

(insert "hello, let's start writing web apps in Emacs!")))



Now what about parameters to get a bit dynamically? Just use defservlet* instead of defservlet.

You can either have parameters in path or via GET/POST



(defservlet* goto/:path text/plain ()

(insert (format "cd %s" path)))

(defservlet* greet text/plain (name)

(insert “Hello ” name))

Last but not least it’s good style to separate the HTML code from the rest of the functionality so we use the mustache template engine to load and render a template file



(require 'mustache)

(defun template (file context)

“Return rendered template as string

Some code happily copied from http://ergoemacs.org/emacs/elisp_read_file_content.html”

(mustache-render

(with-temp-buffer

(insert-file-contents file)

(buffer-string))

context))

(defservlet* greet text/plain (name)

(let ((context (ht (“name” name))))

(insert (template “/home/basti/emacs-web.html” context))))

The content of the emacs-web.html file could be



Hello, my name is {{name}}



For more information about the mustache template engine refer to https://github.com/Wilfred/mustache.el

Happy web hacking in Emacs! 🙂