Clack

Revenge of Lisp in Web

Chapter 3: Hello, World!

English | 日本語

In this chapter, take up the first small program that was appeared in the previous chapter again. Here's the "Hello, World!" code written more kindly.

(defun app (env)
  (declare (ignore env))
  '(200
    (:content-type "text/plain")
    ("Hello, World!")))

(clack:clackup #'app)

You can see Clack application is just a function which takes exactly one argument env and returns a list containing exactly three values -- HTTP status, headers and body.

Let's change it a little like this for trial.

(defun app (env)
  `(200
    (:content-type "text/plain")
    ("Hello stranger from:"
     ,(getf env :remote-addr))))

(clack:clackup #'app)

This code would show you the remote address. Normally it should be 127.0.0.1 if you're running the server on your localhost. The env is a property list which contains lots of information about an HTTP connection.

It also allows to return a file as the body for instead of texts. Here's more complicated example.

(defun app (env)
  (cond
    ((string= (getf env :path-info) "/favicon.ico")
     '(200
       (:content-type "image/x-icon")
       #p"/path/to/favicon.ico"))
    ((string= (getf env :path-info) "/")
     '(200
       (:content-type "text/html")
       ("Hello again")))
    (t '(404 (:content-type "text/plain") ("Not found")))))

(clack:clackup #'app)

This app would serve favicon.ico if the request path is "/favicon.ico", "Hello again" for the request to the root (/) and otherwise 404.