经过一番搜索,我结合Web Jars 和http4k 的静态路由实现了这一点。
文档的潜在查看者必须简单地访问/docs 路径,在该路径中他会被重定向到/docs/index.html?url=<path to Api description> 位置
-
index.html 是从 Web jar 提供的静态 Swagger UI 入口点。
-
url 查询参数告诉 swagger UI 从哪里获取 OpenApi 描述。
从 DX 的角度来看,我们有一个简单的 http4k 应用程序:
// path the OpenApi description will be exposed on
private const val API_DESCRIPTION_PATH = "/swagger.json"
fun app(): HttpHandler {
val api = contract {
renderer = OpenApi3(ApiInfo("Your API summary", "1.0"), Jackson)
descriptionPath = API_DESCRIPTION_PATH
// the actual API routes
routes += ...
}
return routes(
// the docs routes are not considered part of the API so we define them outside of the contract
swaggerUi(API_DESCRIPTION_PATH),
api
)
}
swaggerUi 处理程序实现如下
/**
* Exposes Swagger UI with /docs path as its entry point.
* @param descriptionPath absolute path to API description JSON. The UI will be configured to fetch it after load.
*/
fun swaggerUi(descriptionPath: String): RoutingHttpHandler = routes(
"docs" bind Method.GET to {
Response(Status.FOUND).header("Location", "/docs/index.html?url=$descriptionPath")
},
// For some reason the static handler does not work without "/" path prefix.
"/docs" bind static(Classpath("META-INF/resources/webjars/swagger-ui/3.25.2"))
)
我们还必须包含 swagger-ui webjar 作为我们的依赖项。这是一个 Gradle 指令:
implementation 'org.webjars:swagger-ui:3.25.2'
查看 webjars 网站了解 Maven(以及更多)指令。
请注意,swaggerUi 处理程序假定它绑定到整个服务的 / 根路径。不过,这很容易解决。