Jump to content

Common Lisp/External libraries/Hunchentoot

From Wikibooks, open books for an open world

Hunchentoot is a web application server written in Common Lisp.

Quick start

[edit | edit source]

Installing with ASDF

[edit | edit source]

Installing Hunchentoot on ASDF-enabled systems. The next command installs Hunchentoot and all dependencies.

(require 'asdf-install)
(asdf-install:install 'hunchentoot)

Generating a simple Web page

[edit | edit source]
(asdf:oos 'asdf:load-op :hunchentoot)

(defpackage :testserv
  (:use :cl :hunchentoot)
  (:export :start-server))

(in-package :testserv)

;; Add a simple prefix dispatcher to the *dispatch-table*
(setq *dispatch-table*
      `(,(create-prefix-dispatcher "/hello-world" 'hello-page)))

;; Handler functions either return generated Web pages as strings,
;; or write to the output stream returned by write-headers
(defun hello-page ()
  "<html><body>Hello World!</body></html>")

(defun start-server (&key (port 4242))
  (start (make-instance 'easy-acceptor :port port)))

Start the server:

(testserv:start-server :port 4242)

The generated image is available on http://localhost:4242/hello-world.

Serving dynamic graphics

[edit | edit source]

This example shows how to generate PNG images with Vecto[1] and serve them with Hunchentoot.

First step: load external dependencies

(asdf:oos 'asdf:load-op :hunchentoot)
(asdf:oos 'asdf:load-op :vecto)

Second step: declare a package

(defpackage :testserv
  (:use :cl :vecto :hunchentoot)
  (:export :start-server))

(in-package :testserv)

Add a simple prefix dispatcher to the *dispatch-table*:

(setq *dispatch-table*
      `(,(create-prefix-dispatcher "/img" 'img-page)))

The img-page function expects HTTP parameter height containing an integer value and generates a PNG image height pixels height. If the parameter is not specified a default value of 150 is used.

(defun img-page ()
  (setf (content-type*) "image/png")
  (let ((out (send-headers))   ; send-headers returns the output flexi-stream
        (bar-height (or (and (parameter "height") (parse-integer (parameter "height")))
                        150)))
    (with-canvas (:width 10 :height bar-height)
      (rectangle 0 0 10 bar-height)
      (set-gradient-fill 0 0
			 0 1 1 1
			 0 bar-height
			 1 0 0 1)
      (fill-and-stroke)
      (save-png-stream out)))) ; write the image data to the output stream obtained from send-headers

Start the server:

(testserv:start-server :port 4242)

The generated image is available on http://localhost:4242/img. Try to change the height: http://localhost:4242/img?height=350

References

[edit | edit source]

See also

[edit | edit source]