2013-03-12 57 views
1

我想在html頁面中發佈一個curl命令的結果, 在haskell中使用yesod框架。 這是我的代碼至今:如何使用yesod在html頁面上顯示捲曲結果?

{-# LANGUAGE TypeFamilies, QuasiQuotes, MultiParamTypeClasses, 
     TemplateHaskell, OverloadedStrings #-} 
import Yesod 
import Network.Curl 
import Text.Blaze hiding (toMarkup) 

data HelloWorld = HelloWorld 

mkYesod "HelloWorld" [parseRoutes| 
/HomeR GET 
|] 

url = "http://www.google.com/" 
opts = [CurlFollowLocation True] 

res=withCurlDo $ do 
      curlGet url opts 
      return() 

instance ToMarkup (IO a) where 
toMarkup a = a 

instance Yesod HelloWorld 

getHomeR :: Handler RepHtml 
getHomeR = defaultLayout [whamlet|#{toMarkup res}|] 

main :: IO() 
main = warpDebug 3000 HelloWorld 

此代碼啓動服務器警告

Warning: No explicit method nor default method for `Text.Blaze.toMarkup' 
In the instance declaration for `ToMarkup (IO a)' 

和指向網頁瀏覽器

http://localhost:3000 

它給「內部服務器錯誤「作爲HTML頁面沿着上述警告消息。

我對Haskell和Yesod相當陌生......有人可以幫忙嗎?

回答

1

您的縮進在toMarkup(它應該縮進)是錯誤的。但是這些類型仍然是錯誤的。 toMarkup應該返回一個Markup實例,並且curlGet將輸出轉儲到標準輸出,而您想要捕獲它並重新呈現它。

嘗試這樣:

{-# LANGUAGE TypeFamilies, QuasiQuotes, MultiParamTypeClasses, TemplateHaskell, OverloadedStrings #-} 
import Yesod 
import Network.Curl 

data HelloWorld = HelloWorld 

mkYesod "HelloWorld" [parseRoutes| 
    /HomeR GET 
    |] 

url = "http://www.google.com/" 
opts = [CurlFollowLocation True] 

instance Yesod HelloWorld 

getHomeR = do 
    (code, res) <- liftIO $ curlGetString url opts   
    -- This doesn't work since Yesod HTML-escapes the content in the template 
    -- defaultLayout [whamlet|#{res}|] 
    return $ RepHtml $ toContent res 

main :: IO() 
main = warpDebug 3000 HelloWorld 

作爲替代捲曲,你也可以使用http-conduit package。進口Net.HTTP.Conduit,你可以寫getHomeR爲:

getHomeR = fmap (RepHtml . toContent) . liftIO $ simpleHttp "http://www.google.com" 
+0

謝謝盧克......這非常有幫助! – sudoking 2013-03-13 06:29:10