Skip to content

Commit

Permalink
Use the NotFoundHandler when a file haven't been found. (labstack#966)
Browse files Browse the repository at this point in the history
This is especialy usefull when you use e.Static("/", "static") and you
want a notfoundhandler that serves your index.html like this:

echo.NotFoundHandler = func(c2 echo.Context) error {
	index := filepath.Join(c.config.StaticDir, c.config.Index)
	_, err := os.Open(index)
	if err != nil {
		return echo.ErrNotFound
	}
	return c2.File(path.Join(c.config.StaticDir, c.config.Index))
}

Another usecase with the Handler above is HTML5 SPF applications.

One caveat, you need to make sure that your NotFoundHandler doesn't
produce loops.

Signed-off-by: Rene Jochum <[email protected]>
  • Loading branch information
jochumdev authored and vishr committed Jul 19, 2017
1 parent a5c75b0 commit 0769b34
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 3 deletions.
4 changes: 2 additions & 2 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ func (c *context) Stream(code int, contentType string, r io.Reader) (err error)
func (c *context) File(file string) (err error) {
f, err := os.Open(file)
if err != nil {
return ErrNotFound
return NotFoundHandler(c)
}
defer f.Close()

Expand All @@ -505,7 +505,7 @@ func (c *context) File(file string) (err error) {
file = filepath.Join(file, indexPage)
f, err = os.Open(file)
if err != nil {
return ErrNotFound
return NotFoundHandler(c)
}
defer f.Close()
if fi, err = f.Stat(); err != nil {
Expand Down
2 changes: 1 addition & 1 deletion group.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func (g *Group) Use(middleware ...MiddlewareFunc) {
// Allow all requests to reach the group as they might get dropped if router
// doesn't find a match, making none of the group middleware process.
g.echo.Any(path.Clean(g.prefix+"/*"), func(c Context) error {
return ErrNotFound
return NotFoundHandler(c)
}, g.middleware...)
}

Expand Down

0 comments on commit 0769b34

Please sign in to comment.