Skip to content

Commit

Permalink
fix data race while set prefix (swaggo#125)
Browse files Browse the repository at this point in the history
fix data race in gin handler
  • Loading branch information
lewisay authored Nov 3, 2020
1 parent 06d1cc7 commit 0e6b4ac
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
)

Expand Down Expand Up @@ -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.
)

Expand All @@ -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()
Expand Down
7 changes: 7 additions & 0 deletions swagger.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"regexp"
"strings"
"sync"

"golang.org/x/net/webdav"

Expand Down Expand Up @@ -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) {

Expand All @@ -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")
Expand All @@ -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()
}
}
}
Expand Down

0 comments on commit 0e6b4ac

Please sign in to comment.