Skip to content

Commit

Permalink
lib/memfs: trim trailing slash ("/") in the path of Get method
Browse files Browse the repository at this point in the history
The MemFS always store directory without slash.
If caller request a directory node with slash, it will always return nil.
  • Loading branch information
shuLhan committed Mar 21, 2024
1 parent e892d3a commit 547c4b5
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 8 deletions.
20 changes: 12 additions & 8 deletions lib/http/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -345,24 +345,20 @@ func (srv *Server) Stop(wait time.Duration) (err error) {
// [ServerOptions.EnableIndexHTML] is true, server will generate list of
// content for index.html.
func (srv *Server) getFSNode(reqPath string) (node *memfs.Node, isDir bool) {
var (
nodeIndexHTML *memfs.Node
pathHTML string
err error
)

if srv.Options.Memfs == nil {
return nil, false
}

pathHTML = path.Join(reqPath, `index.html`)
var err error

node, err = srv.Options.Memfs.Get(reqPath)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
return nil, false
}

var pathHTML = path.Join(reqPath, `index.html`)

node, err = srv.Options.Memfs.Get(pathHTML)
if err != nil {
pathHTML = reqPath + `.html`
Expand All @@ -375,16 +371,24 @@ func (srv *Server) getFSNode(reqPath string) (node *memfs.Node, isDir bool) {
}

if node.IsDir() {
var (
pathHTML = path.Join(reqPath, `index.html`)
nodeIndexHTML *memfs.Node
)

nodeIndexHTML, err = srv.Options.Memfs.Get(pathHTML)
if err == nil {
return nodeIndexHTML, true
return nodeIndexHTML, false
}

if !srv.Options.EnableIndexHTML {
return nil, false
}

node.GenerateIndexHTML()

// Do not return isDir=true, to prevent the caller check and
// redirect the user to path with slash.
}

return node, false
Expand Down
3 changes: 3 additions & 0 deletions lib/memfs/memfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,9 @@ func (mfs *MemFS) Get(path string) (node *Node, err error) {
if len(path) == 0 {
return nil, fmt.Errorf(`%s: empty path`, logp)
}
if path != `/` {
path = strings.TrimSuffix(path, `/`)
}

node = mfs.PathNodes.Get(path)
if node != nil {
Expand Down
2 changes: 2 additions & 0 deletions lib/memfs/memfs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,8 @@ func TestMemFS_Get(t *testing.T) {
},
}, {
path: "/include",
}, {
path: "/include/",
}, {
path: "/include/dir",
expErr: os.ErrNotExist.Error(),
Expand Down

0 comments on commit 547c4b5

Please sign in to comment.