简体   繁体   English

Snap Framework:如何在处理程序中运行IO

[英]Snap Framework: How do I run IO within a handler

this is probably a simple question and I've seen a similar one on SO, but I'm still stuck. 这可能是一个简单的问题,我在SO上也看到过类似的问题,但是我仍然很困惑。

I'm trying to do an HTTP call to pull in the contents of another blog and display it on my page. 我正在尝试进行HTTP调用以提取另一个博客的内容并将其显示在我的页面上。 This is more of a learning exercise than anything. 这比任何东西都更重要。

Here's my handler 这是我的经理

blog :: App1Handler ()
blog = do
  contents <- Requester.getUrl "http://someblog.com/"
  heistLocal (bindString "contents" contents) . render $ "blog"

Requester.getUrl has the signature getUrl :: String -> IO T.Text Requester.getUrl具有签名getUrl :: String-> IO T.Text

And the error I get back is 我得到的错误是

src/Main.hs:50:15: SRC / Main.hs:50:15:
Couldn't match expected type Handler App1 App1 t0' with actual type IO T.Text' 无法将预期类型的Handler App1 App1 t0' with actual type IO T.Text'相匹配
In the return type of a call of `getUrl' 在调用getUrl的返回类型中
In a stmt of a 'do' block: 在“执行”块的语句中:
contents <- getUrl "http://someblog.com/" 内容<-getUrl“ http://someblog.com/”
In the expression: 在表达式中:
do { contents <- getUrl "http://someblog.com/"; 做{内容<-getUrl“ http://someblog.com/”;
heistLocal (bindString "contents" contents) . heistLocal(bindString“内容”内容)。 render $ "blog" } 渲染$“ blog”}

From what I gather, I'm stuck inside of the IO monad and it wants the type Handler App1 App1 t0. 从我的收集中,我陷入了IO monad的内部,并且它希望类型为Handler App1 App1 t0。 I've experimented with sticking liftIO in places, but I'm pretty confused on this one. 我已经尝试过将liftIO粘贴在某些地方,但是对此我感到很困惑。

Can anyone point me in the right direction? 谁能指出我正确的方向?

Thanks! 谢谢!

You just have to liftIO the IO action returned by getUrl , like this: 您只需要liftIOgetUrl返回的IO操作,就像这样:

contents <- liftIO $ Requester.getUrl "http://someblog.com/"

The reasoning here is simple. 这里的理由很简单。 You have a do-block of type App1Handler () , which means that the right hand side of any <- statement within this do-block must have type App1Handler a . 您有一个App1Handler ()类型的do-block,这意味着此do-block中任何<-语句的右侧必须具有App1Handler a类型。

However, getUrl returns IO Text , so you need to a function to convert from IO a to App1Handler a which is exactly what liftIO does. 然而, getUrl返回IO Text ,所以你需要一个函数来转换从IO aApp1Handler a这正是liftIO一样。

liftIO :: MonadIO m => IO a -> m a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM