SMILEY4 / ktor-swagger-ui

Kotlin Ktor plugin to generate OpenAPI and provide Swagger UI
Apache License 2.0
150 stars 25 forks source link

Setting custom rootHostPath in swagger context doesn't work properly #81

Closed s76527 closed 7 months ago

s76527 commented 7 months ago

Currently, since version 2.6.0, if i set a custom rootHostPath, it'll configure the routes wrong.

For example, I have an nginx configured to serve the Ktor application under http://my-domain.com/my-ktor-web-app and configured the Plugin like this:

swagger {
    swaggerUrl = "/api/swagger-ui"
    rootHostPath = "/my-ktor-web-app"
}

In this example Ktor will be told to serve the routes under /my-ktor-web-app/api/swagger-ui. In the end, to call the swagger UI page, i need to navigate to http://my-domain.com/my-ktor-web-app/my-ktor-web-app/api/swagger-ui which is not what i wanted.

To fix this issue, i suggest following changes in code (based on version 2.7.2; tested it with success with and without rootHostPath):

io.github.smiley4.ktorswaggerui.routing.SwaggerController

    private fun Route.setup() {
        route(getSubUrl()) {
            get {
                val rootHostPath = if (pluginConfig.swaggerUI.rootHostPath.isNotBlank()) {
                    ControllerUtils.dropSlashes("/${pluginConfig.swaggerUI.rootHostPath}")
                } else ""
                call.respondRedirect("$rootHostPath${call.request.uri}/index.html")
            }
            […]
        }
    }

    […]

    private fun getRootUrl(appConfig: ApplicationConfig): String {
        return "${ControllerUtils.getRootPath(appConfig)}${getSubUrl(true)}"
    }

    private fun getSubUrl(withRootHostPath: Boolean = false): String {
        return "/" + listOfNotNull(
            if (withRootHostPath) pluginConfig.swaggerUI.rootHostPath else null,
            pluginConfig.swaggerUI.swaggerUrl,
            specName
        )
            .filter { it.isNotBlank() }
            .map { ControllerUtils.dropSlashes(it) }
            .joinToString("/")
    }
SMILEY4 commented 7 months ago

Hi, thank you. I fixed the bug using your suggested changes in version 2.7.4