Ejemplo n.º 1
0
// ServeHTTP implements the http.Handler interface.
func (h *Background) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ctx := h.Generate
	if ctx == nil {
		ctx = DefaultGenerator
	}
	h.ServeHTTPContext(httpx.WithRequest(ctx(), r), w, r)
}
Ejemplo n.º 2
0
// WithRequest adds information about the http.Request to reported errors.
func WithRequest(h httpx.Handler) httpx.Handler {
	return httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		ctx = httpx.WithRequest(ctx, r)

		// Add the request to the context.
		reporter.AddRequest(ctx, r)

		// Add the request id
		reporter.AddContext(ctx, "request_id", httpx.RequestID(ctx))

		return h.ServeHTTPContext(ctx, w, r)
	})
}
Ejemplo n.º 3
0
func TestRecovery(t *testing.T) {
	var (
		called  bool
		errBoom = errors.New("boom")
	)

	h := &Recovery{
		Reporter: reporter.ReporterFunc(func(ctx context.Context, err error) error {
			called = true

			e := err.(*reporter.Error)

			if e.Err != errBoom {
				t.Fatalf("err => %v; want %v", err, errBoom)
			}

			if got, want := e.Context["request_id"], "1234"; got != want {
				t.Fatalf("RequestID => %s; want %s", got, want)
			}

			return nil
		}),
		handler: httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
			panic(errBoom)
		}),
	}

	ctx := context.Background()
	req, _ := http.NewRequest("GET", "/", nil)
	req.Header.Set("X-Request-ID", "1234")
	resp := httptest.NewRecorder()

	ctx = httpx.WithRequest(ctx, req)

	defer func() {
		if err := recover(); err != nil {
			t.Fatal("Expected the panic to be handled.")
		}
	}()

	err := h.ServeHTTPContext(ctx, resp, req)

	if err != errBoom {
		t.Fatalf("err => %v; want %v", err, errBoom)
	}
}