1.1.2 Using web response procedures

The (web response) module can be used to help interpret the response from an HTTP server. The module has many procedures for the proper parsing of the HTTP header. But since (web response) was written to expect data from Guile’s internal HTTP client (web client), we need to do some simple gymnastics to convince it that the Curl-fetched data is as good as the (web client)-fetched data.

First, we need to fetch both the HTTP headers as well as the body. To do this, the curl-easy-setopt option 'header must be #t. When this option is set, the HTTP headers are pre-pended to the body.

Second, we fetch the response as a bytevector and create a binary port from it, which read-response and read-response-body then read. A string port would not do: it would re-encode any non-ASCII bytes of the body.

;; Fetch a web page with its HTTP headers and parse the response with
;; Guile's (web response) module.  Requires guile-curl with Guile 2.2
;; or 3.0.
(use-modules (curl)
             (web response)
             (rnrs bytevectors)
             (rnrs io ports))

(setlocale LC_ALL "")

;; Create a Curl handle
(let ((handle (curl-easy-init)))

  ;; Set the URL from which to get the data
  (curl-easy-setopt handle 'url "https://www.gnu.org/")

  ;; Request that the HTTP headers be included in the response
  (curl-easy-setopt handle 'header #t)

  ;; Get the result as a bytevector, so that the body's bytes are kept
  ;; exactly as received
  (let* ((response-bytes (curl-easy-perform handle #t))

         ;; Create a binary port from the response.  (A string port would
         ;; re-encode any non-ASCII bytes of the body.)
         (response-port (open-bytevector-input-port response-bytes))

         ;; Have the (web response) module to parse the response
         (response (read-response response-port))

         ;; Have the (web response) module extract the body from the
         ;; response
         (response-body (read-response-body response)))

    ;; Display the unpacked HTTP headers
    (display "Response header ----------")
    (newline)
    (write response)
    (newline)
    (newline)

    ;; Display information about the HTTP body
    (format #t "The body contains ~a bytes~%"
            (bytevector-length response-body))
    (format #t "The body is of type ~A~%"
            (car (response-content-type response)))
    (format #t "The encoding of the body is ~A~%"
            (assoc-ref (response-content-type response) 'charset))))