Http Client in Haskell

Here’s the translation of the HTTP Client example from Go to Haskell, formatted in Markdown suitable for Hugo:

import Network.HTTP.Simple
import qualified Data.ByteString.Lazy.Char8 as L8
import Control.Exception (try)
import Data.List (take)

main :: IO ()
main = do
    -- Issue an HTTP GET request to a server. We use the `httpLBS` function
    -- which is a convenient way to make a request and get the response body
    -- as a lazy ByteString.
    eresponse <- try $ httpLBS "https://haskellbyexample.com"
    case eresponse of
        Left e -> putStrLn $ "Error: " ++ show (e :: HttpException)
        Right response -> do
            -- Print the HTTP response status.
            putStrLn $ "Response status: " ++ show (getResponseStatusCode response)
            
            -- Print the first 5 lines of the response body.
            let body = L8.lines $ getResponseBody response
            mapM_ L8.putStrLn $ take 5 body

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:

  1. We import necessary modules: Network.HTTP.Simple for HTTP requests, Data.ByteString.Lazy.Char8 for handling the response body, Control.Exception for error handling, and Data.List for the take function.

  2. In the main function, we use httpLBS to make a GET request to “https://haskellbyexample.com”. This function returns the response as a lazy ByteString.

  3. We use try to handle potential exceptions that might occur during the HTTP request.

  4. If an error occurs, we print it. Otherwise, we proceed to process the response.

  5. We print the HTTP response status code using getResponseStatusCode.

  6. 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

To run this program, you would need to have the http-conduit package installed. You can install it using:

$ cabal install http-conduit

Then you can compile and run the program:

$ ghc http-client.hs
$ ./http-client
Response status: 200
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Haskell by Example</title>

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.