1
0
mirror of https://github.com/labstack/echo.git synced 2024-12-24 20:14:31 +02:00

Use the NotFoundHandler when a file haven't been found. (#966)

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 <rene@jochums.at>
This commit is contained in:
Rene Jochum 2017-07-19 20:29:41 +02:00 committed by Vishal Rana
parent a5c75b002d
commit 0769b34b52
2 changed files with 3 additions and 3 deletions

View File

@ -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()
@ -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 {

View File

@ -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...)
}