最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

scala - zio-http, access to Request object inside of implementHandler - Stack Overflow

programmeradmin1浏览0评论

In ZIO http, I defined an Endpoint, and write an implementation. In the implementation, I need to access Request object, as shown in the toy example below:

object MyEndpoint extends ZIOAppDefault {
  private val myEndpoint =
    Endpoint(Method.GET / "my-endpoint").out[String]

  private val myEndpointHandler =
    myEndpoint.implementHandler(Handler.fromFunction { (request: Request) => // Compilation error
      "path: " + request.path
    })

  def run: ZIO[Any, Throwable, Any] =
    (Server.install(Routes(myEndpointHandler)) *> ZIO.never).provide(Server.default)
}

I know it is discouraged practice, but it is needed at least temporarily during migration.

[EDIT] I managed to write implementations of Endpoint with access to Request, as shown below. But the implementation of implementWith is not satisfactory. Is there a better way to do it?

  extension [PathInput, Input, Err, Output, Auth <: AuthType](endPoint: Endpoint[PathInput, Input, Err, Output, Auth])
    def implementWith(f: Request => Input => Output) =
      zio.http.Route.handledIgnoreParams(endPoint.route)(handler { (req: Request) =>
        endPoint.implementHandler(Handler.fromFunction(f(req))).apply(req)
      })

  private val myEndpImpl = myEndpoint.implementWith((req: Request) => Unit => s"myEndpoint  , requested from ${req.remoteAddress}")
发布评论

评论列表(0)

  1. 暂无评论