module Trace.Hpc.Coveralls.Curl ( postJson, PostResult (..) ) where
import Data.Aeson
import Data.Aeson.Types (parseMaybe)
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Maybe
import Network.Curl
data PostResult =
PostSuccess URLString
| PostFailure String
parseResponse :: CurlResponse -> PostResult
parseResponse r = case respCurlCode r of
CurlOK -> PostSuccess $ getField "url"
_ -> PostFailure $ getField "message"
where getField fieldName = fromJust $ mGetField fieldName
mGetField fieldName = do
result <- decode $ LBS.pack (respBody r)
parseMaybe (.: fieldName) result
httpPost :: String -> [HttpPost]
httpPost path = [HttpPost "json_file" Nothing (ContentFile path) [] Nothing]
postJson :: String
-> URLString
-> IO PostResult
postJson path url = do
h <- initialize
setopt h (CurlVerbose True)
setopt h (CurlURL url)
setopt h (CurlHttpPost $ httpPost path)
r <- perform_with_response_ h
return $ parseResponse r