Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

contrib/go-chi/chi: Added option to set custom error status check #773

Merged
merged 8 commits into from
Dec 11, 2020
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 1 addition & 1 deletion contrib/go-chi/chi/chi.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func Middleware(opts ...Option) func(next http.Handler) http.Handler {
}
span.SetTag(ext.HTTPCode, strconv.Itoa(status))

if status >= 500 && status < 600 {
if cfg.statusCheck(status) {
// mark 5xx server error
span.SetTag(ext.Error, fmt.Errorf("%d: %s", status, http.StatusText(status)))
}
Expand Down
92 changes: 65 additions & 27 deletions contrib/go-chi/chi/chi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"testing"

"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
Expand Down Expand Up @@ -99,37 +100,74 @@ func TestTrace200(t *testing.T) {
}

func TestError(t *testing.T) {
assert := assert.New(t)
mt := mocktracer.Start()
defer mt.Stop()
assertSpan := func(assert *assert.Assertions, spans []mocktracer.Span, code int) {
assert.Len(spans, 1)
if len(spans) < 1 {
t.Fatalf("no spans")
}
span := spans[0]
assert.Equal("http.request", span.OperationName())
assert.Equal("foobar", span.Tag(ext.ServiceName))

// setup
router := chi.NewRouter()
router.Use(Middleware(WithServiceName("foobar")))
code := 500
wantErr := fmt.Sprintf("%d: %s", code, http.StatusText(code))
assert.Equal(strconv.Itoa(code), span.Tag(ext.HTTPCode))

wantErr := fmt.Sprintf("%d: %s", code, http.StatusText(code))
assert.Equal(wantErr, span.Tag(ext.Error).(error).Error())
}
knusbaum marked this conversation as resolved.
Show resolved Hide resolved
t.Run("with default isError function", func(t *testing.T) {
Hunrik marked this conversation as resolved.
Show resolved Hide resolved
assert := assert.New(t)
mt := mocktracer.Start()
defer mt.Stop()

// setup
router := chi.NewRouter()
router.Use(Middleware(WithServiceName("foobar")))
code := 500

// a handler with an error and make the requests
router.Get("/err", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, fmt.Sprintf("%d!", code), code)
})
r := httptest.NewRequest("GET", "/err", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
response := w.Result()
assert.Equal(response.StatusCode, code)

// a handler with an error and make the requests
router.Get("/err", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, fmt.Sprintf("%d!", code), code)
// verify the errors and status are correct
spans := mt.FinishedSpans()
assertSpan(assert, spans, code)
})
r := httptest.NewRequest("GET", "/err", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
response := w.Result()
assert.Equal(response.StatusCode, 500)

// verify the errors and status are correct
spans := mt.FinishedSpans()
assert.Len(spans, 1)
if len(spans) < 1 {
t.Fatalf("no spans")
}
span := spans[0]
assert.Equal("http.request", span.OperationName())
assert.Equal("foobar", span.Tag(ext.ServiceName))
assert.Equal("500", span.Tag(ext.HTTPCode))
assert.Equal(wantErr, span.Tag(ext.Error).(error).Error())
t.Run("with custome isError function", func(t *testing.T) {
Hunrik marked this conversation as resolved.
Show resolved Hide resolved
assert := assert.New(t)
mt := mocktracer.Start()
defer mt.Stop()

// setup
router := chi.NewRouter()
router.Use(Middleware(
WithServiceName("foobar"),
WithStatusCheck(func(statusCode int) bool {
return statusCode >= 400
}),
))

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here with whitespace. I think we can remove it.

code := 404
// a handler with an error and make the requests
router.Get("/err", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, fmt.Sprintf("%d!", code), code)
})
r := httptest.NewRequest("GET", "/err", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
response := w.Result()
assert.Equal(response.StatusCode, code)

// verify the errors and status are correct
spans := mt.FinishedSpans()
assertSpan(assert, spans, code)
})
}

func TestGetSpanNotInstrumented(t *testing.T) {
Expand Down
15 changes: 15 additions & 0 deletions contrib/go-chi/chi/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type config struct {
serviceName string
spanOpts []ddtrace.StartSpanOption // additional span options to be applied
analyticsRate float64
statusCheck func(statusCode int) bool
Copy link
Contributor

@gbbr gbbr Nov 11, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this isn't clear enough, perhaps isErrorStatus or isStatusError would be more specific.

}

// Option represents an option that can be passed to NewRouter.
Expand All @@ -32,6 +33,8 @@ func defaults(cfg *config) {
} else {
cfg.analyticsRate = globalconfig.AnalyticsRate()
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need for the empty line here.

cfg.statusCheck = isServerError
}

// WithServiceName sets the given service name for the router.
Expand Down Expand Up @@ -71,3 +74,15 @@ func WithAnalyticsRate(rate float64) Option {
}
}
}

// WithStatusCheck sets the function which is used to decide whther the
// status should be marked as an error
Hunrik marked this conversation as resolved.
Show resolved Hide resolved
func WithStatusCheck(statusCheck func(statusCode int) bool) Option {
Hunrik marked this conversation as resolved.
Show resolved Hide resolved
return func(cfg *config) {
cfg.statusCheck = statusCheck
}
}

func isServerError(statusCode int) bool {
return statusCode >= 500 && statusCode < 600
}