Last active
March 18, 2021 21:28
-
-
Save loicdescotte/20b0a8bf0b7b05840073909717bdeb8d to your computer and use it in GitHub Desktop.
ZIO HTTP basic example
This file contains 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 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