Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package sttp.tapir.examples
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Route
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import scala.io.StdIn
object HelloWorldAkkaServer extends App {
implicit val actorSystem: ActorSystem = ActorSystem()
import actorSystem.dispatcher
// tapir route
val helloWorldRoute: Route = {
import sttp.tapir._
import sttp.tapir.server.akkahttp.AkkaHttpServerInterpreter
val helloWorld: PublicEndpoint[String, Unit, String, Any] =
endpoint.get.in("hello").in(query[String]("name")).out(stringBody)
AkkaHttpServerInterpreter().toRoute(helloWorld.serverLogicSuccess(name => Future.successful(s"Hello, $name!")))
}
// direct akka http route
val helloWorldRoute2: Route = {
import akka.http.scaladsl.server.Directives._
get {
path("hello2") {
parameter("name".as[String]) { name =>
complete(s"Hello, $name!")
}
}
}
}
// combining the two routes
val combinedRoutes = {
import akka.http.scaladsl.server.Directives._
helloWorldRoute ~ helloWorldRoute2
}
// running the server
val bind = Http().newServerAt("localhost", 8080).bindFlow(combinedRoutes)
StdIn.readLine()
Await.result(bind.transformWith { r => actorSystem.terminate().transform(_ => r) }, 1.minute)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment