我覆盖 SwaggerSupport 并提取 swagger 路线。
import cats.effect.Sync
import cats.implicits.catsSyntaxOptionId
import org.http4s.rho.RhoMiddleware
import org.http4s.rho.RhoRoute
import org.http4s.rho.bits.PathAST.PathMatch
import org.http4s.rho.bits.PathAST.TypedPath
import org.http4s.rho.swagger.DefaultSwaggerFormats
import org.http4s.rho.swagger.SwaggerSupport
import org.http4s.rho.swagger.models._
import shapeless._
import scala.collection.immutable.Seq
import scala.reflect.runtime.universe._
object CustomSwaggerSupport {
def apply[F[_]: Sync](implicit etag: WeakTypeTag[F[_]]): CustomSwaggerSupport[F] = new CustomSwaggerSupport[F] {}
}
abstract class CustomSwaggerSupport[F[_]](implicit F: Sync[F], etag: WeakTypeTag[F[_]]) extends SwaggerSupport[F] {
/**
* Create a RhoMiddleware adding a route to get the Swagger json file
* representing the full API
*/
def createRhoMiddlewares: (RhoMiddleware[F], RhoMiddleware[F]) =
({ routes => routes }, { routes =>
lazy val swaggerSpec: Swagger =
createSwagger(
swaggerFormats = DefaultSwaggerFormats,
apiInfo = Info(
title = "API",
version = "1.0.0"
),
host = None,
basePath = "/".some,
schemes = List(Scheme.HTTP),
consumes = Nil,
produces = Nil,
security = List(SecurityRequirement("bearer", List())),
securityDefinitions = Map(
"bearer" -> ApiKeyAuthDefinition("Authorization", In.HEADER)
),
tags = Nil,
vendorExtensions = Map.empty
)(
routes
)
lazy val swaggerRoute: Seq[RhoRoute[F, _ <: HList]] =
createSwaggerRoute(swaggerSpec, TypedPath(PathMatch("swagger.json"))).getRoutes
swaggerRoute
})
}
然后我像这样使用它:
// Create a middleware that will transform RhoService into HttpService with attached Swagger definition
val (swaggerMiddleware, swaggerRoutes): (RhoMiddleware[IO], RhoMiddleware[IO]) = CustomSwaggerSupport
.apply[IO]
.createRhoMiddlewares
lazy val protectedRoutes: HttpRoutes[IO] =
routes.toRoutes(swaggerRoutes) <+> authMiddleware
.apply(Auth.toService(routes.toRoutes(swaggerMiddleware)))