Skip to content

Instantly share code, notes, and snippets.

@adamw
Created September 16, 2022 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamw/fd3f0c974af00b8f3372a803e09374b8 to your computer and use it in GitHub Desktop.
Save adamw/fd3f0c974af00b8f3372a803e09374b8 to your computer and use it in GitHub Desktop.
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