Http Client in Lisp
Here’s an idiomatic Lisp example that demonstrates the same concept as the provided HTTP client example:
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:
- Save the code in a file, e.g.,
http-client.lisp
. - Load and run the file in your Lisp REPL:
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
.