CL-HTTP Chapter 18: Server-Parsed HTML and CGI


Reference Manual | Prev: Chapter 17. SMTP Mail | Next: Chapter 19. Extending CL-HTTP


Contents

  1. 18.1 Server-Parsed HTML (SHTML)
  2. 18.2 CGI Gateway
  3. 18.3 Cookies
  4. 18.4 Content Negotiation

18.1 Server-Parsed HTML (SHTML)

Server-parsed HTML (SHTML) provides template-based page generation. An SHTML file is a standard HTML file containing embedded Lisp expressions that the server evaluates when the page is requested. This is useful for pages that are mostly static but contain a few dynamic elements, such as timestamps, counters, or data lookups.

18.1.1 Exporting SHTML Files

Use the :shtml-file export type:

(http:export-url #u"/status.shtml"
                 :shtml-file
                 :pathname "http:www;status.shtml"
                 :expiration '(:interval 300))

When a client requests this URL, the server reads the file and processes server-side include directives, evaluating embedded Lisp expressions and inserting their output into the response stream.

18.1.2 Template Objects

The :shtml-file export type uses the URL class url:http-template-object. The server methods write-document and write-document-headers specialized on the :shtml-file translation handle the parsing and evaluation of template directives.

SHTML files support conditional GET via modification date tracking, so browsers can cache the rendered output and revalidate with If-Modified-Since headers.


18.2 CGI Gateway

CL-HTTP provides a Common Gateway Interface (CGI 1.1) for running external programs. While computed response functions in Lisp are the preferred approach (eliminating process creation overhead and the limitations of string-based IPC), the CGI gateway enables integration with legacy scripts written in other languages.

18.2.1 The CGI Environment

The macro http:with-cgi-environment establishes CGI variable bindings within the scope of a response function:

(http:with-cgi-environment (server-name server-port
                            request-method query-string
                            content-type content-length
                            remote-addr path-info)
  ;; CGI variables are bound as symbol macros
  (format stream "Server: ~A:~A~%Method: ~A~%"
          server-name server-port request-method))

The standard CGI 1.1 variables are available, plus any HTTP header can be accessed by prefixing its name with http_:

server-name — The server's hostname.
server-port — The port number.
server-protocol — The HTTP version (e.g., "HTTP/1.1").
request-method — GET, POST, HEAD, etc.
query-string — The URL query string after "?".
content-type — The request body MIME type.
content-length — The request body size.
remote-addr — The client's IP address.
remote-host — The client's hostname.
path-info — Extra path information.
path-translated — The translated physical path.
script-name — The URL path of the script.
http_header — Any HTTP header value.

18.2.2 Defining CGI Variables

New CGI variables can be defined with http::define-cgi-variable:

(http::define-cgi-variable my-custom-var
  :value '(get-custom-value *server*)
  :documentation "A custom CGI variable for my application.")

18.2.3 Lisp CGI

CL-HTTP also provides a "Lisp CGI" interface (Server Interface 1.1) that is more efficient than traditional CGI because it evaluates Lisp forms directly in the server process rather than spawning an external program. This gives response functions access to the full CGI variable set while avoiding the overhead of process creation.


18.3 Cookies

Client-side cookies allow the server to store and retrieve state information on the client. CL-HTTP provides a clean interface for setting and reading cookies in response functions.

18.3.1 Reading Cookies

The macro http:with-cookie-values establishes bindings for cookie values within a response function:

(http:with-cookie-values (username preferences)
  ;; username and preferences are bound to cookie values or NIL
  (cond (username
         (write-personalized-page stream username preferences))
        (t
         (write-login-page stream))))

If the cookie names are known at compile time, they are passed as the variables argument and bound as local variables. For runtime-determined cookie names, the local macro get-cookie is available within the scope of with-cookie-values.

Within the scope of with-cookie-values, the variables http:cookies, http:current-user-agent, and http:current-user-agent-version are also accessible.

18.3.2 Setting Cookies

The function http:set-cookie-http-headers creates the header plist for setting cookies on the client:

(http:set-cookie-http-headers
  '(("username" "jcma" :path "/" :expires (:interval 86400))
    ("session-id" "abc123" :path "/" :secure t)))

Each cookie specification is a list of the form (name value &key expires domain path secure). The result is passed as the :additional-headers argument to http:with-successful-response:

(defun write-login-response (url stream)
  (let ((headers (http:set-cookie-http-headers
                   '(("session" "new-session-id"
                      :path "/" :secure t)))))
    (http:with-successful-response (stream :html
        :additional-headers headers)
      (html:with-html-document (:stream stream)
        (html:with-document-body (:stream stream)
          (write-string "Login successful." stream))))))

18.3.3 Cookie Security

Use the :secure flag to ensure cookies are only transmitted over HTTPS connections. For storing Lisp data in cookies, use http:write-to-armor-plated-string to serialize and protect the data, and http:read-from-armor-plated-string to deserialize it. This prevents tampering with cookie values that contain structured Lisp objects.


18.4 Content Negotiation

HTTP content negotiation allows the server to select the best representation of a resource based on the client's stated preferences. CL-HTTP supports server-driven negotiation based on the Accept, Accept-Language, Accept-Charset, and Accept-Encoding request headers.

18.4.1 Language Negotiation

The :content-language keyword on response macros specifies the language of the response:

(http:with-successful-response (stream :html
    :content-language '(:en))
  ...)

For resources available in multiple languages, the response function can inspect the Accept-Language header and select the appropriate version.

18.4.2 Character Set Negotiation

The :character-set keyword specifies the character encoding of the response. CL-HTTP defaults to UTF-8 for HTML content:

(http:with-successful-response (stream :html
    :character-set :utf-8)
  ...)

18.4.3 Encoding Negotiation

Content encoding (compression) is handled at the transport layer. The server can inspect the Accept-Encoding header to determine whether the client supports gzip or deflate encoding.