camrymps
camrymps

Reputation: 327

Get CurlCode form cURL IO response - Haskell

I am relatively new to Haskell and I am having some trouble with parsing the response of a cURL request.

Here is the code I have so far:

import Control.Monad
import Network.Curl
import Data.Aeson

getReq :: URLString -> [CurlOption] -> IO (CurlCode, String)
getReq url opt = curlGetString url opt

When I use the getReq function,

Prelude> getReq "http://google.com" []

I get something like this as a response:

(CurlOk, "<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">...)

What I am trying to do is just somehow parse out the CurlCode (CurlOk). It is an IO type so I am confused on how I would go about getting the CurlCode from that.

Any help is greatly appreciated!

Upvotes: 0

Views: 220

Answers (2)

Lee Duhem
Lee Duhem

Reputation: 15121

You can use getReq like this:

do
  (c, _) <- getReq ...

Because getReq returns an IO monad instead of a normal value, it has to be used in another IO monad.

You can learn more about monad and do-notation from Monad

Upvotes: 1

kqr
kqr

Reputation: 15028

Here are some ideas of what you can do. Is any of them close to what you want to do?

getCurlCode :: IO (CurlCode, String) -> IO CurlCode
getCurlCode res = do
    (cc, _) <- res
    return cc

printCurlCode :: IO (CurlCode, String) -> IO ()
printCurlCode res = do
    (cc, _) <- res
    print cc

printStatus :: IO (CurlCode, String) -> IO ()
printStatus res = do
    cc <- getCurlCode res
    if cc == CurlOk
        then putStrLn "Everything okay"
        else putStrLn "Maybe not okay"

curlMessage :: CurlCode -> String
curlMessage cc =
    case cc of
        CurlOk -> "Everything okay"
        _      -> "Maybe not okay"

printCurlMessage :: IO (CurlCode, String) -> IO ()
    cc <- getCurlCode res
    let msg = curlMessage cc
    putStrLn msg

Upvotes: 1

Related Questions