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
6 changes: 4 additions & 2 deletions middleware/static.go
Original file line number Diff line number Diff line change
Expand Up @@ -269,10 +269,12 @@ func (config StaticConfig) ToMiddleware() (echo.MiddlewareFunc, error) {
}

var he echo.HTTPStatusCoder
if !errors.As(err, &he) || !config.HTML5 || he.StatusCode() != http.StatusNotFound {
if (c.Path() != "" && c.RouteInfo().Method != echo.RouteNotFound) ||
!errors.As(err, &he) ||
!config.HTML5 || he.StatusCode() != http.StatusNotFound {
return err
}
// is case HTML5 mode is enabled + echo 404 we serve index to the client
// In HTML5 mode, serve index for a router-level 404.
file, err = currentFS.Open(config.Index)
if err != nil {
return err
Expand Down
30 changes: 30 additions & 0 deletions middleware/static_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,36 @@ func TestStatic_useCaseForApiAndSPAs(t *testing.T) {

}

func TestStaticHTML5PreservesMatchedHandlerNotFound(t *testing.T) {
e := echo.New()
e.Use(StaticWithConfig(StaticConfig{
Root: "testdata/dist/public",
HTML5: true,
}))
e.GET("/api/users/:id", func(c *echo.Context) error {
return echo.NewHTTPError(http.StatusNotFound, "user not found")
})

req := httptest.NewRequest(http.MethodGet, "/api/users/42", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)

assert.Equal(t, http.StatusNotFound, rec.Code)
assert.JSONEq(t, `{"message":"user not found"}`, rec.Body.String())

group := echo.New()
group.Group("/app", StaticWithConfig(StaticConfig{
Root: "testdata/dist/public",
HTML5: true,
}))
req = httptest.NewRequest(http.MethodGet, "/app/dashboard", nil)
rec = httptest.NewRecorder()
group.ServeHTTP(rec, req)

assert.Equal(t, http.StatusOK, rec.Code)
assert.Contains(t, rec.Body.String(), "<h1>Hello from index</h1>\n")
}

func TestStatic(t *testing.T) {
var testCases = []struct {
name string
Expand Down