Search code examples
proxyhostfinagle

Using Finagle's clientbuilder, how do I set the host externally?


I am building a simple proxy to point to another server. Everything works but I need to find a way to be able to set the hosts in a ClientBuilder externally most likely using Docker or maybe some sort of configuration file. Here is what I have:

import java.net.InetSocketAddress
import com.twitter.finagle.Service
import com.twitter.finagle.builder.{ServerBuilder, ClientBuilder}
import com.twitter.finagle.http.{Request, Http}
import com.twitter.util.Future
import org.jboss.netty.handler.codec.http._

object Proxy extends App {

  val client: Service[HttpRequest, HttpResponse] = {
  ClientBuilder()
    .codec(Http())
    .hosts("localhost:8888")
    .hostConnectionLimit(1)
    .build()
  }

  val server = {
    ServerBuilder()
      .codec(Http())
      .bindTo(new InetSocketAddress(8080))
      .name("TROGDOR")
      .build(client)
  }
}

If you know of a way to do this or have any ideas about it please let me know!


Solution

  • if you want running this simple proxy in a docker container and manage the target host ip dynamically, you can try to pass a target host ip through environment variable and change your code like this

    import java.net.InetSocketAddress
    import com.twitter.finagle.Service
    import com.twitter.finagle.builder.{ServerBuilder, ClientBuilder}
    import com.twitter.finagle.http.{Request, Http}
    import com.twitter.util.Future
    import org.jboss.netty.handler.codec.http._
    
    object Proxy extends App {
      val target_host = sys.env.get("TARGET_HOST")
    
      val client: Service[HttpRequest, HttpResponse] = {
      ClientBuilder()
        .codec(Http())
        .hosts(target_host.getOrElse("127.0.0.1:8888"))
        .hostConnectionLimit(1)
        .build()
      }
    
      val server = {
        ServerBuilder()
          .codec(Http())
          .bindTo(new InetSocketAddress(8080))
          .name("TROGDOR")
          .build(client)
      }
    }
    

    this will let your code read system environment variable TARGET_HOST. when you done this part, you can try to start your docker container by adding the following parameter to your docker run command:

    -e "TARGET_HOST=127.0.0.1:8090"

    for example docker run -e "TARGET_HOST=127.0.0.1:8090" <docker image> <docker command>

    note that you can change 127.0.0.1:8090 to your target host.