加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 播放/记录/打印响应正文/运行枚举器/缓冲正文

发布时间:2020-12-16 18:56:16 所属栏目:安全 来源:网络整理
导读:我正在寻找一种在Play框架中打印响应体的方法,我有这样的代码: object AccessLoggingAction extends ActionBuilder[Request] { def invokeBlock[A](request: Request[A],block: (Request[A]) = Future[Result]) = { Logger.info(s"""Request: id=${request.
我正在寻找一种在Play框架中打印响应体的方法,我有这样的代码:

object AccessLoggingAction extends ActionBuilder[Request] {
  def invokeBlock[A](request: Request[A],block: (Request[A]) => Future[Result]) = {
    Logger.info(s"""Request:
      id=${request.id} 
      method=${request.method} 
      uri=${request.uri} 
      remote-address=${request.remoteAddress} 
      body=${request.body}
    """)
    val ret = block(request)
    /*
    ret.map {result =>
      Logger.info(s"""Response:
      id=${request.id} 
      body=${result.body}
      """)
    }
    */ //TODO: find out how to print result.body (be careful not to consume the enumerator)
    ret
  }
}

目前,已注释掉的代码无法正常工作,我的意思是,它会打印出来:

Response:
id=1
body=play.api.libs.iteratee.Enumerator$$anon$18@39e6c1a2

所以,我需要找到一种从Enumerator [Array [Byte]]中获取String的方法.我试着通过阅读这个:http://mandubian.com/2012/08/27/understanding-play2-iteratees-for-normal-humans/来掌握Enumerator的概念

所以…,如果我理解正确的话:

>在将枚举器转换为String的过程中,我不应该干掉它.否则,客户端将不会收到任何信息.
>让我假设我弄清楚如何实现T /过滤器机制.但那么……它不会打败Play框架作为非阻塞流式传输框架的目的(因为我会在内存中构建完整的字节数组,然后在其上调用toString,最后记录它)?

那么,记录响应的正确方法是什么?

提前致谢,
拉嘎

解决方法

此代码有效:

object AccessLoggingAction extends ActionBuilder[Request] {
  def invokeBlock[A](request: Request[A],block: (Request[A]) => Future[Result]) = {
    val start = System.currentTimeMillis

    Logger.info(s"""Request:
      id=${request.id} 
      method=${request.method} 
      uri=${request.uri} 
      remote-address=${request.remoteAddress} 
      body=${request.body}
    """)

    val resultFut = block(request)

    resultFut.map {result =>
      val time = System.currentTimeMillis - start
      Result(result.header,result.body &> Enumeratee.map(arrOfBytes => {
        val body = new String(arrOfBytes.map(_.toChar))
        Logger.info(s"""Response:
      id=${request.id} 
      method=${request.method}
      uri=${request.uri}
      delay=${time}ms 
      status=${result.header.status}
      body=${body}""")
        arrOfBytes
      }),result.connection)
    }
  }
}

我从这里部分学习了它(关于如何从枚举器中获取字节数组):Scala Play 2.1: Accessing request and response bodies in a filter.

我正在使用Play 2.3.7,而我给出的链接使用2.1(并且仍使用PlainResult,2.3中不再存在).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读