Skip to content

Instantly share code, notes, and snippets.

@bpholt
Created January 26, 2016 01:49
Show Gist options
  • Save bpholt/bf0588a5a0be1aae9010 to your computer and use it in GitHub Desktop.
Save bpholt/bf0588a5a0be1aae9010 to your computer and use it in GitHub Desktop.
package com.dwolla.http.finagle
import com.twitter.finagle.Http.Client
import com.twitter.finagle.http.{Method, Request, Response}
import com.twitter.finagle.loadbalancer.LoadBalancerFactory
import com.twitter.finagle.{Http, Service}
object FinagleHttpClient {
private def newService(dest: String): Service[Request, Response] = {
val modifiedStack = Http.Client.stack.insertAfter(LoadBalancerFactory.role, new HttpHostHeaderAppendingModule[Request, Response])
Client(stack = modifiedStack).newService(dest)
}
def apply(dest: String): FinagleHttpClient = new FinagleHttpClient(newService(dest))
}
package com.dwolla.http.finagle
import java.net.SocketAddress
import com.dwolla.http.finagle.HttpHostHeaderAppendingModule.toHostHeaderValue
import com.twitter.finagle.Stack.Role
import com.twitter.finagle.client.Transporter.EndpointAddr
import com.twitter.finagle.http.Request
import com.twitter.finagle.{Filter, ServiceFactory, Stack}
class HttpHostHeaderAppendingModule[Req <: Request, Rep] extends Stack.Module1[EndpointAddr, ServiceFactory[Req, Rep]] {
val role = Role("sets-host-header")
val description = "adds the Host header to the request"
def addHostHeaderWith(dest: EndpointAddr) = Filter.mk[Req, Rep, Req, Rep] { (req, svc) ⇒
req.headerMap.add("Host", toHostHeaderValue(dest.addr))
svc(req)
}
override def make(dest: EndpointAddr, next: ServiceFactory[Req, Rep]) = {
addHostHeaderWith(dest) andThen next
}
}
object HttpHostHeaderAppendingModule {
private val addrRegex = """/?(.+)""".r
def toHostHeaderValue(addr: SocketAddress): String = {
addr.toString match {
case addrRegex(inet) ⇒ inet
case _ ⇒ throw new RuntimeException(s"could not parse $addr")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment