akka-http:完整的请求流
假设我已经设置了一个任意复杂的Flow[HttpRequest, HttpResponse, Unit]
.
Assume I have set up an arbitrarily complex Flow[HttpRequest, HttpResponse, Unit]
.
我已经可以使用上述流程来处理传入的请求
I can already use said flow to handle incoming requests with
Http().bindAndHandle(flow, "0.0.0.0", 8080)
现在我想添加日志,利用一些现有的指令,比如 logRequestResult("my-service"){...}
有没有办法将此指令与我的流程结合起来?我想我正在寻找另一个指令,类似于
Now I would like to add logging, leveraging some existing directive, like logRequestResult("my-service"){...}
Is there a way to combine this directive with my flow? I guess I am looking for another directive, something along the lines of
def completeWithFlow(flow: Flow): Route
这可能吗?
注意:logRequestResult 是一个例子,我的问题适用于任何可能有用的指令.
N.B.: logRequestResult is an example, my question applies to any Directive one might find useful.
事实证明,一种(也许是唯一的)方法是连接并具体化一个新流,并将提取的请求提供给它.下面的例子
Turns out one (and maybe the only) way is to wire and materialize a new flow, and feed the extracted request to it. Example below
val myFlow: Flow[HttpRequest, HttpResponse, NotUsed] = ???
val route =
get {
logRequestResult("my-service") {
extract(_.request) { req ⇒
val futureResponse = Source.single(req).via(myFlow).runWith(Sink.head)
complete(futureResponse)
}
}
}
Http().bindAndHandle(route, "127.0.0.1", 9000)