scalafinch

How can I specify an IP address besides localhost?


I'm taking my first steps with Scala and Finch and working up a very simple rest API. Currently everything works properly, but I am unable to serve over anything besides "localhost" and there is no apparent way for me to specify it.

I've googled for the last hour and combed the docs but I cannot for the life of me determine how I'm meant to specify an IP address

object Main extends App with Endpoint.Module[IO] {
  val egService = new EgService
  val IPService = new IPService
  val hostIP = IPService.getIP

  def healthCheck: Endpoint[IO, String] = get(pathEmpty) { Ok("OK") }

  def helloWorld: Endpoint[IO, Message] = get("hello") {
    egService.getMessage().map(Ok)
  }

  def sayHello: Endpoint[IO, Message] = get("hello" :: path[String]) {
    s: String =>
      egService.getMessage(s).map(Ok)
  }

  def service: Service[Request, Response] =
    Bootstrap
      .serve[Text.Plain](healthCheck.handle {
        case e: Exception => InternalServerError(e)
      })
      .serve[Application.Json](helloWorld.handle {
        case e: Exception => InternalServerError(e)
      } :+: sayHello.handle {
        case e: Exception => InternalServerError(e)
      })
      .toService

  println(s"Trying to serve $hostIP on port 8080...")
  Await.ready(Http.server.serve(":8080", service))
}

As I said the above code works exactly as I expect it to, and I am able to curl localhost:8080 to get the appropriate responses but beyond that I'm stumped. I tried specifying:

Http.server.serve(s"$hostIP:8080", service)

But that seems to be ignored. Beyond that I am totally confused. When using http4s it's as simple as:

BlazeServerBuilder[IO]
  .bindHttp(8080, hostIP)

so I feel like I must be missing something obvious.


Solution

  • There is a serve variant that takes a SocketAddress. It won't resolve the hostname for you (as it seems to be done with http4s) so you'd need to pass it a resolved address.

    Http.server.serve(new java.net.InetSocketAddress("192.168.0.1", 8080), service)
    

    Note that by default, when you simply pass ":8081", the server will listen on all interfaces (including localhost).