Created
July 19, 2012 17:01
-
-
Save dtjm/3145317 to your computer and use it in GitHub Desktop.
HTTP Fibonacci service in Haskell
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
{-# LANGUAGE OverloadedStrings #-} | |
import Char | |
import Control.Monad (join) | |
import Network.Wai | |
import Network.HTTP.Types | |
import Network.Wai.Handler.Warp (run) | |
import Data.ByteString.Lazy.Char8 () -- Just for an orphan instance | |
import Control.Monad.IO.Class (liftIO) | |
import Data.Conduit | |
import Data.String.Utils () | |
import Data.ByteString as BS (ByteString, putStrLn) | |
import Data.ByteString.Char8 as B (pack, unpack) | |
import Data.ByteString.Lazy.Char8 as LBS (pack, unpack) | |
import Data.Text as T (intercalate, pack, unpack) | |
headers :: ResponseHeaders | |
headers = [("Content-Type", "text/plain")] | |
app :: Application | |
app req | |
| rawPathInfo req == "/fib" = fibHandler req | |
| otherwise = notFoundHandler | |
fibHandler :: Request -> ResourceT IO Response | |
fibHandler req = do | |
case getFibIndex (queryString req) of | |
Nothing -> return $ responseLBS | |
badRequest400 | |
headers | |
"bad request" | |
Just n -> return $ responseLBS | |
ok200 | |
headers | |
(LBS.pack $ show $ fib n) | |
fib :: Int -> Int | |
fib n = fibs !! n | |
fibs :: [Int] | |
fibs = 1 : 2 : zipWith (+) fibs (tail fibs) | |
getFibIndex :: Query -> Maybe Int | |
getFibIndex query = Control.Monad.join (lookup "n" query) >>= extractInt | |
isInteger :: BS.ByteString -> Bool | |
isInteger bs = isInteger' $ B.unpack bs | |
where isInteger' xs = all isDigit xs | |
extractInt :: BS.ByteString -> Maybe Int | |
extractInt s = case isInteger s of | |
True -> Just $ read $ B.unpack s | |
False -> Nothing | |
notFoundHandler :: ResourceT IO Response | |
notFoundHandler = return $ responseLBS | |
status404 | |
headers | |
"Not found" | |
main :: IO () | |
main = do | |
BS.putStrLn $ "http://localhost:8080/" | |
run 8080 $ app |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment