Skip to content

Instantly share code, notes, and snippets.

@d10xa
Created March 28, 2020 11:32
Show Gist options
  • Save d10xa/df1cb15b187da010c6108055a1a1a3bb to your computer and use it in GitHub Desktop.
Save d10xa/df1cb15b187da010c6108055a1a1a3bb to your computer and use it in GitHub Desktop.
http4s + AsyncHttpClient + proxy
import cats.effect.ContextShift
import cats.effect.IO
import cats.effect.Sync
import org.asynchttpclient.DefaultAsyncHttpClientConfig
import org.asynchttpclient.Realm
import org.asynchttpclient.proxy.ProxyServer
import org.asynchttpclient.proxy.ProxyType
import org.http4s._
import org.http4s.client._
import org.http4s.client.asynchttpclient.AsyncHttpClient
import org.http4s.implicits._
import org.http4s.util.threads.threadFactory
import scala.concurrent.ExecutionContext
object Http4sProxyExample {
implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global)
import io.circe.Codec
import io.circe.generic.semiauto.deriveCodec
import org.http4s.EntityDecoder
import org.http4s.circe.jsonOf
final case class IpResponse(origin: String)
object IpResponse {
implicit val codecIpResponse: Codec[IpResponse] = deriveCodec
implicit def userDecoder[F[_]: Sync]: EntityDecoder[F, IpResponse] =
jsonOf[F, IpResponse]
}
val baseUri: Uri = uri"https://httpbin.org"
def main(args: Array[String]): Unit = {
val config = new DefaultAsyncHttpClientConfig.Builder()
.setMaxConnectionsPerHost(200)
.setMaxConnections(400)
.setRequestTimeout(defaults.RequestTimeout.toMillis.toInt)
.setThreadFactory(threadFactory(name = { i: Long =>
s"http4s-async-http-client-worker-${i.toString}"
}))
.setProxyServer(
new ProxyServer.Builder("host", 8000)
.setProxyType(ProxyType.HTTP)
.setRealm(new Realm.Builder("principal", "password")
.setScheme(Realm.AuthScheme.BASIC)))
.build()
val _ = AsyncHttpClient.resource[IO](config).use(run).unsafeRunSync()
}
def run(client: Client[IO]): IO[Unit] = {
val request = Request[IO](
method = Method.GET,
uri = baseUri / "/ip",
headers = Headers.of(
Header(
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"))
)
client
.expect[IpResponse](request)
.map(_.origin)
.flatMap(s => IO(println(s)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment