2014-03-04 71 views

回答

2

我將建立我的this previous answer例子。

在這方面最重要的模塊它Network.HTTP.Types,特別是Query類型。

您可以從WAI Request使用QueryString獲得Query

作爲Query只不過是一個[(ByteString, Maybe ByteString)]下,我們可以使用lookup從基礎庫找到相應的屬性。

但是,由於lookup包裝類型在Maybe本身,我們最終以Maybe (Maybe ByteString)結束。我的例子包含相當難聽的函數maybeMaybeToMaybe將其轉換爲Maybe ByteString

該示例返回包含id查詢參數的明文響應(在任何URL上)。由於它只是使用show,對於例如URL

http://localhost:3000/foo?id=bar 

它產生

Query parameter: Just "foobar" 

而對於

http://localhost:3000/ 

它產生

Query parameter: Nothing 

下面是完整的源代碼:

{-# LANGUAGE OverloadedStrings #-} 
import Control.Applicative ((<$>)) 
import Control.Monad 
import Network.Wai 
import Network.Wai.Handler.Warp 
import Network.HTTP.Types (status200) 
import Network.HTTP.Types.Header (hContentType) 
import Blaze.ByteString.Builder.Char.Utf8 (fromString) 
import Data.ByteString (ByteString) 

main = do 
    let port = 3000 
    putStrLn $ "Listening on port " ++ show port 
    run port app 

app req f = f $ 
    case pathInfo req of 
     -- Place custom routes here 
     _ -> anyRoute req 

anyRoute req = 
    let query = queryString req :: [(ByteString, Maybe ByteString)] 
     idParam = join $ lookup "id" query :: Maybe ByteString 
    in responseBuilder 
      status200 
      [(hContentType, "text/plain")] 
      $ fromString $ "Query parameter: " ++ (show idParam) 
+4

'maybeMaybeToMaybe'只是'Control.Monad.join'。 –

+0

@MichaelSnoyman非常感謝你的注意!我在上面的代碼中用'join'替換了'maybeMaybeToMaybe',這使得它更簡單!另外,我使用'responseBuilder'去除了內部導入 –