【发布时间】:2020-09-17 09:49:54
【问题描述】:
我正在 scala 中重写一些应用程序层代码,从使用 scalaj 到 akka-http 为了减少项目中第三方依赖的数量(我们已经在同一个项目中将akka用于其他事情。)代码只是将常见类型的请求包装到库提供的底层通用请求中
大部分情况下都很好,但我被困在可选地向请求中添加代理的问题上。
请求应该直接到达目的地或通过代理,由运行时的参数确定。
在我的 scalaj 实现中,我有以下帮助程序类和方法
object HttpUtils {
private def request(
host: Host,
method: HttpMethod,
params: Map[String, String],
postData: Option[String],
timeout: Duration,
headers: Seq[(String, String)],
proxy: Option[ProxyConfig]
): HttpResponse[String] = {
// most general request builder. Other methods in the object fill in parameters and wrap this in a Future
val baseRequest = Http(host.url)
val proxiedRequest = addProxy(proxy, baseRequest)
val fullRequest = addPostData(postData)(proxiedRequest)
.method(method.toString)
.params(params)
.headers(headers)
.option(HttpOptions.connTimeout(timeout.toMillis.toInt))
.option(HttpOptions.readTimeout(timeout.toMillis.toInt))
fullRequest.asString // scalaj for send off request and block until response
}
// Other methods ...
private def addProxy(proxy: Option[ProxyConfig], request: HttpRequest): HttpRequest =
proxy.fold(request)((p: ProxyConfig) => request.proxy(p.host, p.port))
}
case class ProxyConfig(host: String, port: Int)
有没有办法用 akka-http 构建类似的结构?
【问题讨论】: