Created
March 1, 2019 07:45
-
-
Save Yyukan/7cd64e2534408b5ae746138b6c9bcc9b to your computer and use it in GitHub Desktop.
Http4s example with ZIO
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 | |
import scalaz.zio._ | |
import scalaz.zio.interop.catz._ | |
import org.http4s._ | |
import org.http4s.dsl.io._ | |
import org.http4s.implicits._ | |
import org.http4s.server.Router | |
import org.http4s.server.blaze.BlazeServerBuilder | |
import scalaz.zio.clock.Clock | |
import scala.concurrent.duration.{FiniteDuration, NANOSECONDS, TimeUnit} | |
object ZioDemo extends App { | |
implicit val ioTimer: effect.Timer[Task] = new effect.Timer[Task] { | |
override def clock: effect.Clock[Task] = new effect.Clock[Task] { | |
override def realTime(unit: TimeUnit): Task[Long] = | |
scalaz.zio.clock.currentTime(unit) | |
.provide(Clock.Live) | |
override def monotonic(unit: TimeUnit): Task[Long] = | |
scalaz.zio.clock.nanoTime.map(unit.convert(_, NANOSECONDS)) | |
.provide(Clock.Live) | |
} | |
override def sleep(duration: FiniteDuration): Task[Unit] = | |
scalaz.zio.clock.sleep(scalaz.zio.duration.Duration.fromNanos(duration.toNanos)) | |
.provide(Clock.Live) | |
} | |
def run(args: List[String]): ZIO[Environment, Nothing, Int] = { | |
def endpoints: HttpApp[Task] = { | |
def service = HttpRoutes.of[Task] { | |
case GET -> Root / "echo" / "ready" => Task(Response[Task](Status.Ok)) | |
case GET -> Root / "echo" / "alive" => Task(Response[Task](Status.Ok)) | |
} | |
Router("/" -> service).orNotFound | |
} | |
for { | |
config <- Configuration[Task].flatMapError(IO.die) | |
exitCode <- BlazeServerBuilder[Task] | |
.bindHttp(config.http.port, config.http.host) | |
.withHttpApp(endpoints).resource.use(_ => IO.never) | |
.either | |
.map(_.fold(_ => 1, _ => 0)) | |
} yield exitCode | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment