Reference Manual | Prev: Installation | Next: URL System
This chapter walks through progressively more complex examples of
exporting URLs and writing response functions. Each example is
complete and can be evaluated in a running CL-HTTP image. The
code uses the HTTP-USER package, which inherits the
HTTP and HTML interfaces. The
#u reader macro completes a partial URL against
the local context (see
http:merge-url).
The simplest thing a web server does is serve a file from disk.
http:export-url
maps a URL to a translation method and a set of properties. The
:html-file translation serves a static HTML file:
(in-package :http-user)
;;; Export a static HTML file.
;;; The :pathname argument names the file on disk.
;;; The :public argument allows proxy caching.
(export-url #u"/my-app/hello.html"
:html-file
:pathname "http:www;my-app;hello.html"
:expiration '(:interval 900)
:public t
:language :en
:keywords '(:my-app)
:documentation "A simple static page.")
After evaluating this form, browsing
http://localhost:8000/my-app/hello.html serves the file.
The :expiration argument controls HTTP caching —
(:interval 900) means the response may be cached for
900 seconds (15 minutes). The :keywords are metadata
used by the server's URL index.
Other static file export types follow the same pattern:
:text-file for plain text, :css-file for
stylesheets, :js-file for JavaScript. See
http:export-url
for the complete list.
To export an entire directory of files at once, use
:directory:
(export-url #u"/my-app/"
:directory
:recursive-p t
:pathname "http:www;my-app;"
:expiration '(:interval 900)
:public t
:language :en
:keywords '(:my-app))
A computed URL generates its response dynamically by calling
a Lisp function. The :computed translation takes a
:response-function that receives two arguments: the URL
object and the output stream to the client.
Every response function must wrap its output in http:with-successful-response, which sends the HTTP status code and headers before the body.
(in-package :http-user)
;;; A response function receives the URL and the stream.
(defmethod respond-to-hello ((url http-url) stream)
(with-successful-response (stream :html
:expires (url:expiration-universal-time url)
:cache-control (url:response-cache-control-directives url)
:content-language (languages url))
(with-html-document (:declare-dtd-version-p :transitional :stream stream)
(with-document-preamble (:stream stream)
(declare-title "Hello World" :stream stream)
(declare-link :reference "/cl-http/css/base.css"
:relation "stylesheet" :media-type "text/css"
:stream stream))
(with-document-body (:stream stream)
(with-section-heading ("Hello from CL-HTTP" :stream stream)
(horizontal-line :stream stream)
(with-paragraph (:stream stream)
(write-string "This page was generated dynamically by Common Lisp at " stream)
(write-string (write-to-string (get-universal-time)) stream)
(write-string "." stream))
(horizontal-line :stream stream))))))
;;; Export the computed URL.
(export-url #u"/my-app/hello"
:computed
:response-function #'respond-to-hello
:expiration '(:interval 60)
:public t
:language :en
:keywords '(:my-app)
:documentation "A dynamically generated greeting page.")
Key points:
with-successful-response is the
stream; the second is the content type keyword (:html,
:text, :jpeg, etc.).
:expires argument should use
url:expiration-universal-time
so the URL's expiration policy is respected.
defmethod
specializing on the URL class allows different behavior for different
URL types.
When the response depends on cached state that may not have changed, use http:with-conditional-get-response instead. It returns a 304 Not Modified status when the client already has a fresh copy, saving bandwidth and computation.
A search URL computes a response based on arguments passed in
the query string after the ?. For example, a request to
/my-app/lookup?common+lisp passes the search keys
("common" "lisp") to the response function.
Search URLs are exported with the :search translation.
The response function receives three arguments: URL, stream, and
(by convention) accesses the search keys via
url:search-keys:
(in-package :http-user)
;;; Response function for a search URL.
;;; The search keys are accessed from the URL object.
(defmethod respond-to-symbol-lookup ((url url:http-search) stream)
(with-slots (url:search-keys) url
(with-successful-response (stream :html
:content-location url
:expires (url:expiration-universal-time url)
:cache-control (url:response-cache-control-directives url)
:content-language (languages url))
(let ((query (car url:search-keys)))
(with-html-document (:declare-dtd-version-p :transitional :stream stream)
(with-document-preamble (:stream stream)
(declare-title "Symbol Lookup" :stream stream)
(declare-link :reference "/cl-http/css/base.css"
:relation "stylesheet" :media-type "text/css"
:stream stream))
(with-document-body (:stream stream)
(with-section-heading ("Symbol Lookup" :stream stream)
(horizontal-line :stream stream)
(cond (query
(with-paragraph (:stream stream)
(write-string "Looking up: " stream)
(with-rendition (:bold :stream stream)
(write-string query stream)))
(let ((sym (find-symbol (string-upcase query) :http)))
(cond (sym
(with-paragraph (:stream stream)
(with-rendition (:bold :stream stream)
(write-string "Documentation: " stream))
(let ((doc (documentation sym 'function)))
(cond (doc (write-string doc stream))
(t (write-string "No documentation available." stream))))))
(t (with-paragraph (:stream stream)
(write-string "Symbol not found." stream))))))
(t (with-paragraph (:stream stream)
(write-string "No search query provided. " stream)
(write-string "Append a symbol name after the ?" stream))))
(horizontal-line :stream stream))))))))
;;; Export the search URL. Note the trailing ? in the URL path.
(export-url #u"/my-app/lookup?"
:search
:response-function #'respond-to-symbol-lookup
:expiration '(:interval 300)
:public t
:language :en
:keywords '(:my-app)
:documentation "Look up a symbol's documentation by name.")
Browse /my-app/lookup?export-url to see the
documentation for http:export-url. Multiple search keys
are separated by + in the URL (e.g.,
/my-app/lookup?foo+bar), which produces a list of strings
in url:search-keys.
Note that the URL path ends with ? — this is
required so CL-HTTP recognizes it as a search URL.
Forms provide a richer interface than search URLs. A
computed form uses :html-computed-form, which
supplies two functions: a :form-function to render the
form (handling GET), and a :response-function to process
the submitted data (handling POST).
The form function uses
html:with-fillout-form
to emit the <form> tag, and
html:accept-input
to emit input elements. The response function uses
http:bind-query-values
to extract the submitted values:
(in-package :http-user)
;;; The form function renders the HTML form (handles GET).
(defmethod compute-greeting-form ((url url:http-form) stream)
(with-successful-response (stream :html
:content-location url
:expires (url:expiration-universal-time url)
:cache-control (url:response-cache-control-directives url)
:content-language (languages url))
(with-html-document (:declare-dtd-version-p :transitional :stream stream)
(with-document-preamble (:stream stream)
(declare-title "Greeting Form" :stream stream)
(declare-link :reference "/cl-http/css/base.css"
:relation "stylesheet" :media-type "text/css"
:stream stream))
(with-document-body (:stream stream)
(with-section-heading ("Personal Greeting" :stream stream)
(horizontal-line :stream stream)
(with-fillout-form (:post url :stream stream)
(with-paragraph (:stream stream)
(with-rendition (:bold :stream stream)
(write-string "Your Name: " stream))
(accept-input 'string "NAME" :size 40 :stream stream))
(with-paragraph (:stream stream)
(with-rendition (:bold :stream stream)
(write-string "Favorite Language: " stream))
(accept-input 'radio-button "LANGUAGE"
:choices '(("Common Lisp" . "CL")
("Scheme" . "SCHEME")
("Clojure" . "CLOJURE"))
:default "CL"
:linebreaks nil
:stream stream))
(with-paragraph (:stream stream)
(accept-input 'submit-button "Submit" :stream stream)
(write-string " " stream)
(accept-input 'reset-button "Reset" :stream stream)))
(horizontal-line :stream stream))))))
;;; The response function handles POST. BIND-QUERY-VALUES binds
;;; the form field names as local variables whose values are the
;;; submitted strings.
(defmethod respond-to-greeting-form ((url url:http-form) stream query-alist)
(bind-query-values (name language)
(url query-alist)
(with-successful-response (stream :html
:expires (url:expiration-universal-time url)
:cache-control (url:response-cache-control-directives url)
:content-language (languages url))
(with-html-document (:declare-dtd-version-p :transitional :stream stream)
(with-document-preamble (:stream stream)
(declare-title "Greeting" :stream stream)
(declare-link :reference "/cl-http/css/base.css"
:relation "stylesheet" :media-type "text/css"
:stream stream))
(with-document-body (:stream stream)
(with-section-heading ("Greeting" :stream stream)
(horizontal-line :stream stream)
(with-paragraph (:stream stream)
(write-string "Hello, " stream)
(with-rendition (:bold :stream stream)
(write-string (or name "Anonymous") stream))
(write-string "!" stream))
(with-paragraph (:stream stream)
(write-string "Your favorite language is " stream)
(with-rendition (:italic :stream stream)
(write-string (or language "unknown") stream))
(write-string "." stream))
(with-paragraph (:stream stream)
(note-anchor "Try again" :reference (name-string url) :stream stream))
(horizontal-line :stream stream)))))))
;;; Export the computed form.
(export-url #u"/my-app/greeting.html"
:html-computed-form
:form-function #'compute-greeting-form
:response-function #'respond-to-greeting-form
:expiration '(:no-expiration-header)
:public t
:language :en
:keywords '(:my-app)
:documentation "A form that generates a personal greeting.")
The form function and response function receive different argument lists:
(url stream) — renders the form HTML.
(url stream query-alist) — the
query-alist is an association list of
(field-name . value) pairs from the submitted form data.
http:bind-query-values
destructures this into local variables matching the field names.
Common input types for
accept-input
include: string, hidden,
password, radio-button,
checkbox, select-choices,
multi-line-text, submit-button, and
reset-button.
CL-HTTP provides a comprehensive set of macros for generating conformant HTML. These macros emit properly structured markup and insulate your code from changes in the HTML standard. Here is a quick tour of the most commonly used macros:
<html>
and </html> tags. The :declare-dtd-version-p
keyword controls the DOCTYPE declaration (:transitional,
:strict, :frameset, or t for default).
<head> section. Contains title, stylesheets,
meta declarations, and base references.
<body> section. All visible content goes here.
<h1> through
<h6>). The heading text can be a string or a
function that writes to the stream.
<p> tags.
<a href="...">). Accepts a
string or function for the display text and a :reference
for the target URL.
with-table-row and
with-table-cell for rows and cells.
:enumerate (ordered), :itemize (unordered),
:definition (definition list), or :plain.
Use enumerating-item for each list item.
:bold, :italic,
:underline, :code, :teletype,
:strike, etc.
<hr> tag.
<img> tag with :stream,
:width, :height, and
:alignment options.
<link> element (stylesheets, etc.).
<br> tag.
Here is a complete example showing several of these macros together:
(in-package :http-user)
(defmethod respond-to-html-demo ((url http-url) stream)
(with-successful-response (stream :html
:expires (url:expiration-universal-time url)
:cache-control (url:response-cache-control-directives url)
:content-language (languages url))
(with-html-document (:declare-dtd-version-p :transitional :stream stream)
(with-document-preamble (:stream stream)
(declare-title "HTML Generation Demo" :stream stream)
(declare-link :reference "/cl-http/css/base.css"
:relation "stylesheet" :media-type "text/css"
:stream stream))
(with-document-body (:stream stream)
(with-section-heading ("HTML Generation Demo" :stream stream)
(horizontal-line :stream stream)
;; A paragraph with styled text and a link.
(with-paragraph (:stream stream)
(write-string "CL-HTTP generates " stream)
(with-rendition (:bold :stream stream)
(write-string "conformant HTML" stream))
(write-string " from Lisp macros. See the " stream)
(note-anchor "reference manual"
:reference "/cl-http/manual/index.html"
:stream stream)
(write-string " for details." stream))
;; An ordered list.
(with-section-heading ("Features" :stream stream :level 3)
(with-enumeration (stream :enumerate)
(dolist (item '("Dynamic page generation"
"Automatic HTML escaping"
"Multi-version HTML support"))
(enumerating-item (stream)
(write-string item stream)))))
;; A simple table.
(with-section-heading ("Platform Support" :stream stream :level 3)
(with-table (:stream stream :cell-spacing 2 :cell-padding 4)
(with-table-row (:stream stream)
(with-table-cell (:stream stream :header-p t)
(write-string "Platform" stream))
(with-table-cell (:stream stream :header-p t)
(write-string "Status" stream)))
(dolist (entry '(("LispWorks" "Released")
("SBCL" "Released")
("Genera" "Released")))
(with-table-row (:stream stream)
(with-table-cell (:stream stream)
(write-string (first entry) stream))
(with-table-cell (:stream stream)
(write-string (second entry) stream))))))
(horizontal-line :stream stream))))))
(export-url #u"/my-app/html-demo"
:computed
:response-function #'respond-to-html-demo
:expiration '(:interval 300)
:public t
:language :en
:keywords '(:my-app)
:documentation "Demonstrates the HTML generation macros.")
CL-HTTP provides a full authentication framework with realms, users,
groups, and access controls. To protect a URL, you first define the
authentication infrastructure, then export the URL with the
:authentication-realm and :capabilities
arguments.
(in-package :http-user)
;;; Step 1: Define an authentication realm.
;;; The realm name appears in the browser's authentication dialog.
;;; :digest uses HTTP Digest authentication (more secure than :basic).
(add-realm :my-app-realm :digest)
;;; Step 2: Create a group within the realm.
(add-group :my-app-realm :developers)
;;; Step 3: Add users to the group.
(add-user "alice"
:my-app-realm
:password "secret123"
:groups '(:developers)
:personal-name "Alice Developer"
:email-address "alice@example.com")
(add-user "bob"
:my-app-realm
:password "hunter2"
:groups '(:developers)
:personal-name "Bob Hacker"
:email-address "bob@example.com")
;;; Step 4: Define an access control that grants capabilities
;;; to the group. Capabilities map HTTP methods to groups.
(add-access-control-group :my-app-developers
:my-app-realm
:capabilities '((:get :developers)
(:head :developers)
(:post :developers)))
;;; Step 5: Export the URL with authentication.
(export-url #u"/my-app/private/dashboard"
:computed
:response-function #'respond-to-hello
:authentication-realm :my-app-realm
:capabilities :my-app-developers
:expiration '(:interval 60)
:language :en
:keywords '(:my-app :private)
:documentation "A protected page requiring authentication.")
When a client requests the protected URL without credentials, the
server returns a 401 Unauthorized response with a
WWW-Authenticate header. The browser then prompts for
credentials and retransmits the request with an
Authorization header.
You can also restrict access by subnet without requiring user
authentication, using the :secure-subnets argument:
;;; Allow access only from the local machine.
(export-url #u"/my-app/admin/status"
:computed
:response-function #'respond-to-hello
:secure-subnets `(,(local-host-ip-address))
:private t
:language :en
:keywords '(:my-app :admin)
:documentation "An admin page restricted by IP address.")
See the Authentication documentation for full details on realms, groups, access control lists, and certificate-based authentication.
CL-HTTP provides dedicated export types for common binary formats.
Each export type sets the correct Content-Type header
automatically:
(in-package :http-user)
;;; GIF image.
(export-url #u"/my-app/images/logo.gif"
:gif-image
:pathname "http:www;my-app;images;logo.gif"
:expiration '(:interval 86400)
:public t
:keywords '(:my-app :images)
:documentation "The application logo.")
;;; JPEG image.
(export-url #u"/my-app/images/photo.jpeg"
:jpeg-image
:pathname "http:www;my-app;images;photo.jpeg"
:expiration '(:interval 86400)
:public t
:keywords '(:my-app :images))
;;; PNG image.
(export-url #u"/my-app/images/diagram.png"
:png-image
:pathname "http:www;my-app;images;diagram.png"
:expiration '(:interval 86400)
:public t
:keywords '(:my-app :images))
;;; Export an entire directory of images.
(export-url #u"/my-app/images/"
:image-directory
:pathname "http:www;my-app;images;"
:expiration '(:interval 86400)
:public t
:keywords '(:my-app :images)
:documentation "All image files in the images directory.")
For maximum performance with frequently accessed files, use the
:cache-file-data argument to hold the file contents in
memory, and :file-data-revalidation to control how often
the in-memory cache checks the disk for changes:
;;; Cache the favicon in memory, revalidate hourly.
(export-url #u"/my-app/favicon.ico"
:ico-image
:pathname "http:www;my-app;favicon.ico"
:cache-file-data t
:file-data-revalidation 3600
:file-data-wired t
:max-age 86400
:public t
:keywords '(:my-app))
To serve binary content from a computed URL, specify the appropriate
content type keyword in with-successful-response:
;;; A response function that generates a GIF image dynamically.
(defmethod respond-with-dynamic-image ((url http-url) stream)
(let ((image-data (generate-my-image)))
(with-successful-response (stream :gif
:content-length (length image-data))
(write-sequence image-data stream))))
CL-HTTP supports both permanent and temporary redirects. A
permanent redirect (:redirect) sends a 301 Moved
Permanently status, telling clients and proxies to update their
bookmarks. A temporary redirect
(:temporary-redirect) sends a 307 Temporary Redirect
status, indicating the resource has moved but may return to the
original URL.
(in-package :http-user)
;;; Permanent redirect (301): use when a URL has moved forever.
;;; :alternate-urls names the new location.
(export-url #u"/old-path/page.html"
:redirect
:alternate-urls #u"/my-app/page.html"
:keywords '(:my-app :redirect))
;;; Temporary redirect (307): use when a URL has moved temporarily.
(export-url #u"/maintenance.html"
:temporary-redirect
:alternate-urls #u"/my-app/maintenance-notice.html"
:keywords '(:my-app :redirect))
The :alternate-urls argument accepts a single URL or a
list of URLs. When multiple alternates are provided, the first is used
as the redirect target.
For dynamic redirects within a response function, use http:redirect-request:
;;; Redirect dynamically based on the user agent.
(defmethod respond-with-redirect ((url http-url) stream)
(declare (ignore stream))
(multiple-value-bind (user-agent)
(current-user-agent)
(redirect-request *server*
(if (user-agent-capability-p :frames user-agent)
#u"/my-app/framed.html"
#u"/my-app/simple.html"))))
(export-url #u"/my-app/adaptive"
:computed
:response-function #'respond-with-redirect
:expiration '(:interval 60)
:keywords '(:my-app))
This chapter covered the basics of serving content with CL-HTTP. For a deeper understanding of the URL system and all available export types, continue to Chapter 4: URL System. See also: