经过一番搜索后,我结合了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'
有关 Maven(以及更多)指令,请参阅 webjars 网站。
请注意,swaggerUi
处理程序假定它绑定到/
整个服务的根路径。但是,这很容易解决。