fix: use ginSwagger.WrapHandler for correct path routing
Some checks failed
CI / Build & Test (push) Has been cancelled
Some checks failed
CI / Build & Test (push) Has been cancelled
This commit is contained in:
parent
42527b616d
commit
df30ea5c33
@ -10,22 +10,23 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
swaggerFiles "github.com/swaggo/files"
|
||||
"github.com/gin-gonic/gin"
|
||||
ginSwagger "github.com/swaggo/gin-swagger"
|
||||
swaggerFiles "github.com/swaggo/files"
|
||||
)
|
||||
|
||||
func SwaggerHandler() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
rawPath := c.Request.URL.Path
|
||||
relPath := strings.TrimPrefix(rawPath, "/swagger")
|
||||
if relPath == "" || relPath == "/" {
|
||||
relPath = "/index.html"
|
||||
}
|
||||
c.Request.URL.Path = relPath
|
||||
defer func() { c.Request.URL.Path = rawPath }()
|
||||
wrapHandler := ginSwagger.WrapHandler(swaggerFiles.Handler)
|
||||
|
||||
return func(c *gin.Context) {
|
||||
relPath := strings.TrimPrefix(c.Request.URL.Path, "/swagger")
|
||||
isCSS := strings.HasSuffix(relPath, "swagger-ui.css")
|
||||
|
||||
if !isCSS {
|
||||
wrapHandler(c)
|
||||
return
|
||||
}
|
||||
|
||||
underlying := c.Writer
|
||||
crw := &captureResponseWriter{
|
||||
ginWriter: underlying,
|
||||
@ -33,7 +34,7 @@ func SwaggerHandler() gin.HandlerFunc {
|
||||
}
|
||||
c.Writer = crw
|
||||
|
||||
swaggerFiles.Handler.ServeHTTP(crw, c.Request)
|
||||
wrapHandler(c)
|
||||
|
||||
c.Writer = underlying
|
||||
|
||||
@ -44,7 +45,7 @@ func SwaggerHandler() gin.HandlerFunc {
|
||||
h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
|
||||
h.Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:")
|
||||
|
||||
if isCSS && crw.code == 200 && crw.buf.Len() > 0 {
|
||||
if crw.code == 200 && crw.buf.Len() > 0 {
|
||||
body := append(crw.buf.Bytes(), []byte(brandingCSS)...)
|
||||
h.Set("Content-Length", strconv.Itoa(len(body)))
|
||||
h.Set("Content-Type", "text/css; charset=utf-8")
|
||||
@ -58,7 +59,6 @@ func SwaggerHandler() gin.HandlerFunc {
|
||||
if ct := mime.TypeByExtension(ext); ct != "" {
|
||||
h.Set("Content-Type", ct)
|
||||
}
|
||||
h.Del("Content-Length")
|
||||
underlying.WriteHeader(crw.code)
|
||||
underlying.Write(crw.buf.Bytes())
|
||||
return
|
||||
|
||||
Loading…
Reference in New Issue
Block a user