[英]How to compose an effect with an Http4s HttpRoutes?
I have an http4s HttpRoutes
and a task in my effect type (ZIO, if that matters).我的效果类型中有一个 http4s
HttpRoutes
和一个任务(ZIO,如果这很重要)。 The effect is side-effecting and returns no value.效果是副作用,不返回任何值。 I want to compose the two together, creating a new
HttpRoutes
that will run the effect before any matching route in the HttpRoutes
.我想将两者组合在一起,创建一个新的
HttpRoutes
,它将在HttpRoutes
中的任何匹配路由之前运行效果。
import zio.Task
val httpRoutes: HttpRoutes[Task] = ...
val effect: Task[Unit] = ...
val combined: HttpRoutes[Task] = ???
How do I combine the HttpRoutes
and the effect together?如何将
HttpRoutes
和效果结合在一起?
Naive implementation according to https://http4s.org/v0.21/middleware根据https://http4s.org/v0.21/middleware 的幼稚实现
works for me为我工作
@accessible
trait HttpServer {
def bindHttp: UIO[Server[Task]]
}
object HttpServer {
def make(
httpRoutes: HttpRoutes[Task],
cpuPool: ExecutionContext@Id("zio.cpu"),
) = {
for {
implicit0(rts: Runtime[Any]) <- ZIO.runtime[Any].toManaged_
combined = Kleisli { (req: Request[Task]) =>
val effect: Task[Unit] = Task.effectTotal(println("123"))
OptionT.liftF(effect).flatMap { _ =>
httpRoutes(req)
}
}
srv <- BlazeServerBuilder[Task](cpuPool)
.withHttpApp(combined.orNotFound)
.bindHttp(host = "0.0.0.0")
.resource
.toManaged
} yield new HttpServer {
val bindHttp = IO.succeed(srv)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.