Skip to content

Commit

Permalink
NewNoopError & Middleware Shortcircuiting (#10)
Browse files Browse the repository at this point in the history
Add NewNoopError API to allow short-circuiting of main endpoint by middleware
  • Loading branch information
apourchet authored Feb 8, 2024
1 parent 02b9fa9 commit bde724d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
5 changes: 5 additions & 0 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,8 @@ func (err httpError) WriteBody(writer io.Writer) error {
_, writeError := io.WriteString(writer, err.body)
return writeError
}

// NewNoopError returns an HTTPError that will completely bypass the
// deserialization logic. This can be used when the endpoint or middleware
// operates directly on the native http.ResponseWriter.
func NewNoopError() HTTPError { return NewHTTPError(0, "") }
23 changes: 23 additions & 0 deletions standard_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,29 @@ func TestStandardWrapper(t *testing.T) {
require.Equal(t, http.StatusUnauthorized, statusCode)
require.Equal(t, "Unauthorized.", body)
})

t.Run("middleware shortcircuit with nooperror", func(t *testing.T) {
wrapper := NewStandardWrapper().
Before(func(rw http.ResponseWriter) error {
rw.WriteHeader(http.StatusCreated)
rw.Write([]byte("HELLO WORLD"))
return NewNoopError()
})

handler := wrapper.Wrap(func(p1 header, p2 query, context typedContext) error {
require.Fail(t, "Handler should never be called.")
return nil
})

rw := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/endpoint?string=abc", nil)
req.Header.Set("integer", "12")

handler.ServeHTTP(rw, req)
statusCode, body := readResponseRecorder(t, rw)
require.Equal(t, http.StatusCreated, statusCode)
require.Equal(t, "HELLO WORLD", body)
})
}

func readResponseRecorder(t *testing.T, rw *httptest.ResponseRecorder) (int, string) {
Expand Down

0 comments on commit bde724d

Please sign in to comment.