As a Haskell beginner I'm currently playing around the IO monad and prepared simple program which gets from the user two information:
- URL (http)
- Output file path
Then it performs GET
request to the provided URL and stores the result in the selected file. HTTP status code of the response is displayed on the standard output
Could you please suggest how such code could be improved? Maybe some places when point-free style can be used? I also feel that the part with confirmation of file overwriting is not very elegant.
import System.IO
import Network.HTTP
import System.Directory
getUrl :: IO String
getUrl = putStr "URL: " >> hFlush stdout >> getLine
confirmOverideOrGetNewPath :: String -> IO String
confirmOverideOrGetNewPath filepath = do
putStr $ "File " ++ filepath ++ " exists. Override? [y/n] "
hFlush stdout
decision <- getLine
let shouldOverride = (if decision == "y" then True else False)
case shouldOverride of True -> return filepath
False -> putStrLn "\nProvide other path" >> getOutputFilepath
getOutputFilepath :: IO String
getOutputFilepath = do
putStr "Output file path: "
hFlush stdout
filepath <- getLine
file_exists <- doesFileExist filepath
case file_exists of True -> confirmOverideOrGetNewPath filepath
False -> return filepath
performGetRequest :: String -> IO (String, Int)
performGetRequest url = do
rsp <- Network.HTTP.simpleHTTP (getRequest url)
content <- getResponseBody rsp
responseCode <- getResponseCode rsp
return (content, responseCodeToInt responseCode)
where
responseCodeToInt :: ResponseCode -> Int
responseCodeToInt code = let (x,y,z) = code in read (mconcat $ show <$> [x,y,z]) :: Int
saveContentToFile :: FilePath -> String -> IO ()
saveContentToFile = writeFile
printHttpStatusCode :: Int -> IO ()
printHttpStatusCode statusCode = putStrLn ("\nStatus code: " ++ show statusCode)
>> putStrLn "Content saved into file"
main :: IO ()
main = do
url <- getUrl
filepath <- getOutputFilepath
(content, statusCode) <- performGetRequest url
saveContentToFile filepath content
printHttpStatusCode statusCode