English 中文(简体)
Scala 游乐会在菲斯特中华获得反应头盔?
原标题:Scala Play get response headers in Filter Middleware?

I want to capture the response headers that my server is going to send with response headers to the browser. Upon inspection, I can see those: enter image description here

However when I try to tap into those using my Filter Middleware:

class CustomFilter @Inject()(implicit val mat: Materializer, ec: ExecutionContext) extends Filter {
  private val logger = Logger(this.getClass)

  private def getRequestContext(ctx: RequestContext):String = {
    val RequestContext(userAgent, remoteAddress) = ctx
    // Log request context information based on availability of remoteAddress, appToken and appVersion
    s"NRS Request [User-Agent=$userAgent] [Remote-Address=$remoteAddress]"
  }

  private def getResponseContext(resCtx: ResponseContext): String = {
    val ResponseContext(duration, statusCode, appToken, appVersion, requestID, clientID, redirect, via) = resCtx
    s"NRS Response [DurationInMs=$duration] [Status=$statusCode] [App-Token=$appToken] [App-Version=$appVersion] [Request-ID=$requestID] [Client-ID=$clientID] [Redirect=$redirect] [Via=$via]"
  }


  private def getCompleteContext(reqCtx: RequestContext, resCtx: ResponseContext):String =
    s"{{${getRequestContext(reqCtx)}::${getResponseContext(resCtx)}}}"

  override def apply(nextFilter: RequestHeader => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
    val startTime = System.currentTimeMillis()

    // Extract request context information
    val userAgent = requestHeader.headers.get("User-Agent").getOrElse("")
    val remoteAddress = requestHeader.headers.get("Remote-Address")

    nextFilter(requestHeader).flatMap { result =>
      val endTime = System.currentTimeMillis()
      val duration = endTime - startTime
      val status = result.header.status
      val appToken = result.header.headers.get("X-App-Token")
      val appVersion = result.header.headers.get("X-App-Version")
      val requestID = result.header.headers.get("X-Request-ID")
      val clientID = result.header.headers.get("X-Client-ID")
      val redirect = result.header.headers.get("X-Redirect")
      val via = result.header.headers.get("Via")

      println(s"""Headers: ${result.header.headers.mkString(",")}::${requestHeader.headers.headers.mkString(",")}""")

      if (userAgent.nonEmpty) {
        logger.warn(
          getCompleteContext(
            RequestContext(userAgent, remoteAddress),
            ResponseContext(duration, status, appToken, appVersion, requestID, clientID, redirect, via)
          )
        )
      }

      Future.successful(result)
    } recoverWith {
      case e: Throwable =>
        val endTime = System.currentTimeMillis()
        val duration = endTime - startTime

        if (userAgent.nonEmpty) {
          logger.warn(getCompleteContext(RequestContext(userAgent, remoteAddress), ResponseContext(duration, 500, None, None, None, None, None, None)))
        }

        // Propagate the exception
        Future.failed(e)
    }
  }
}

不幸的是,我无法看到这些反应头盔在我的中间。 谁能帮助我了解我做了什么错呢?

I am able to set new headers but not getting old headers: Future.successful(result.withHeaders("X-Request-ID-022" -> requestID.getOrElse("dvcsdf")))

我收到了这些回复记录:

Response Header 121 - Access-Control-Allow-Origin: *
Response Header 121 - ETag: "XXXXXXX"

这里是我应用的共同证据:

class Filters @Inject()(corsFilter: CORSFilter,
                        clientIdFilter: ClientIdFilter,
                        requestIdFilter: RequestIdFilter,
                        processingTimeFilter: ProcessingTimeFilter,
                        host: HostFilter,
                        date: DateFilter,
                        head: HeadFilter,
                        gzipFilter: GzipFilter,
                        customFilter: CustomFilter
                       )
  extends DefaultHttpFilters(Seq(corsFilter, processingTimeFilter,
      clientIdFilter, requestIdFilter, host, date, head, gzipFilter,customFilter):_*)
问题回答

Your filter needs to be at the start of the list. The code that applies the filters wraps them in the same order as the list, so basically expands out to this:

firstFilter.apply(secondFilter.apply(thirdFilter.apply(action))))

因此,第一个过滤器是外部最过滤器,因此,当它得到回复时,它将从所有内层过滤器的内侧过滤器中接收,并由所有内层过滤器设定。





相关问题
How to flatten a List of different types in Scala?

I have 4 elements:List[List[Object]] (Objects are different in each element) that I want to zip so that I can have a List[List[obj1],List[obj2],List[obj3],List[obj4]] I tried to zip them and I ...

To use or not to use Scala for new Java projects? [closed]

I m impressed with Twitter and investigating to use Scala for a new large scale web project with Hibernate and Wicket. What do you think about Scala, and should I use it instead of Java? EDIT: And, ...

Why does Scala create a ~/tmp directory when I run a script?

When I execute a Scala script from the command line, a directory named "tmp" is created in my home directory. It is always empty, so I simply deleted it without any apparent problem. Of course, when I ...

Include jar file in Scala interpreter

Is it possible to include a jar file run running the Scala interpreter? My code is working when I compile from scalac: scalac script.scala -classpath *.jar But I would like to be able to include a ...

Scala and tail recursion

There are various answers on Stack Overflow which explain the conditions under which tail recursion is possible in Scala. I understand the limitations and how and where I can take advantage of tail ...

热门标签