Http Client in Lisp
Here’s an idiomatic Lisp example that demonstrates the same concept as the provided HTTP client example:
(defpackage :http-client-example
(:use :cl :dexador :babel))
(in-package :http-client-example)
(defun main ()
;; Make an HTTP GET request to a server
(handler-case
(multiple-value-bind (body status headers uri stream)
(dex:get "https://example.com")
;; Print the HTTP response status
(format t "Response status: ~A~%" status)
;; Print the first 5 lines of the response body
(let ((lines (split-sequence:split-sequence #\Newline body)))
(loop for line in lines
for i from 0 below 5
do (format t "~A~%" line))))
(error (e)
(format t "An error occurred: ~A~%" e))))
;; Run the main function
(main)
This Lisp example demonstrates how to make an HTTP GET request and process the response. Let’s break it down:
We define a package
http-client-example
and use thedexador
library for HTTP requests andbabel
for text encoding.The
main
function is where the HTTP client logic is implemented.We use
dex:get
from the Dexador library to make an HTTP GET request to “https://example.com”. This is equivalent to thehttp.Get
function in the Go example.The
handler-case
macro is used for error handling, similar to theif err != nil
checks in the Go code.We use
multiple-value-bind
to destructure the response fromdex:get
, which returns the body, status, headers, URI, and stream.The response status is printed using
format
, which is similar tofmt.Println
in Go.To print the first 5 lines of the response body, we split the body into lines using
split-sequence:split-sequence
and then use a loop to print the first 5 lines.If an error occurs during the HTTP request or processing, it’s caught in the
handler-case
and printed.
To run this Lisp program:
- Ensure you have a Common Lisp implementation installed (e.g., SBCL, CCL).
- Install the required libraries (dexador, babel, split-sequence) using Quicklisp:
(ql:quickload '(:dexador :babel :split-sequence))
- Save the code in a file, e.g.,
http-client.lisp
. - Load and run the file in your Lisp REPL:
(load "http-client.lisp")
This example demonstrates how to make HTTP requests, handle responses, and process the response body in Lisp. It showcases Lisp’s powerful error handling with handler-case
and its ability to return multiple values from a function, which is used here with dex:get
.