如何使用 Http4s HttpRoutes 组合效果?

How to compose an effect with an Http4s HttpRoutes?

我有一个 http4s HttpRoutes 和一个在我的效果类型中的任务(ZIO,如果重要的话)。效果是副作用,returns 没有价值。我想将两者组合在一起,创建一个新的 HttpRoutes,它将 运行 在 HttpRoutes.

中的任何匹配路由之前产生效果
import zio.Task

val httpRoutes: HttpRoutes[Task] = ...
val effect: Task[Unit] = ...

val combined: HttpRoutes[Task] = ???

如何将 HttpRoutes 和效果组合在一起?

根据 https://http4s.org/v0.21/middleware

的简单实现

适合我

@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)
    }
  }
}