fix: use ginSwagger.WrapHandler for correct path routing
Some checks failed
CI / Build & Test (push) Has been cancelled

This commit is contained in:
MengStack Dev 2026-10-03 04:12:15 +08:00
parent 42527b616d
commit df30ea5c33

View File

@ -10,22 +10,23 @@ import (
"strconv" "strconv"
"strings" "strings"
swaggerFiles "github.com/swaggo/files"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
ginSwagger "github.com/swaggo/gin-swagger"
swaggerFiles "github.com/swaggo/files"
) )
func SwaggerHandler() gin.HandlerFunc { func SwaggerHandler() gin.HandlerFunc {
return func(c *gin.Context) { wrapHandler := ginSwagger.WrapHandler(swaggerFiles.Handler)
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 }()
return func(c *gin.Context) {
relPath := strings.TrimPrefix(c.Request.URL.Path, "/swagger")
isCSS := strings.HasSuffix(relPath, "swagger-ui.css") isCSS := strings.HasSuffix(relPath, "swagger-ui.css")
if !isCSS {
wrapHandler(c)
return
}
underlying := c.Writer underlying := c.Writer
crw := &captureResponseWriter{ crw := &captureResponseWriter{
ginWriter: underlying, ginWriter: underlying,
@ -33,7 +34,7 @@ func SwaggerHandler() gin.HandlerFunc {
} }
c.Writer = crw c.Writer = crw
swaggerFiles.Handler.ServeHTTP(crw, c.Request) wrapHandler(c)
c.Writer = underlying c.Writer = underlying
@ -44,7 +45,7 @@ func SwaggerHandler() gin.HandlerFunc {
h.Set("Referrer-Policy", "strict-origin-when-cross-origin") 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:") 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)...) body := append(crw.buf.Bytes(), []byte(brandingCSS)...)
h.Set("Content-Length", strconv.Itoa(len(body))) h.Set("Content-Length", strconv.Itoa(len(body)))
h.Set("Content-Type", "text/css; charset=utf-8") h.Set("Content-Type", "text/css; charset=utf-8")
@ -58,7 +59,6 @@ func SwaggerHandler() gin.HandlerFunc {
if ct := mime.TypeByExtension(ext); ct != "" { if ct := mime.TypeByExtension(ext); ct != "" {
h.Set("Content-Type", ct) h.Set("Content-Type", ct)
} }
h.Del("Content-Length")
underlying.WriteHeader(crw.code) underlying.WriteHeader(crw.code)
underlying.Write(crw.buf.Bytes()) underlying.Write(crw.buf.Bytes())
return return