Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion middleware/static.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc {
}

var he *echo.HTTPError
if !(errors.As(err, &he) && config.HTML5 && he.Code == http.StatusNotFound) {
if !(errors.As(err, &he) && config.HTML5 && he.Code == http.StatusNotFound && isRouterNotFoundError(c, err)) {
return err
}

Expand Down Expand Up @@ -246,6 +246,18 @@ func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc {
}
}

func isRouterNotFoundError(c echo.Context, err error) bool {
if errors.Is(err, echo.ErrNotFound) {
return true
}
switch c.Path() {
case "", "/*":
return true
default:
return false
}
}

func serveFile(c echo.Context, file http.File, info os.FileInfo) error {
http.ServeContent(c.Response(), c.Request(), info.Name(), info.ModTime(), file)
return nil
Expand Down
36 changes: 36 additions & 0 deletions middleware/static_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -454,3 +454,39 @@ func TestStatic_CustomFS(t *testing.T) {
})
}
}

func TestStaticHTML5DoesNotOverrideHandler404(t *testing.T) {
t.Parallel()

e := echo.New()
e.Use(StaticWithConfig(StaticConfig{
Root: "../_fixture",
HTML5: true,
}))

e.GET("/api/test/:id", func(c echo.Context) error {
if c.Param("id") == "3" {
return echo.NewHTTPError(http.StatusNotFound, "not found")
}
return c.String(http.StatusOK, "ID: "+c.Param("id"))
})

t.Run("handler 404 is preserved", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/api/test/3", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)

assert.Equal(t, http.StatusNotFound, rec.Code)
assert.Contains(t, rec.Body.String(), "not found")
assert.NotContains(t, rec.Body.String(), "<title>Echo</title>")
})

t.Run("router 404 serves SPA index", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/client-route", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)

assert.Equal(t, http.StatusOK, rec.Code)
assert.Contains(t, rec.Body.String(), "<title>Echo</title>")
})
}