gin-swagger icon indicating copy to clipboard operation
gin-swagger copied to clipboard

Serve Swagger UI on custom route without path or path extensions

Open bmeverett opened this issue 1 year ago • 1 comments

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?

bmeverett avatar Sep 25 '23 14:09 bmeverett

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

juampiq6 avatar Nov 17 '23 22:11 juampiq6