我正在尝试使用 WAI 编写一个简单的斐波那契网络服务器,但我就是不知道类型。这段代码是我想做的事情的本质,但它被破坏了。该getQueryArg
函数返回一个Maybe ByteString
,我想在我的fibHandler
函数中使用它。
- 如何正确处理
Maybe
我的fibHandler
? - 如何在 Maybe 上调用 putStrLn?我正在尝试
fmap
,但我似乎无法做到这一点。
{-# LANGUAGE OverloadedStrings #-}
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 (unpack)
import Data.Text as T (intercalate, pack, unpack)
app :: Application
app req
| rawPathInfo req == "/fib" = fibHandler req
| otherwise = notFoundHandler
fibHandler :: Request -> ResourceT IO Response
fibHandler req = do
let nStr = getQueryArg (queryString req) "n"
fmap (liftIO . BS.putStrLn) n
let n = read nStr
return $ responseLBS
status200
[("Content-Type", "text/plain")]
(show $ fib n)
fib :: Int -> Int
fib n = foldl (*) 1 [1..n]
getQueryArg :: Query -> BS.ByteString -> Maybe BS.ByteString
getQueryArg [] key = Nothing
getQueryArg ((k,v):qs) key
| k == key = Just v
| otherwise = getQueryArg qs key
notFoundHandler :: ResourceT IO Response
notFoundHandler = return $ responseLBS
status404
[("Content-Type", "text/plain")]
"Not found"
main :: IO ()
main = do
BS.putStrLn $ "http://localhost:8080/"
run 8080 $ app
[更新:此代码的工作副本在这里:https ://gist.github.com/3145317 ]