[Http4s Project 3] How to define secondary routes?

Question:

We have a server with a route name welcome. How to make it a second route and make root route path called sprint?

object Main {
  def main(args: Array[String]): Unit = {

    (for {
      serverExecutionContext <- IO(
        ExecutionContext.fromExecutor(Executors.newFixedThreadPool(1))
      )
      routes = HttpRoutes.of [IO] {
        case GET -> Root / "welcome" / user =>
          Ok(s"Welcome, ${user}")
      }
      serverIO <- BlazeServerBuilder[IO]
        .withExecutionContext(serverExecutionContext)
        .withIdleTimeout(180.seconds)
        .bindHttp(port = 8080, host = "0.0.0.0")
        .withHttpApp(routes.orNotFound)
        .serve
        .compile
        .drain
    } yield serverIO).unsafeRunSync()
  }
}

Extract HttpRoutes.of method and wrapped with Route:

WelcomeService.scala

class WelcomeService[M[_] : Async]() extends Http4sDsl[M] {
  def service: HttpRoutes[M] = HttpRoutes.of {
    case GET -> Root / "welcome" / user =>
      welcome(Some(user))
  }

  def welcome[M[_] : Sync](req: Option[String]): M[Response[M]] = {
    (for {
      _ <- Sync[M].raiseError(TMError("User is Jason", IntentionError)).whenA(req.contains("Jason"))
      user = req.map(username => s"Welcome, $username").getOrElse("No user provided")
    } yield user).attempt.map(x => x.leftMap(_.toTMError)).flatMap[TMErrorEither[String]] ({
      case Left(e) => Sync[M].delay {
        println(e);
        Left(e)
      }
      case value => Sync[M].pure(value)
    })
      .toResponse
  }
}

Main.scala

object Main {
  def main(args: Array[String]): Unit = {

    (for {
      serverExecutionContext <- IO(
        ExecutionContext.fromExecutor(Executors.newFixedThreadPool(1))
      )
      serverIO <- BlazeServerBuilder[IO]
        .withExecutionContext(serverExecutionContext)
        .withIdleTimeout(180.seconds)
        .bindHttp(port = 8080, host = "0.0.0.0")
        .withHttpApp(Router("sprint" -> new WelcomeService[IO]().service).orNotFound)
        .serve
        .compile
        .drain
    } yield serverIO).unsafeRunSync()
  }
}
Last updated: 2024-04-14 05:30:01Scala/HTTP4s/Cats
Author:Chaolocation:https://www.baidu.com/article/29
Comments
Submit
Be the first one to write a comment ~