Last active
November 16, 2025 02:02
-
-
Save vkostyukov/74e04736b74b0b43becbbaf05fa1afe5 to your computer and use it in GitHub Desktop.
TwitterServer-And-CatsEffect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 () | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
First of all, thanks for the example. However, I noticed that
ToEffectis changed toToAsync. Can you create a new revision?