Skip to content

Instantly share code, notes, and snippets.

@loicdescotte
Last active March 18, 2021 21:28
Show Gist options
  • Save loicdescotte/20b0a8bf0b7b05840073909717bdeb8d to your computer and use it in GitHub Desktop.
Save loicdescotte/20b0a8bf0b7b05840073909717bdeb8d to your computer and use it in GitHub Desktop.
ZIO HTTP basic example
import zio._
import zhttp.http._
import zhttp.http.HttpError.InternalServerError
import zhttp.service.Server
import zio.clock.Clock
import java.time.DateTimeException
object HelloWorld extends App {
val app = Http.collectM[Request] {
case Method.GET -> Root / "hello" =>
HelloWorldService.helloWorld.fold({
//error case(s) :
case dateTimeError: DateTimeException =>
Response.fromHttpError(InternalServerError("Internal error : " + dateTimeError.getMessage))
},
// success case :
message => Response.text(message)
)
// you can add more routes here :
// case Method.GET -> Root / "fruits" => ...
}
override def run(args: List[String]) = {
val serverIO = Server.start(8090, app).provideLayer(Clock.live) // <- bind clock implementation
serverIO.exitCode
}
}
object HelloWorldService {
val clock = ZIO.access[Clock](_.get) // <- dependency injection : can use Clock.live, or a fake clock for tests
def helloWorld: ZIO[Clock, DateTimeException, String] =
for {
c <- clock
time <- c.localDateTime
} yield s"Hello world, the current date is $time"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment