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 firstFiveLinesThis PureScript code demonstrates how to make an HTTP GET request and process the response. Here’s a breakdown of the code:
We import necessary modules, including
Affjax.Webfor making HTTP requests andEffect.Afffor handling asynchronous effects.The
mainfunction is defined as anEffect Unit, which is PureScript’s equivalent to a main entry point.We use
launchAff_to run our asynchronous code.The
AX.getfunction is used to make an HTTP GET request to “https://purescript.org”. We specifyResponseFormat.stringto get the response as a string.We use pattern matching to handle the response, which can be either an error (
Left) or a success (Right).If successful, we print the response status using
show res.status.We then split the response body into lines, take the first 5 lines, and print them.
To run this program:
Make sure you have PureScript and Spago (PureScript’s package manager and build tool) installed.
Create a new PureScript project:
$ spago init
$ spago install affjax affjax-web stringsSave the code in a file named
src/Main.purs.Build and run the program:
$ spago runThis 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.