Created
April 15, 2021 07:56
-
-
Save adamw/18b1cecedd19403765b735e6532d743e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sttp.tapir.examples | |
import cats.effect._ | |
import cats.syntax.all._ | |
import org.http4s.HttpRoutes | |
import org.http4s.server.Router | |
import org.http4s.server.blaze.BlazeServerBuilder | |
import org.http4s.syntax.kleisli._ | |
import sttp.client3._ | |
import sttp.tapir._ | |
import sttp.tapir.server.http4s.{Http4sServerInterpreter, Http4sServerOptions} | |
import sttp.tapir.server.interceptor.decodefailure.DefaultDecodeFailureHandler | |
import sttp.tapir.server.interceptor.exception.DefaultExceptionHandler | |
import scala.concurrent.ExecutionContext | |
object TestHttp4sServer extends App { | |
val test: Endpoint[Int, Unit, Unit, Any] = endpoint.get.in("hello" / path[Int]("x")) | |
implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global | |
implicit val contextShift: ContextShift[IO] = IO.contextShift(ec) | |
implicit val timer: Timer[IO] = IO.timer(ec) | |
implicit val options: Http4sServerOptions[IO, IO] = Http4sServerOptions.customInterceptors[IO, IO]( | |
exceptionHandler = Some(DefaultExceptionHandler), | |
serverLog = Some(Http4sServerOptions.Log.defaultServerLog), | |
decodeFailureHandler = DefaultDecodeFailureHandler( | |
DefaultDecodeFailureHandler | |
.respond(_, badRequestOnPathErrorIfPathShapeMatches = true, badRequestOnPathInvalidIfPathShapeMatches = true), | |
DefaultDecodeFailureHandler.FailureMessages.failureMessage, | |
DefaultDecodeFailureHandler.failureResponse | |
) | |
) | |
val testRoute: HttpRoutes[IO] = Http4sServerInterpreter.toRoutes(test)(_ => IO(().asRight[Unit])) | |
BlazeServerBuilder[IO](ec) | |
.bindHttp(8080, "localhost") | |
.withHttpApp(Router("/" -> testRoute).orNotFound) | |
.resource | |
.use { _ => | |
IO { | |
val backend: SttpBackend[Identity, Any] = HttpURLConnectionBackend() | |
val result1 = basicRequest.response(asStringAlways).get(uri"http://localhost:8080/hello/123").send(backend) | |
println("Code 1: " + result1.code) | |
val result2 = basicRequest.response(asStringAlways).get(uri"http://localhost:8080/hello/abc").send(backend) | |
println("Code 2: " + result2.code) | |
} | |
} | |
.unsafeRunSync() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment