CL-HTTP Chapter 19: Extending CL-HTTP


Reference Manual | Prev: Chapter 18. Server-Parsed HTML and CGI | Next: Appendix A. Quick Reference


Contents

  1. 19.1 Custom Export Types
  2. 19.2 Custom URL Classes
  3. 19.3 Custom Stream Handling
  4. 19.4 Adding Protocols
  5. 19.5 Porting to a New Lisp

19.1 Custom Export Types

CL-HTTP's URL export system is extensible. You can define new export types to serve new MIME content types, implement new response strategies, or wrap existing functionality with application-specific behavior.

19.1.1 Defining MIME Types

Use http:define-url-export-type to register a new export type with its MIME content type and file extension:

(http:define-url-export-type
  :shockwave-file      ;; export type keyword
  :dir                 ;; primary file extension
  (:application :x-director)  ;; MIME content type
  :copy-mode :binary   ;; binary or text transfer
  :alternate-extensions (:dcr))  ;; other file extensions

This macro automatically defines the standard methods (write-document, write-document-headers, export-url) for the new type. The :copy-mode controls whether the content is transferred as binary or text (with CRLF canonicalization).

When no corresponding export type is required and you only need to register a MIME type, use http::define-mime-content-type.

19.1.2 Writing Export Methods

For export types that need custom behavior beyond what define-url-export-type provides, write methods on three generic functions:

export-url (url translation &rest args)
Interns the URL and initializes it. Called when the application invokes (http:export-url #u"..." :my-type ...).
write-document-headers (url translation stream)
Handles the HTTP HEAD method. Writes the HTTP headers describing the document. Must not write a body.
write-document (url translation stream)
Handles the HTTP GET method. Writes both headers and body. For non-idempotent operations (those with side effects), define a post-document method instead.
;; Define a custom export type for JSON API endpoints
(defmethod http:export-url ((url url:http-computed-url)
                            (translation (eql :json-api))
                            &rest args)
  (destructuring-bind (&key response-function
                            expiration &allow-other-keys) args
    (setf (url:translation-method url) translation)
    (setf (url:response-function url) response-function)
    (when expiration
      (url:initialize-expiration url expiration))
    url))

(defmethod http:write-document ((url url:http-computed-url)
                                (translation (eql :json-api))
                                stream)
  (http:with-successful-response
      (stream :json
       :cache-control '(:no-cache t))
    (funcall (url:response-function url) url stream)))

19.2 Custom URL Classes

URL classes define the behavior of URL objects. CL-HTTP provides a class hierarchy rooted at url:url with specialized subclasses for different URL schemes and content types. Application code can subclass these for domain-specific behavior.

19.2.1 The URL Class Hierarchy

Key classes in the hierarchy:

url:url
Abstract root class.
url:http-url
Base class for HTTP URLs. Supports scheme, host, port, path.
url:http-object
An HTTP URL that refers to a single document (file or computed).
url:http-path
An HTTP URL that refers to a directory. Supports recursive export of directory trees.
url:http-computed-url
An HTTP URL whose content is generated by a response function.
url:http-form
An HTTP URL that accepts form data via POST.
url:http-search
An HTTP URL that accepts search queries via GET.
url:http-template-object
An HTTP URL whose content is a server-parsed HTML template.

19.2.2 Defining Custom URL Classes

(defclass url:my-api-url
          (url:http-computed-url
           url:expiration-mixin
           url:secure-subnets-mixin)
  ((api-version :initform 1
                :initarg :api-version
                :accessor url:api-version))
  (:documentation "A URL class for versioned API endpoints."))

The URL class can then be specified via the :url-class argument to define-url-export-type, or by specializing export-url methods.


19.3 Custom Stream Handling

CL-HTTP uses Gray streams (CLOS-based streams) for all I/O. The stream class hierarchy wraps the underlying socket with layers for byte counting, chunked transfer encoding, and character encoding.

19.3.1 Stream Architecture

The stream class hierarchy (per-port, defined in tcp-stream.lisp):

cl-http-socket-stream
Base TCP stream wrapping the implementation's socket. Supports both binary (unsigned-byte 8) and character element types on the same stream. Tracks bytes transmitted and received.
cl-http-chunk-transfer-socket-stream
Extends the base stream with HTTP/1.1 chunked transfer encoding. Handles chunk headers, trailers, and boundary management.

19.3.2 Binary/Character Mode Switching

HTTP requires switching between binary and character modes on the same stream (binary for images, character for HTML). CL-HTTP's stream classes support this via mode-switching methods. The macros with-binary-stream and with-text-stream switch the stream mode within their scope:

;; Write mixed binary and character content
(http:with-successful-response (stream :html)
  ;; Stream is in character mode for HTML
  (write-string "<html>" stream)
  ...)

19.3.3 Buffered I/O

For performance, stream implementations should use internal byte buffers with bulk read-sequence/write-sequence operations rather than per-character delegation to the underlying stream. The SBCL and LispWorks ports both use buffered I/O with pooled buffers (via defresource) to minimize allocation on the hot path.


19.4 Adding Protocols

CL-HTTP's architecture supports extension beyond HTTP. The URL system already handles multiple schemes (HTTP, HTTPS, FTP, mailto, Gopher, WAIS), and new protocols can be added by:

  1. Defining a new URL class for the protocol's scheme.
  2. Implementing the connection and stream handling in the port layer.
  3. Defining export types and response methods for the new protocol.

The HTTP/2 implementation (RFC 9113) demonstrates this pattern. It adds a reactor-based connection multiplexer, HPACK header compression, stream prioritization, and flow control while reusing the existing URL dispatch and response function infrastructure.


19.5 Porting to a New Lisp

CL-HTTP's package-based portability model makes porting to a new Common Lisp implementation a well-defined task. The portable code (approximately 80,000 lines) is never modified — a port implements the platform-specific contracts that the portable code expects.

19.5.1 The Portability Contract

Two packages define the portability interface:

IPC — Internal TCP Package
Low-level networking: TCP socket creation, stream classes, DNS resolution, byte counting, network address manipulation. Defined in tcp-stream.lisp.
WWW-UTILS — Portability Bridge
Imports platform-specific symbols from the implementation's packages (threading, MOP, POSIX, etc.) plus IPC and RESOURCES, then exports a unified interface for: process management, file operations, conditions, stream operations, resource pooling, and MOP introspection. Defined across package.lisp, tcp-stream.lisp, unix.lisp, and the portable http:mcl;server;www-utils.lisp.

The HTTP package uses WWW-UTILS and gets all platform-specific functionality through package inheritance. It never contains conditionalized code.

19.5.2 Files Every Port Must Create

FilePackagePurpose
package.lispIPC, WWW-UTILS Import native APIs, export unified interface
tcp-stream.lispIPC, WWW-UTILS Streams, conditions, DNS, connections
unix.lispWWW-UTILS Threading, file ops, atomics, utilities
tcp-interface.lispHTTP Service management, process pool
utf-8.lispIPC Character encoding
ssl.lispIPC SSL/TLS initialization and stream wrapping
x509.lispHTTP X.509 certificate handling
sysdcl.lispCL-USER System definition with loading order
pre-cl-http.lispCL-USER Features, translations, system definition macro
start.lispCL-USER Startup script

19.5.3 The Network Condition Hierarchy

Every port must map the target Lisp's native socket exceptions to CL-HTTP's condition hierarchy (all in the WWW-UTILS package):

network-error
  domain-resolver-error
  local-network-error
    network-resources-exhausted
    unknown-address
    unknown-host-name
  remote-network-error
    bad-connection-state
      connection-closed
      connection-lost
      host-stopped-responding
    connection-error
      connection-refused
    host-not-responding
    protocol-timeout
network-parse-error

Wrapper functions around native socket calls catch implementation-specific exceptions and re-signal them as CL-HTTP conditions.

19.5.4 Key Implementation Areas

Threading
Map make-process, process-run-function, process-wait, make-lock, with-lock-held, and atomic operations to the target Lisp's threading primitives.
Gray Streams
Implement bivalent (binary + character) TCP streams using the target Lisp's Gray stream package. Must support byte counting, timeouts, and stream-unread-char with correct byte count adjustment.
Sockets
Implement server socket accept loops, client connections, DNS resolution, and address manipulation using the target Lisp's socket API.
File System
Map file metadata access (creation date, modification date, length, author) to the target Lisp's POSIX bindings.
MOP
Map class introspection (class-slots, class-direct-subclasses, generic-function-methods) to the target Lisp's Meta-Object Protocol package.

19.5.5 Porting Methodology

The recommended approach, proven during the SBCL port:

  1. Choose a reference port — Study the LispWorks port (http:lw;) as the most complete reference.
  2. Create API mapping tables — Map every platform-specific API (threading, sockets, streams, file system, MOP, FFI) from the reference to the target.
  3. Map conditions — Create a condition "Rosetta Stone" mapping native socket exceptions to CL-HTTP conditions.
  4. Implement in phases:
  5. Match export lists exactly — Every symbol exported by the reference port's WWW-UTILS and IPC packages must also be exported by the new port. Missing exports cause undefined function errors deep in the portable code.
  6. Cold compile with zero warnings — The entire system must compile from scratch with no errors or warnings.
  7. Run the full test suite — All tests must pass, including the example site, dynamic URLs, concurrent connections, graceful error handling, and clean shutdown.

19.5.6 Existing Ports

PortDirectoryStatus
Generahttp:lispm;Released
LispWorkshttp:lw;Released (reference)
SBCLhttp:sbcl;Released (v1.4.2)
MCLhttp:mcl;Released (portable utils)
CMU CLhttp:cmucl;Beta
ACLhttp:acl;Released
SCLhttp:scl;Beta

19.6 Custom Log Classes

The logging system is designed for extensibility via CLOS mixins. See Chapter 9, Section 9.6 for the mixin architecture and instructions on defining custom log classes.