コード例 #1
0
ファイル: recovery_test.go プロジェクト: yourchanges/empire
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")
			}

			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)
	resp := httptest.NewRecorder()

	ctx = httpx.WithRequestID(ctx, "1234")

	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)
	}
}
コード例 #2
0
ファイル: request_id.go プロジェクト: yourchanges/empire
// ServeHTTPContext implements the httpx.Handler interface. It extracts a
// request id from the headers and inserts it into the context.
func (h *RequestID) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
	requestID := extractRequestID(r, h.Header)

	ctx = httpx.WithRequestID(ctx, requestID)
	return h.handler.ServeHTTPContext(ctx, w, r)
}