Skip to content

Commit 0c8bf3f

Browse files
authored
add directory index feature (#56)
1 parent e12ffe8 commit 0c8bf3f

File tree

2 files changed

+11
-9
lines changed

2 files changed

+11
-9
lines changed

swagger.go

+8-9
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ var WrapHandler = EchoWrapHandler()
5555
func EchoWrapHandler(configFns ...func(c *Config)) echo.HandlerFunc {
5656
var once sync.Once
5757

58-
handler := swaggerFiles.Handler
58+
h := swaggerFiles.Handler
5959

6060
config := &Config{
6161
URL: "doc.json",
@@ -72,21 +72,20 @@ func EchoWrapHandler(configFns ...func(c *Config)) echo.HandlerFunc {
7272
t := template.New("swagger_index.html")
7373
index, _ := t.Parse(indexTemplate)
7474

75-
var re = 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)[?|.]*`)
75+
var re = regexp.MustCompile(`^(.*/)([^?].*)?[?|.]*$`)
7676

7777
return func(c echo.Context) error {
78-
var matches []string
79-
if matches = re.FindStringSubmatch(c.Request().RequestURI); len(matches) != 3 {
80-
return c.String(http.StatusNotFound, "404 page not found")
81-
}
78+
matches := re.FindStringSubmatch(c.Request().RequestURI)
8279
path := matches[2]
80+
8381
once.Do(func() {
84-
handler.Prefix = matches[1]
82+
h.Prefix = matches[1]
8583
})
8684

8785
defer c.Response().Flush()
88-
8986
switch path {
87+
case "":
88+
c.Redirect(301, h.Prefix+"index.html")
9089
case "index.html":
9190
_ = index.Execute(c.Response().Writer, config)
9291
case "doc.json":
@@ -100,7 +99,7 @@ func EchoWrapHandler(configFns ...func(c *Config)) echo.HandlerFunc {
10099
c.Response().Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
101100
_, _ = c.Response().Writer.Write([]byte(doc))
102101
default:
103-
handler.ServeHTTP(c.Response().Writer, c.Request())
102+
h.ServeHTTP(c.Response().Writer, c.Request())
104103
}
105104

106105
return nil

swagger_test.go

+3
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,7 @@ func TestWrapHandler(t *testing.T) {
235235

236236
router := echo.New()
237237

238+
//RegisterEchoHandler(router.GET, "/", nil)
238239
router.GET("/*", EchoWrapHandler(DocExpansion("none"), DomID("#swagger-ui")))
239240

240241
w1 := performRequest("GET", "/index.html", router)
@@ -253,6 +254,8 @@ func TestWrapHandler(t *testing.T) {
253254
w4 := performRequest("GET", "/notfound", router)
254255
assert.Equal(t, 404, w4.Code)
255256

257+
w5 := performRequest("GET", "/", router)
258+
assert.Equal(t, 301, w5.Code)
256259
}
257260

258261
func performRequest(method, target string, e *echo.Echo) *httptest.ResponseRecorder {

0 commit comments

Comments
 (0)