Skip to content

Commit 28020c2

Browse files
sotexsolymroz3x178inaba
authored
The directory path does not end with '/', it needs to be redirected (#1572)
* The directory path does not end with '/', it needs to be redirected * changed guide highlighting to shell (#1593) * Fix recover print stack trace log level (#1604) * Fix recover print stack trace log level * Add recover log level test * Add default LogLevel to DefaultRecoverConfig Co-authored-by: solym <[email protected]> Co-authored-by: roz3x <[email protected]> Co-authored-by: Masahiro Furudate <[email protected]>
1 parent 6463bcb commit 28020c2

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

echo.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ import (
4848
"net"
4949
"net/http"
5050
"net/url"
51+
"os"
5152
"path"
5253
"path/filepath"
5354
"reflect"
@@ -479,7 +480,20 @@ func (common) static(prefix, root string, get func(string, HandlerFunc, ...Middl
479480
if err != nil {
480481
return err
481482
}
483+
482484
name := filepath.Join(root, path.Clean("/"+p)) // "/"+ for security
485+
fi, err := os.Stat(name)
486+
if err != nil {
487+
// The access path does not exist
488+
return NotFoundHandler(c)
489+
}
490+
491+
// If the request is for a directory and does not end with "/"
492+
p = c.Request().URL.Path // path must not be empty.
493+
if fi.IsDir() && p[len(p)-1] != '/' {
494+
// Redirect to ends with "/"
495+
return c.Redirect(http.StatusMovedPermanently, p+"/")
496+
}
483497
return c.File(name)
484498
}
485499
if prefix == "/" {

echo_test.go

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,19 +76,28 @@ func TestEchoStatic(t *testing.T) {
7676

7777
// Directory
7878
e.Static("/images", "_fixture/images")
79-
c, _ = request(http.MethodGet, "/images", e)
79+
c, _ = request(http.MethodGet, "/images/", e)
8080
assert.Equal(http.StatusNotFound, c)
8181

82+
// Directory Redirect
83+
e.Static("/", "_fixture")
84+
req := httptest.NewRequest(http.MethodGet, "/folder", nil)
85+
rec := httptest.NewRecorder()
86+
e.ServeHTTP(rec, req)
87+
assert.Equal(http.StatusMovedPermanently, rec.Code)
88+
assert.Equal("/folder/", rec.HeaderMap["Location"][0])
89+
8290
// Directory with index.html
8391
e.Static("/", "_fixture")
8492
c, r := request(http.MethodGet, "/", e)
8593
assert.Equal(http.StatusOK, c)
8694
assert.Equal(true, strings.HasPrefix(r, "<!doctype html>"))
8795

8896
// Sub-directory with index.html
89-
c, r = request(http.MethodGet, "/folder", e)
97+
c, r = request(http.MethodGet, "/folder/", e)
9098
assert.Equal(http.StatusOK, c)
9199
assert.Equal(true, strings.HasPrefix(r, "<!doctype html>"))
100+
92101
}
93102

94103
func TestEchoFile(t *testing.T) {

0 commit comments

Comments
 (0)