Http Client in PureScript
Here’s an idiomatic PureScript example demonstrating the concept of an HTTP client:
This 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.Web
for making HTTP requests andEffect.Aff
for handling asynchronous effects.The
main
function 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.get
function is used to make an HTTP GET request to “https://purescript.org”. We specifyResponseFormat.string
to 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:
Save the code in a file named
src/Main.purs
.Build and run the program:
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.