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

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

问题描述

我正在尝试编写类似于 http://www.playframework中描述的简单过滤器. com/documentation/2.1.1/ScalaHttpFilters ,但我需要访问请求正文.下面的文档指出:当我们下次调用时,我们将返回一个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\nHeader:\n${result.header.headers.toString}\nBody:\n${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天全站免登陆