Http Client in Haskell
Here’s the translation of the HTTP Client example from Go to Haskell, formatted in Markdown suitable for Hugo:
This Haskell code demonstrates how to make an HTTP GET request using the http-conduit
library, which provides excellent support for HTTP clients in Haskell.
Here’s a breakdown of what the code does:
We import necessary modules:
Network.HTTP.Simple
for HTTP requests,Data.ByteString.Lazy.Char8
for handling the response body,Control.Exception
for error handling, andData.List
for thetake
function.In the
main
function, we usehttpLBS
to make a GET request to “https://haskellbyexample.com”. This function returns the response as a lazy ByteString.We use
try
to handle potential exceptions that might occur during the HTTP request.If an error occurs, we print it. Otherwise, we proceed to process the response.
We print the HTTP response status code using
getResponseStatusCode
.To print the first 5 lines of the response body, we:
- Get the response body with
getResponseBody
- Split it into lines with
L8.lines
- Take the first 5 lines with
take 5
- Print each line with
mapM_ L8.putStrLn
- Get the response body with
To run this program, you would need to have the http-conduit
package installed. You can install it using:
Then you can compile and run the program:
This example demonstrates how to make HTTP requests in Haskell, handle potential errors, and process the response. It’s a fundamental building block for creating more complex HTTP clients in Haskell.