简体   繁体   中英

Migrating from Akka Http to Http4s - custom directives

I'm starting to learn Http4s, at work we may need to migrate Rest APIs implemented with Akka Http to Http4s.

As an example I can define a custom directive like this:

trait CustomDirectives {

  def extractUUID: Directive1[UUID] = {
    path(Segment).flatMap { maybeuuid =>
      Try(UUID.fromString(maybeuuid)) match {
        case Success(result) => provide(result)
        case Failure(_) =>
          complete(StatusCodes.BadRequest, s"Invalid uuid: $maybeuuid")
      }
    }
  }

}

So everytime I want to extract an UUID and validate it I can use this directive. We have other custom directives to make some processing on headers, and many more.

Is there anything similar to akka custom directives but in Http4s?

This is described inHandling Path Parameters section of the documentation

// standard Scala extractor, matching String against UUID
object UUIDVar {
  def unapply(maybeuuid: String): Option[UUID] =
    Try(UUID.fromString(maybeuuid)).toOption
}

val usersService = HttpRoutes.of[IO] {
  // just use extractor in pattern matching
  case GET -> Root / "users" / UUIDVar(uuid) =>
    Ok(useUUIDForSth(uuid))
}

However, personally, I find it easier to describe endpoints with libraries like Tapir or Endpoint4s since their DSL seem more intuitive to me and I am not coupling my code with a particular implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM