Skip to content

Instantly share code, notes, and snippets.

@vkostyukov
Last active February 12, 2020 17:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vkostyukov/74e04736b74b0b43becbbaf05fa1afe5 to your computer and use it in GitHub Desktop.
Save vkostyukov/74e04736b74b0b43becbbaf05fa1afe5 to your computer and use it in GitHub Desktop.
TwitterServer-And-CatsEffect
import cats.effect.{ContextShift, IO, Resource, Timer}
import com.twitter.finagle.{Http, ListeningServer, Service}
import com.twitter.finagle.http.{Request, Response}
import com.twitter.server.TwitterServer
import com.twitter.util.Future
import io.finch.Endpoint
import io.finch.internal.ToEffect
import java.util.concurrent.CountDownLatch
import scala.concurrent.ExecutionContext
object Main extends TwitterServer {
protected implicit def contextShift: ContextShift[IO] =
IO.contextShift(ExecutionContext.global)
protected implicit def timer: Timer[IO] =
IO.timer(ExecutionContext.global)
final def main(): Unit = {
val latch = new CountDownLatch(1)
val cancel = run().unsafeRunCancelable {
case Right(_) => latch.countDown()
case Left(e) => exitOnError(e)
}
onExit {
cancel.unsafeRunSync()
latch.countDown()
}
latch.await()
}
def run(): IO[Unit] = {
def closeLater(l: ListeningServer): IO[Unit] =
IO.suspend(implicitly[ToEffect[Future, IO]].apply(l.close()))
def serve(s: Service[Request, Response]): Resource[IO, ListeningServer] =
Resource.make[IO, ListeningServer](
IO(Http.server.withStatsReceiver(statsReceiver).serve(":8081", s))
)(closeLater)
for {
_ <- IO(println("starting"))
_ <- serve(Endpoint[IO].const("Hello").toService[Text.Plain]).use(_ => IO.never)
} yield ()
}
}
@BranislavLazic
Copy link

First of all, thanks for the example. However, I noticed that ToEffect is changed to ToAsync. Can you create a new revision?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment