Http Client in PureScript

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

module Main where

import Prelude

import Effect (Effect)
import Effect.Aff (launchAff_)
import Effect.Class.Console (log)
import Affjax.Web as AX
import Affjax.ResponseFormat as ResponseFormat
import Data.Either (Either(..))
import Data.String (split)
import Data.Array (take)

main :: Effect Unit
main = launchAff_ do
  -- Make an HTTP GET request
  response <- AX.get ResponseFormat.string "https://purescript.org"
  case response of
    Left err -> log $ "Error: " <> AX.printError err
    Right res -> do
      -- Print the HTTP response status
      log $ "Response status: " <> show res.status

      -- Print the first 5 lines of the response body
      let bodyLines = split (Pattern "\n") res.body
      let firstFiveLines = take 5 bodyLines
      log "First 5 lines of response body:"
      traverse_ log firstFiveLines

This PureScript code demonstrates how to make an HTTP GET request and process the response. Here’s a breakdown of the code:

  1. We import necessary modules, including Affjax.Web for making HTTP requests and Effect.Aff for handling asynchronous effects.

  2. The main function is defined as an Effect Unit, which is PureScript’s equivalent to a main entry point.

  3. We use launchAff_ to run our asynchronous code.

  4. The AX.get function is used to make an HTTP GET request to “https://purescript.org”. We specify ResponseFormat.string to get the response as a string.

  5. We use pattern matching to handle the response, which can be either an error (Left) or a success (Right).

  6. If successful, we print the response status using show res.status.

  7. We then split the response body into lines, take the first 5 lines, and print them.

To run this program:

  1. Make sure you have PureScript and Spago (PureScript’s package manager and build tool) installed.

  2. Create a new PureScript project:

$ spago init
$ spago install affjax affjax-web strings
  1. Save the code in a file named src/Main.purs.

  2. Build and run the program:

$ spago run

This example showcases PureScript’s strong type system, its handling of asynchronous operations using Aff, and its functional approach to programming. The use of Either for error handling and traverse_ for iteration over effects are idiomatic PureScript patterns.

Note that PureScript compiles to JavaScript and is typically run in a browser or Node.js environment, which is different from languages that compile to native binaries.