Http Client in Scheme

Here’s an idiomatic Scheme example demonstrating the concept of an HTTP client:

(import (scheme base)
        (scheme write)
        (srfi 13)
        (srfi 28)
        (chibi net http))

(define (main)
  ;; Make an HTTP GET request
  (let* ((response (http-get "https://example.com"))
         (status (car response))
         (headers (cadr response))
         (body (caddr response)))

    ;; Print the HTTP response status
    (display "Response status: ")
    (display status)
    (newline)

    ;; Print the first 5 lines of the response body
    (display "First 5 lines of response body:")
    (newline)
    (let ((lines (string-split body #\newline)))
      (for-each (lambda (line)
                  (display line)
                  (newline))
                (take lines 5)))))

(main)

This Scheme program demonstrates how to make an HTTP GET request and process the response. Let’s break it down:

  1. We import necessary modules, including (chibi net http) which provides HTTP client functionality.

  2. The main function is defined to encapsulate our program logic.

  3. We use http-get to make a GET request to “https://example.com”. This function returns a list containing the status, headers, and body of the response.

  4. We extract the status, headers, and body from the response.

  5. The response status is printed using display and newline.

  6. To print the first 5 lines of the response body, we:

    • Split the body into lines using string-split.
    • Use take to get the first 5 lines.
    • Use for-each with a lambda function to print each line.
  7. Finally, we call the main function to execute our program.

To run this program, you’ll need a Scheme implementation that supports the SRFI (Scheme Requests for Implementation) libraries used here, such as Chibi Scheme. Save the code in a file (e.g., http-client.scm) and run it using your Scheme interpreter:

$ chibi-scheme http-client.scm

This example demonstrates how to make HTTP requests, handle responses, and process text data in Scheme. It showcases Scheme’s functional programming style and use of list processing functions.

Note that the exact output will depend on the content of the website you’re requesting. Also, error handling has been omitted for brevity, but in a real-world application, you should add appropriate error checks and handling.