Skip to content

Instantly share code, notes, and snippets.

@frosforever
Created September 18, 2019 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frosforever/4974ca9c4c29f071857f11a03ecc2c1e to your computer and use it in GitHub Desktop.
Save frosforever/4974ca9c4c29f071857f11a03ecc2c1e to your computer and use it in GitHub Desktop.
Incrementing server using a different route for each request based on updating a `Ref`
import org.http4s.circe._
import org.http4s.dsl.io._
import org.http4s.implicits._
import org.http4s.server.blaze.BlazeServerBuilder
import org.http4s.{ HttpApp, HttpRoutes, Request }
import cats.data.Kleisli
import cats.effect._
import cats.effect.concurrent.Ref
import cats.implicits._
object IncrementingServer extends IOApp {
def ltRouteK(ref: Ref[IO, (Int, HttpApp[IO])]): HttpApp[IO] = Kleisli { request: Request[IO] =>
ref.access.flatMap {
case ((oldI, oldRoute), setter) =>
oldRoute.run(request)
.flatTap { _ =>
setter((oldI + 1, counterRoute(oldI + 1)))
}
}
}
def counterRoute(i: Int): HttpApp[IO] = HttpRoutes.of[IO] {
case GET -> Root / "tick" => Ok(s"This has been hit $i times")
}.orNotFound
override def run(args: List[String]): IO[ExitCode] = {
Ref[IO].of((0, counterRoute(0))).flatMap { ref =>
BlazeServerBuilder[IO]
.bindHttp(8080, "0.0.0.0")
.withHttpApp(ltRouteK(ref))
.serve //We want an infinite stream so the application doesn't terminate early
.compile
.drain
}.as(ExitCode.Success)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment