swaggo / gin-swagger

gin middleware to automatically generate RESTful API documentation with Swagger 2.0.
MIT License
3.66k stars 266 forks source link

Serve Swagger UI on custom route without path or path extensions #284

Open bmeverett opened 9 months ago

bmeverett commented 9 months ago

I would like to be able to serve the swagger UI on a route like /docs or /swagger without having to provide the full path and extension /swagger/index.html. Is there currently a way to do this or something that could be supported?

juampiq6 commented 7 months ago

Hey! I was having the same issue declaring a custom route. I did manage to create a partial solution.

func setupSwagger(e *gin.Engine) {
    e.GET("/swagger", func(ctx *gin.Context) {
        ctx.Redirect(http.StatusPermanentRedirect, "/swagger/index.html")
    })
    e.GET("/docs/*any", func(ctx *gin.Context) {
        ctx.Redirect(http.StatusPermanentRedirect, "/swagger/index.html")
    })
    e.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))
}

I declared some routes where you can redirect to the main swagger assets handler to serve the request. So with this hack if you request /swagger, /docs, /docs/ or even /docs/adsasdfasdf that will perfectly redirect to the main swagger handler correctly /swagger/index.html. The only case i couldnt not solve was /swagger/ because this case is handled by the swagger wildcard route and the ginSwagger.WrapHandler cannot resolve any asset to serve from that route so it responds with 404. Note that this is a hack and a better solution to serve these files could be implemented in this library, but maybe not that neccessary