我试图确保服务器的所有响应都通过GZIP进行编码/压缩。它适用于已定义的路径,但我无法弄清楚如何为“已拒绝”路径实现相同的目的。
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.coding.Gzip
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import scala.concurrent.Await
import scala.concurrent.duration.Duration
object Test extends App {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
val route =
encodeResponseWith(Gzip) {
path("hello") {
get {
complete(HttpEntity(ContentTypes.`text/plain(UTF-8)`, "world"))
}
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
Await.result(bindingFuture, Duration.Inf)
}
响应(找到路线时压缩)
http http://localhost:8080/hello
HTTP/1.1 200 OK
Content-Encoding: gzip
Content-Type: text/plain; charset=UTF-8
Date: Fri, 27 May 2016 17:54:40 GMT
Server: akka-http/2.4.6
Transfer-Encoding: chunked
world
响应(未找到路线时未压缩 - AKA被拒绝)
http http://localhost:8080/hell0
HTTP/1.1 404 Not Found
Content-Length: 42
Content-Type: text/plain; charset=UTF-8
Date: Fri, 27 May 2016 17:57:50 GMT
Server: akka-http/2.4.6
The requested resource could not be found.
更新
即使使用RejectionHandler,响应也不会受到影响。
implicit def myRejectionHandler = RejectionHandler.newBuilder()
.handleNotFound {
encodeResponseWith(Gzip) {
complete((NotFound, "Not here!"))
}
}.result()
产量
HTTP/1.1 404 Not Found
Content-Length: 9
Content-Type: text/plain; charset=UTF-8
Date: Fri, 27 May 2016 18:10:47 GMT
Server: akka-http/2.4.6
Not here!
答案 0 :(得分:0)
您需要定义隐式RejectionHandler
,如official documentation
implicit def myRejectionHandler = RejectionHandler.newBuilder()
.handleNotFound {
encodeResponseWith(Gzip) {
complete((NotFound, "Not here!"))
}
}.result()