【问题标题】:Wai Request CopyingWai 请求复印
【发布时间】:2015-12-01 13:28:04
【问题描述】:

我希望能够将请求正文的内容用作缓存键的一部分。

我当前的代码如下:

caching app req respond =
    -- Request Body is consumed here
    cacheKey <- strictRequestBody req
    -- the req object is no more usable as body was consumed
    maybe (app req (addToCacheAndRespond cacheKey))
        (sendResponse . responseFromCachedValue)
        (lookup cacheKey cacheContainer)

我在这里没有看到任何解决方案。如何从 cacheKey 和 req 对象复制请求或生成另一个请求?

或者事件更好有没有其他更好的解决方案?

作为奖励,有人能指出将 Wai Application 类型从 Request -&gt; IO Response 更改为 Request -&gt; (Response -&gt; IO ResponseReceived) -&gt; IO ResponseReceived 的理由吗?

【问题讨论】:

  • Michael Snoyman 在this blog article 中讨论了 WAI API 更改的一些原因。还有一个follow up
  • 谢谢!写我的中间件确实更难。

标签: haskell middleware haskell-wai


【解决方案1】:

我终于找到了如何以 requestLogger 为例:

http://haddock.stackage.org/lts-3.15/wai-extra-3.0.13/src/Network.Wai.Middleware.RequestLogger.html#logStdout

主要是需要把请求体复制回来……

getRequestBody :: Request -> IO (Request, [S8.ByteString])
getRequestBody req = do
  let loop front = do
         bs <- requestBody req
         if S8.null bs
             then return $ front []
             else loop $ front . (bs:)
  body <- loop id
  -- logging the body here consumes it, so fill it back up
  -- obviously not efficient, but this is the development logger
  --
  -- Note: previously, we simply used CL.sourceList. However,
  -- that meant that you could read the request body in twice.
  -- While that in itself is not a problem, the issue is that,
  -- in production, you wouldn't be able to do this, and
  -- therefore some bugs wouldn't show up during testing. This
  -- implementation ensures that each chunk is only returned
  -- once.
  ichunks <- newIORef body
  let rbody = atomicModifyIORef ichunks $ \chunks ->
         case chunks of
             [] -> ([], S8.empty)
             x:y -> (y, x)
  let req' = req { requestBody = rbody }
  return (req', body)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 2018-03-21
    • 2020-02-23
    • 1970-01-01
    • 2014-09-04
    • 1970-01-01
    相关资源
    最近更新 更多