com.http4s.rho.swagger.ui.SwaggerUiRoutes.scala Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of rho-swagger-ui_2.13 Show documentation
Show all versions of rho-swagger-ui_2.13 Show documentation
A self documenting DSL build upon the http4s framework
The newest version!
package com.http4s.rho.swagger.ui
import cats.effect.Sync
import cats.implicits._
import org.http4s.headers.`Content-Type`
import org.http4s.rho.RhoRoutes
import org.http4s.rho.bits.PathAST.CaptureTail
import org.http4s.rho.swagger.ui.BuildInfo
import org.http4s._
class SwaggerUiRoutes[F[_]: Sync](
swaggerUiPath: String,
swaggerUiResourcesPath: String,
indexHtml: String)
extends RhoRoutes[F] {
private val htmlEncoder: EntityEncoder[F, String] =
EntityEncoder
.stringEncoder()
.withContentType(`Content-Type`(MediaType.text.html).withCharset(org.http4s.Charset.`UTF-8`))
// Serving the html directly here would break all relative paths, so we redirect.
GET / swaggerUiPath |>> { req: Request[F] =>
PermanentRedirect(req.uri / "")
}
// The "" is the path that we normally want to use. The "index.html" is here to hide the "index.html" from the webjar.
GET / swaggerUiPath / ("" || "index.html") |>> { () =>
Ok(indexHtml)(implicitly, htmlEncoder)
}
GET / swaggerUiPath / CaptureTail |>> { (req: Request[F], path: List[String]) =>
fetchResource(swaggerUiResourcesPath + path.mkString("/", "/", ""), req)
}
private def fetchResource(path: String, req: Request[F]): F[Response[F]] =
StaticFile.fromResource[F](path, Some(req)).getOrElseF(NotFound(()).map(_.resp))
}
object SwaggerUiRoutes {
def apply[F[_]: Sync](
swaggerUiPath: String,
swaggerSpecRelativePath: String): SwaggerUiRoutes[F] = {
val swaggerUiResourcesPath =
s"/META-INF/resources/webjars/swagger-ui/${BuildInfo.swaggerUiVersion}/"
val indexHtml = defaultIndexHtml(swaggerSpecRelativePath)
new SwaggerUiRoutes[F](swaggerUiPath, swaggerUiResourcesPath, indexHtml)
}
def defaultIndexHtml(swaggerUrl: String): String =
s"""
|
|
|
|
|
| Swagger UI
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|""".stripMargin
}