scala - Route akka-http request through a proxy -
i rewriting application layer code in scala using scalaj akka-http in order reduce number of third party dependencies in project (we use akka other things in same project.) code wraps common types of request underlying general request provided library
mostly has been fine, stuck on problem of optionally adding proxy request.
requests should either direct destination or via proxy, determined parameter @ runtime.
in scalaj implementation, have following helper class , methods
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] = { // general request builder. other methods in object fill in parameters , wrap in 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 send off request , 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)
is there way build similar construct akka-http?
akka http have proxy support that, of version 10.0.9, still unstable. keeping in mind api change, following handle optional proxy settings:
import java.net.inetsocketaddress import akka.actor.actorsystem import akka.stream.actormaterializer import akka.http.scaladsl.{clienttransport, http} implicit val system = actorsystem() implicit val materializer = actormaterializer() case class proxyconfig(host: string, port: int) val proxyconfig = option(proxyconfig("localhost", 8888)) val clienttransport = proxyconfig.map(p => clienttransport.httpsproxy(inetsocketaddress.createunresolved(p.host, p.port))) .getorelse(clienttransport.tcp) val settings = connectionpoolsettings(system).withtransport(clienttransport) http().singlerequest(httprequest(uri = "https://google.com"), settings = settings)
Comments
Post a Comment