gpt4 book ai didi

scala - Play 2.4 禁用基于请求路径或方法设置的某些过滤器

转载 作者:行者123 更新时间:2023-12-03 17:06:50 29 4
gpt4 key购买 nike

在 Play 2.3 中,我可以根据不同的请求路径或方法禁用某些过滤器。但是,我在 Play 2.4 中找不到方法。 https://www.playframework.com/documentation/2.4.x/ScalaHttpFilters .如何在 Play 2.4 HttpFilters 中获得类似的结果。

这是我在 Play 2.3 中的做法。

object CacheCtrlHeadersFilter extends EssentialFilter {
def apply(action: EssentialAction) = new EssentialAction {
def apply(requestHeader: RequestHeader) = {
action(requestHeader).map { result =>
result.withHeaders(
CACHE_CONTROL -> "no-cache, no-store, must-revalidate, private",
PRAGMA -> "no-cache"
)
}
}
}
}

import play.api.libs.iteratee._
object FilterChainByRequestHeader {
def apply[A](action: EssentialAction, filtersFun: (RequestHeader) => List[EssentialFilter]): EssentialAction = new EssentialAction {
def apply(rh: RequestHeader): Iteratee[Array[Byte], Result] = {
val chain = filtersFun(rh).reverse.foldLeft(action) { (a, i) => i(a) }
chain(rh)
}
}
}

object Global extends GlobalSettings {

val securityFilter = SecurityHeadersFilter()
val defaultFilters = List(securityFilter,
CacheCtrlHeadersFilter)

def filters(rh: RequestHeader) = {
if (rh.method == "OPTIONS") <----------- by method
defaultFilters.filterNot(_.eq(securityFilter))
else if (rh.path.startsWith("/apps/google")) <----------- by path
defaultFilters.filterNot(_.eq(securityFilter))
else defaultFilters
}
override def doFilter(a: EssentialAction): EssentialAction = {
FilterChainByRequestHeader(super.doFilter(a), filters)
}

}

Play 2.4 中的 HttpFilters 中没有可用的 RequestHeader
class Filters @Inject() (
securityHeadersFilter: SecurityHeadersFilter,
cacheCtrlHeadersFilter: CacheCtrlHeadersFilter
) extends HttpFilters {

val filters = Seq(securityHeadersFilter, cacheCtrlHeadersFilter)
}

最佳答案

object Global extends WithFilters(new CoreActionFilter()) {

}


class CoreActionFilter extends Filter {

lazy val serviceLogger = Logger("services")

def apply(nextFilter: RequestHeader => Future[Result])(requestHeader: RequestHeader) = {

nextFilter(requestHeader).map { result =>

val action = requestHeader.path match {
case "/favicon.ico" => s"[ ${requestHeader.remoteAddress.toString}]"
case _ => s"[ ${requestHeader.remoteAddress.toString}]" + ("[") + requestHeader.tags(Tags.RoutePattern) + ("]") + ("[") + requestHeader.tags(Tags.RouteController) + "." + requestHeader.tags(Tags.RouteActionMethod) + ("]")
}

val startTime = System.currentTimeMillis
val endTime = System.currentTimeMillis
val requestTime = endTime - startTime
val token = requestHeader.headers.get("X-Auth-Token")
serviceLogger.info(s"[$token]" + s"${action}[${requestTime}ms]" + s"[${result.header.status}]")
result.withHeaders("Request-Time" -> requestTime.toString)

}(CoreContexts.simpleSqlQuery)

}
}

关于scala - Play 2.4 禁用基于请求路径或方法设置的某些过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34431105/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com