first commit
This commit is contained in:
60
pkg/swaggerui/initializer.go
Normal file
60
pkg/swaggerui/initializer.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package swaggerui
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
swaggerFiles "github.com/swaggo/files"
|
||||
ginSwagger "github.com/swaggo/gin-swagger"
|
||||
)
|
||||
|
||||
const initializerJS = `window.onload = function() {
|
||||
const ui = SwaggerUIBundle({
|
||||
url: "doc.json",
|
||||
dom_id: '#swagger-ui',
|
||||
validatorUrl: null,
|
||||
persistAuthorization: true,
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIStandalonePreset
|
||||
],
|
||||
plugins: [
|
||||
SwaggerUIBundle.plugins.DownloadUrl
|
||||
],
|
||||
layout: "StandaloneLayout",
|
||||
docExpansion: "list",
|
||||
deepLinking: true,
|
||||
defaultModelsExpandDepth: 1,
|
||||
requestInterceptor: function(request) {
|
||||
const auth = request.headers.Authorization || request.headers.authorization
|
||||
|
||||
if (typeof auth === 'string') {
|
||||
const trimmed = auth.trim()
|
||||
|
||||
if (trimmed !== '' && !/^Bearer\s+/i.test(trimmed)) {
|
||||
request.headers.Authorization = 'Bearer ' + trimmed
|
||||
}
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
})
|
||||
|
||||
window.ui = ui
|
||||
}
|
||||
`
|
||||
|
||||
// Handler serves Swagger UI and overrides the initializer script to prefix raw tokens with Bearer.
|
||||
func Handler() gin.HandlerFunc {
|
||||
defaultHandler := ginSwagger.WrapHandler(swaggerFiles.Handler, ginSwagger.PersistAuthorization(true))
|
||||
|
||||
return func(c *gin.Context) {
|
||||
if strings.HasSuffix(c.Request.URL.Path, "/swagger-initializer.js") {
|
||||
c.Data(http.StatusOK, "application/javascript", []byte(initializerJS))
|
||||
return
|
||||
}
|
||||
|
||||
defaultHandler(c)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user