Пример #1
0
// ServeHTTPContext implements the httpx.Handler interface. It recovers from
// panics and returns an error for upstream middleware to handle.
func (h *Recovery) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) (err error) {
	ctx = reporter.WithReporter(ctx, h.Reporter)

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

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

	defer func() {
		if v := recover(); v != nil {
			err = fmt.Errorf("%v", v)

			if v, ok := v.(error); ok {
				err = v
			}

			reporter.Report(ctx, err)

			return
		}
	}()

	err = h.handler.ServeHTTPContext(ctx, w, r)

	return
}
Пример #2
0
func Example() {
	ctx := reporter.WithReporter(context.Background(), hb.NewReporter("dcb8affa"))
	req, _ := http.NewRequest("GET", "/api/foo", nil)
	req.Header.Set("Content-Type", "application/json")

	reporter.AddContext(ctx, "request_id", "1234")
	reporter.AddRequest(ctx, req)
	reporter.Report(ctx, errBoom)
	// Output:
}
Пример #3
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)
	})
}