Skip to content

Commit 1b6744c

Browse files
authored
Merge pull request #328 from illionillion/fix/swagger-index-html-direct-response
fix: return index.html for /swagger and /swagger/ instead of 404
2 parents 2b8554d + 0edc920 commit 1b6744c

3 files changed

Lines changed: 17 additions & 1 deletion

File tree

.github/workflows/ci.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ jobs:
1515
steps:
1616
- uses: actions/checkout@master
1717
- name: Set up Go
18-
uses: actions/setup-go@v1
18+
uses: actions/setup-go@v4
1919
with:
2020
go-version: ${{ matrix.go }}
2121
- name: test

swagger.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,12 @@ func CustomWrapHandler(config *Config, handler *webdav.Handler) gin.HandlerFunc
159159
var matcher = regexp.MustCompile(`(.*)(index\.html|index\.css|swagger-initializer\.js|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)[?|.]*`)
160160

161161
return func(ctx *gin.Context) {
162+
// Return index.html content for /swagger or /swagger/
163+
if ctx.Request.Method == http.MethodGet && (ctx.Request.RequestURI == "/swagger" || ctx.Request.RequestURI == "/swagger/") {
164+
ctx.Header("Content-Type", "text/html; charset=utf-8")
165+
_ = index.Execute(ctx.Writer, config.toSwaggerConfig())
166+
return
167+
}
162168
if ctx.Request.Method != http.MethodGet {
163169
ctx.AbortWithStatus(http.StatusMethodNotAllowed)
164170

swagger_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,16 @@ func TestWrapCustomHandler(t *testing.T) {
8080
assert.Equal(t, http.StatusMethodNotAllowed, performRequest(http.MethodPost, "/index.html", router).Code)
8181

8282
assert.Equal(t, http.StatusMethodNotAllowed, performRequest(http.MethodPut, "/index.html", router).Code)
83+
84+
// Test: /swagger should redirect to /swagger/index.html (not implemented yet, should fail)
85+
w := performRequest(http.MethodGet, "/swagger", router)
86+
assert.Equal(t, http.StatusOK, w.Code)
87+
assert.Contains(t, w.Body.String(), "<title>Swagger UI</title>")
88+
89+
// Test: /swagger/ should also return index.html
90+
wSlash := performRequest(http.MethodGet, "/swagger/", router)
91+
assert.Equal(t, http.StatusOK, wSlash.Code)
92+
assert.Contains(t, wSlash.Body.String(), "<title>Swagger UI</title>")
8393
}
8494

8595
func TestDisablingWrapHandler(t *testing.T) {

0 commit comments

Comments
 (0)