Writing Web apps in Emacs Lisp

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”

(insert-file-contents file)

(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! 🙂


2 thoughts on “Writing Web apps in Emacs Lisp

  1. Do you know how to send post data or json?? I want to create a notification system:

    (defun httpd/alert (proc path &rest args)
    (with-httpd-buffer proc “text/plain”
    (insert (file-name-nondirectory path)))
    (get-buffer-create “httpd-buffer”)
    (insert (file-name-nondirectory path))



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s