Skip to content

Commit

Permalink
Router: Route StaticFS() not found to Router's NoRoute() (#1663)
Browse files Browse the repository at this point in the history
Closes #1220
  • Loading branch information
MetalBreaker authored and appleboy committed Nov 26, 2018
1 parent 149ef75 commit b97ccf3
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
12 changes: 10 additions & 2 deletions routergroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,11 +185,19 @@ func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRou
func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc {
absolutePath := group.calculateAbsolutePath(relativePath)
fileServer := http.StripPrefix(absolutePath, http.FileServer(fs))
_, nolisting := fs.(*onlyfilesFS)

return func(c *Context) {
if nolisting {
file := c.Param("filepath")

// Check if file exists and/or if we have permission to access it
if _, err := fs.Open(file); err != nil {
c.Writer.WriteHeader(http.StatusNotFound)
c.handlers = group.engine.allNoRoute
// Reset index
c.index = -1
return
}

fileServer.ServeHTTP(c.Writer, c.Request)
}
}
Expand Down
15 changes: 15 additions & 0 deletions routes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,21 @@ func TestRouterNotFound(t *testing.T) {
assert.Equal(t, http.StatusNotFound, w.Code)
}

func TestRouterStaticFSNotFound(t *testing.T) {
router := New()

router.StaticFS("/", http.FileSystem(http.Dir("/thisreallydoesntexist/")))
router.NoRoute(func(c *Context) {
c.String(404, "non existent")
})

w := performRequest(router, "GET", "/nonexistent")
assert.Equal(t, "non existent", w.Body.String())

w = performRequest(router, "HEAD", "/nonexistent")
assert.Equal(t, "non existent", w.Body.String())
}

func TestRouteRawPath(t *testing.T) {
route := New()
route.UseRawPath = true
Expand Down

2 comments on commit b97ccf3

@Collapsik
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This commit broke handlers system. I got panic "index out of range" in context.go:108. In my case length of c.handlers equal 1 and c.index equal 1.

@thinkerou
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @MetalBreaker

Please sign in to comment.