fix data race while set prefix (#125)

fix data race in gin handler
This commit is contained in:
Liu Yuan 2020-11-03 18:09:07 +08:00 committed by GitHub
parent 06d1cc765b
commit 0e6b4ac19e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 4 deletions

View File

@ -43,7 +43,7 @@ import (
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
_ "github.com/swaggo/gin-swagger/example/basic/docs" // docs is generated by Swag CLI, you have to import it.
)
@ -86,7 +86,7 @@ import (
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
_ "github.com/swaggo/gin-swagger/example/basic/docs" // docs is generated by Swag CLI, you have to import it.
)
@ -106,8 +106,8 @@ import (
// @BasePath /v2
func main() {
r := gin.New()
// use ginSwagger middleware to
// use ginSwagger middleware to
r.GET("/swagger/*any", ginSwagger.DisablingWrapHandler(swaggerFiles.Handler, "NAME_OF_ENV_VARIABLE"))
r.Run()

View File

@ -5,6 +5,7 @@ import (
"os"
"regexp"
"strings"
"sync"
"golang.org/x/net/webdav"
@ -54,6 +55,7 @@ func CustomWrapHandler(config *Config, h *webdav.Handler) gin.HandlerFunc {
index, _ := t.Parse(swagger_index_templ)
var rexp = regexp.MustCompile(`(.*)(index\.html|doc\.json|favicon-16x16\.png|favicon-32x32\.png|/oauth2-redirect\.html|swagger-ui\.css|swagger-ui\.css\.map|swagger-ui\.js|swagger-ui\.js\.map|swagger-ui-bundle\.js|swagger-ui-bundle\.js\.map|swagger-ui-standalone-preset\.js|swagger-ui-standalone-preset\.js\.map)[\?|.]*`)
var locker sync.RWMutex
return func(c *gin.Context) {
@ -70,7 +72,10 @@ func CustomWrapHandler(config *Config, h *webdav.Handler) gin.HandlerFunc {
}
path := matches[2]
prefix := matches[1]
locker.Lock()
h.Prefix = prefix
locker.Unlock()
if strings.HasSuffix(path, ".html") {
c.Header("Content-Type", "text/html; charset=utf-8")
@ -96,7 +101,9 @@ func CustomWrapHandler(config *Config, h *webdav.Handler) gin.HandlerFunc {
c.Writer.Write([]byte(doc))
return
default:
locker.RLock()
h.ServeHTTP(c.Writer, c.Request)
locker.RUnlock()
}
}
}