Skip to content

Commit

Permalink
The directory path does not end with '/', it needs to be redirected (#…
Browse files Browse the repository at this point in the history
…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]>
  • Loading branch information
4 people authored Aug 28, 2020
1 parent 6463bcb commit 28020c2
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
14 changes: 14 additions & 0 deletions echo.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import (
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
Expand Down Expand Up @@ -479,7 +480,20 @@ func (common) static(prefix, root string, get func(string, HandlerFunc, ...Middl
if err != nil {
return err
}

name := filepath.Join(root, path.Clean("/"+p)) // "/"+ for security
fi, err := os.Stat(name)
if err != nil {
// The access path does not exist
return NotFoundHandler(c)
}

// If the request is for a directory and does not end with "/"
p = c.Request().URL.Path // path must not be empty.
if fi.IsDir() && p[len(p)-1] != '/' {
// Redirect to ends with "/"
return c.Redirect(http.StatusMovedPermanently, p+"/")
}
return c.File(name)
}
if prefix == "/" {
Expand Down
13 changes: 11 additions & 2 deletions echo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,19 +76,28 @@ func TestEchoStatic(t *testing.T) {

// Directory
e.Static("/images", "_fixture/images")
c, _ = request(http.MethodGet, "/images", e)
c, _ = request(http.MethodGet, "/images/", e)
assert.Equal(http.StatusNotFound, c)

// Directory Redirect
e.Static("/", "_fixture")
req := httptest.NewRequest(http.MethodGet, "/folder", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
assert.Equal(http.StatusMovedPermanently, rec.Code)
assert.Equal("/folder/", rec.HeaderMap["Location"][0])

// Directory with index.html
e.Static("/", "_fixture")
c, r := request(http.MethodGet, "/", e)
assert.Equal(http.StatusOK, c)
assert.Equal(true, strings.HasPrefix(r, "<!doctype html>"))

// Sub-directory with index.html
c, r = request(http.MethodGet, "/folder", e)
c, r = request(http.MethodGet, "/folder/", e)
assert.Equal(http.StatusOK, c)
assert.Equal(true, strings.HasPrefix(r, "<!doctype html>"))

}

func TestEchoFile(t *testing.T) {
Expand Down

0 comments on commit 28020c2

Please sign in to comment.