Scala播放http过滤器:如何找到请求正文 [英] Scala play http filters: how to find the request body

查看:23
本文介绍了Scala播放http过滤器:如何找到请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个类似于 http://www.playframework 中描述的简单过滤器.com/documentation/2.1.1/ScalaHttpFilters 但我需要访问请求正文.下面的文档指出当我们调用 next 时,我们会返回一个 Iteratee.如果您愿意,您可以将它包装在一个 Enumeratee 中以进行一些转换."我试图弄清楚如何包装 Iteratee 以便我可以将请求正文作为过滤器中的字符串获取,以便我也可以记录它.

I'm trying to write a filter similar to the simple one described in http://www.playframework.com/documentation/2.1.1/ScalaHttpFilters but I need to access the request body. The documentation below states that "when we invoke next, we get back an Iteratee. You could wrap this in an Enumeratee to do some transformations if you wished." I'm trying to figure out how to wrap the Iteratee so I can get the request body as a string within the filter so I can log that as well.

推荐答案

我花了一些时间在这上面.我不是 Scala 专家,但这很有效!:)

I spent some time on this. I am no means a Scala expert but this works pretty well! :)

object AccessLog extends EssentialFilter {
  def apply(nextFilter: EssentialAction) = new EssentialAction {
    def apply(requestHeader: RequestHeader) = {
      val startTime = System.currentTimeMillis

      nextFilter(requestHeader).map { result =>
        val endTime = System.currentTimeMillis
        val requestTime = endTime - startTime

        val bytesToString: Enumeratee[ Array[Byte], String ] = Enumeratee.map[Array[Byte]]{ bytes => new String(bytes) } 
        val consume: Iteratee[String,String] = Iteratee.consume[String]()    
        val resultBody : Future[String] = result.body |>>> bytesToString &>> consume

        resultBody.map {
          body =>
            Logger.info(s"${requestHeader.method} ${requestHeader.uri}" +
          s" took ${requestTime}ms and returned ${result.header.status}")
            val jsonBody = Json.parse(body)
            Logger.debug(s"Response
Header:
${result.header.headers.toString}
Body:
${Json.prettyPrint(jsonBody)}")
        }

         result.withHeaders("Request-Time" -> requestTime.toString)

      }
    }
  }

最终结果会将正文打印为 Json 字符串(打印的很漂亮).

The end result will print the body as a Json String (pretty printed).

这篇关于Scala播放http过滤器:如何找到请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆