Skip to content

Commit

Permalink
fix crash when unknown endpoint is called (#179)
Browse files Browse the repository at this point in the history
  • Loading branch information
jakecoffman authored Sep 26, 2023
1 parent 443fd62 commit c1e3fc0
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
8 changes: 7 additions & 1 deletion internal/server/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ func (a *API) Complete() {
}

// ServeHTTP handles requests to the server
func (a *API) ServeHTTP(_ http.ResponseWriter, r *http.Request) {
func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) {
data, err := io.ReadAll(r.Body)
if err != nil {
err = fmt.Errorf("failed to read body: %w", err)
Expand All @@ -122,6 +122,12 @@ func (a *API) ServeHTTP(_ http.ResponseWriter, r *http.Request) {
a.pushError(err)
}

if actual == nil {
// indicates the kind (endpoint) isn't implemented in decodeWrapper, so return a 501
w.WriteHeader(http.StatusNotImplemented)
return
}

if kind == "increment_metric" {
// Let's just output the metrics data and stop
a.outputRequestData(kind, actual)
Expand Down
16 changes: 16 additions & 0 deletions internal/server/api_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package server

import (
"net/http"
"net/http/httptest"
"testing"
)

Expand All @@ -12,3 +14,17 @@ func Test_decodeWrapper(t *testing.T) {
}
})
}

func TestAPI_ServeHTTP(t *testing.T) {
t.Run("doesn't crash when unknown endpoint is used", func(t *testing.T) {
request := httptest.NewRequest("POST", "/unexpected-endpoint", nil)
response := httptest.NewRecorder()

api := NewAPI(nil, nil)
api.ServeHTTP(response, request)

if response.Code != http.StatusNotImplemented {
t.Errorf("expected status code %d, got %d", http.StatusNotImplemented, response.Code)
}
})
}

0 comments on commit c1e3fc0

Please sign in to comment.