Created
December 14, 2012 15:24
-
-
Save owainlewis/4286239 to your computer and use it in GitHub Desktop.
Haskell HTTP basics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Basic HTTP stuff | |
module Parser where | |
import System.Environment | |
import Data.List | |
import Data.Maybe | |
import Network.HTTP | |
import Network.URI | |
buildRequest :: String -> Request [Char] | |
buildRequest url = Request { | |
rqURI = uri | |
, rqMethod = GET | |
, rqHeaders = [] | |
, rqBody = "" | |
} | |
where | |
uri = fromJust $ parseURI url | |
-- Make a simple HTTP request | |
makeRequest :: Request [Char] -> IO (Either [Char] [Char]) | |
makeRequest request = do | |
resp <- simpleHTTP request | |
case resp of | |
Left err -> return $ Left ("Error: " ++ show err) | |
Right r -> | |
case rspCode r of | |
(2,_,_) -> return $ Right (rspBody r) | |
(3,_,_) -> | |
case findHeader HdrLocation r of | |
Nothing -> return $ Left (show r) | |
Just url -> do | |
let secondRequest = buildRequest url | |
makeRequest secondRequest | |
(4,_,_) -> return $ Left ("Not found") | |
-- Make a simple get request with no headers | |
-- Example : httpGet "http://www.owainlewis.com" | |
httpGet :: String -> IO (Either [Char] [Char]) | |
httpGet url = makeRequest $ buildRequest url | |
-- Main method (just does http get on the first param) | |
-- runhaskell parser.hs http://www.owainlewis.com | |
main = do | |
(url:_) <- getArgs | |
httpGet url | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment