Skip to content

Instantly share code, notes, and snippets.

@adamw
Created October 13, 2022 10:16
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/e0c289f38861cd31ec45f62a6028729c to your computer and use it in GitHub Desktop.
Save adamw/e0c289f38861cd31ec45f62a6028729c to your computer and use it in GitHub Desktop.
package sttp.tapir.examples
import cats.effect.{ExitCode, IO, IOApp}
import org.http4s.HttpRoutes
import org.http4s.blaze.server.BlazeServerBuilder
import org.http4s.server.Router
import sttp.model.{Part, StatusCode}
import sttp.model.headers.WWWAuthenticateChallenge
import sttp.tapir._
import sttp.tapir.generic.auto._
import sttp.tapir.examples.HelloWorldHttp4sServer.ec
import sttp.tapir.model.UsernamePassword
import sttp.tapir.server.http4s.Http4sServerInterpreter
import java.io.File
object X extends IOApp {
case class UploadFileForm(rows: Part[File])
def postFile: Endpoint[(UsernamePassword, UploadFileForm), Unit, StatusCode, StatusCode, Any] =
endpoint.post
.in("file")
.securityIn(
auth.basic[UsernamePassword](WWWAuthenticateChallenge.basic("example"))
)
.securityIn(multipartBody[UploadFileForm])
.errorOut(statusCode)
.out(statusCode)
.description("Persisting a file to the server.")
val postFileRoute: HttpRoutes[IO] =
Http4sServerInterpreter[IO]().toRoutes(
postFile
.serverSecurityLogicPure[Unit, IO] { case (usernamePassword, uploadFileForm) => Right(()) }
.serverLogicPure(_ => _ => Right(StatusCode.Ok))
)
override def run(args: List[String]): IO[ExitCode] = {
// starting the server
BlazeServerBuilder[IO]
.withExecutionContext(ec)
.bindHttp(8080, "localhost")
.withHttpApp(Router("/" -> postFileRoute).orNotFound)
.resource
.use { _ => IO.never }
.as(ExitCode.Success)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment