RSS Feed

Lisp Project of the Day


You can support this project by donating at:

Donate using PatreonDonate using Liberapay

Or see the list of project sponsors.


Tests ๐Ÿ˜€
CI ๐Ÿ˜€

Today we begin our sprint around Fukamachi's web tools and will start from the Clack.

Clack is an intermediate layer between the real webserver and your application code. It unifies requests parsing and you don't need to rewrite an app if you'll decide to run your app under another webserver.

Today it supports FCGI, Hunchentoot, Toot, Woo, Wookie. Woo and Wookie are asynchronous and can be used to serve hundreds of simultaneous connections.

Another interesting feature of Clack is that application is the only a lambda function. Because of this, the application code can be wrapped with middlewares. There are a number of middlewares: for logging, handling errors, serving static files, etc.

Here is an example of the simplest app. A function should return a list of status-code, headers plist and the content. The content should be a list of strings, a vector of bytes or pathname:

POFTHEDAY> (defparameter *server*
              (lambda (env)
                (declare (ignore env))
                '(200 (:content-type "text/plain")
                  ("Hello, Lisp World!")))
              :port 8000))
Hunchentoot server is started.
Listening on

POFTHEDAY> (nth-value 0
             (dex:get "http://localhost:8000"))
"Hello, Lisp World!"

POFTHEDAY> (clack:stop *server*)

Compare this with plain Hunchentoot application:

POFTHEDAY> (hunchentoot:define-easy-handler (say-yo :uri "/") ()
             (setf (hunchentoot:content-type*)
             "Hello Lisp World")

POFTHEDAY> (hunchentoot:start
            (make-instance 'hunchentoot:easy-acceptor
                           :port 8002))

POFTHEDAY> (dex:get "http://localhost:8002/"
                    :headers '(("Custom-Header" . "Hello"))) - [2020-06-20 20:58:04] "GET / HTTP/1.1" 200 16 "-" 
            "Dexador/0.9.14 (SBCL 2.0.2); Darwin; 19.5.0"
"Hello Lisp World"

Clack version is more coherent. All request parameters are in one place and it is obvious how to return a status code or the headers.

Here is the content of the env var passed by the Clack to the application function:

;; For this request:
POFTHEDAY> (dex:get "http://localhost:8000/some/path"
                    :headers '(("Custom-Header" . "Hello")))

;; This plist will be passed as env argument
;; to the function:
 :PATH-INFO "/some/path"
 :SERVER-NAME "localhost"
 :REQUEST-URI "/some/path"
 :URL-SCHEME "http"

;; And here is the content of the HEADERS:
POFTHEDAY> (rutils:print-hash-table
            (getf * :headers))
  "user-agent" "Dexador/0.9.14 (SBCL 2.0.2); Darwin; 19.5.0"
  "host" "localhost:8000"
  "accept" "*/*"
  "custom-header" "Hello"

Tomorrow we'll review a Clack middleware and see how to apply to the app.

Brought to you by 40Ants under Creative Commons License