// doRequests performs a POST to requestPath. It uses the marshaled form of req
// as the request body payload, and automatically unmarshals the response body
// payload as resp.
420497
func (a *netAPI) doRequest(ctx context.Context, requestPath string, req proto.Message, resp proto.Message) error {
	p, err := proto.Marshal(req)
	if err != nil {
		return err
	}

	u := *a.url // Make a copy of URL
	u.Path = requestPath
	httpReq, err := http.NewRequest("POST", u.String(), bytes.NewReader(p))
	httpReq.Header.Add("Content-Type", "application/x-protobuf")
	httpReq = httpReq.WithContext(ctx)
	httpResp, err := a.client.Do(httpReq)
	if err != nil {
		return err
	}
	defer httpResp.Body.Close()
	if httpResp.StatusCode != 200 {
		return fmt.Errorf("safebrowsing: unexpected server response code: %d", httpResp.StatusCode)
	}
	body, err := ioutil.ReadAll(httpResp.Body)
	if err != nil {
		return err
	}
	return proto.Unmarshal(body, resp)
}
492025
func (r *Request) Do() *Response {
	var (
		err  error
		req  *http.Request
		resp *http.Response
		url  string
		body []byte
	)

	if r.err != nil {
		return &Response{err: r.err}
	}
	url = r.URL().String()
	req, err = http.NewRequest(r.verb, url, bytes.NewBuffer(r.body))
	if err != nil {
		return &Response{err: err}
	}
	if r.headers == nil {
		r.headers = http.Header{}
	}

	req.Header = r.headers
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Date", time.Now().String())

	if len(r.authstring) > 0 {
		if auth.IsJwtToken(r.authstring) {
			req.Header.Set("Authorization", "bearer "+r.authstring)
		} else {
			req.Header.Set("Authorization", "Basic "+r.authstring)
		}
	}

	if len(r.accesstoken) > 0 {
		req.Header.Set("Access-Token", r.accesstoken)
	}

	start := time.Now()
	attemptNum := 0
	for {
		if resp, err = r.client.Do(req); err != nil {
			return &Response{err: err}
		}

		if time.Since(start) >= maxRetryDuration ||
			resp.StatusCode != http.StatusServiceUnavailable {
			break
		}
		attemptNum++
		handleServiceUnavailable(resp, attemptNum)
	}

	if resp.Body != nil {
		defer resp.Body.Close()
		if body, err = ioutil.ReadAll(resp.Body); err != nil {
			return &Response{err: err}
		}
	}

	return &Response{
		status:     resp.Status,
		statusCode: resp.StatusCode,
		body:       body,
		err:        parseHTTPStatus(resp, body),
	}
}
424299
func (d *tracedDoer) Do(ctx context.Context, req *http.Request) (*http.Response, error) {
	var (
		traceID = ContextTraceID(ctx)
		spanID  = ContextSpanID(ctx)
	)
	if traceID != "" {
		req.Header.Set(TraceIDHeader, traceID)
		req.Header.Set(ParentSpanIDHeader, spanID)
	}

	return d.Doer.Do(ctx, req)
}
1038655
func (doer httpRequestDoer) Do(req *http.Request) (*http.Response, error) {
	return doer.DoWithBody(req, nil)
}
749117
func Do(url string) ([]byte, error) {
	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return body, nil
}
285257
func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
	if client == nil {
		client = http.DefaultClient
	}

	// Request cancelation changed in Go 1.5, see cancelreq.go and cancelreq_go14.go.
	cancel := canceler(client, req)

	type responseAndError struct {
		resp *http.Response
		err  error
	}
	result := make(chan responseAndError, 1)

	go func() {
		resp, err := client.Do(req)
		result <- responseAndError{resp, err}
	}()

	select {
	case <-ctx.Done():
		cancel()
		return nil, ctx.Err()
	case r := <-result:
		return r.resp, r.err
	}
}
172876
func (r *Request) Do() *Response {
	if r.err != nil {
		return &Response{
			err: r.err,
		}
	}

	req, err := r.request()
	if err != nil {
		return &Response{
			err: err,
		}
	}

	res, err := r.client.Do(req)
	if err != nil {
		return &Response{
			err: err,
		}
	}

	// return res, err
	return newResponse(res, err)
}
388327
func (c *traceClient) Do(r *http.Request) (*http.Response, error) {
	span, _ := tracing.StartSpanFromContext(r.Context())
	tracing.InjectToHTTPRequest(span, r)
	return c.Client.Do(r)
}
558234
func (f DoerFunc) Do(req *http.Request) (resp *http.Response, err error) {
	return f(req)
}
1042605
func (c *Client) do(req *http.Request, remote string, via []*http.Request) (*http.Response, error) {
	return c.client.Do(req)
}
891133
func (r *Request) Do() (*Response, error) {
	if r.dispatched {
		return nil, errors.New("gentleman: Request was already dispatched")
	}

	r.dispatched = true
	ctx := NewDispatcher(r).Dispatch()

	return buildResponse(ctx)
}
1077970
func (c *HTTPClient) Do(req *http.Request) (*http.Response, error) {
	var resp *http.Response
	var err error
	breaker := c.breakerLookup(req.URL.String())
	err = breaker.Call(func() error {
		resp, err = c.Client.Do(req)
		return err
	}, c.timeout)
	return resp, err
}
705197
func Do(req *http.Request) (resp *http.Response, err error) {
	c := New()
	return c.Do(req)
}
49643
func (c Client) Do(r *http.Request) (*http.Response, error) {
	if r.UserAgent() == "" {
		r, _ = Prepare(r,
			WithUserAgent(c.UserAgent))
	}
	// NOTE: c.WithInspection() must be last in the list so that it can inspect all preceding operations
	r, err := Prepare(r,
		c.WithAuthorization(),
		c.WithInspection())
	if err != nil {
		var resp *http.Response
		if detErr, ok := err.(DetailedError); ok {
			// if the authorization failed (e.g. invalid credentials) there will
			// be a response associated with the error, be sure to return it.
			resp = detErr.Response
		}
		return resp, NewErrorWithError(err, "autorest/Client", "Do", nil, "Preparing request failed")
	}
	logger.Instance.WriteRequest(r, logger.Filter{
		Header: func(k string, v []string) (bool, []string) {
			// remove the auth token from the log
			if strings.EqualFold(k, "Authorization") || strings.EqualFold(k, "Ocp-Apim-Subscription-Key") {
				v = []string{"**REDACTED**"}
			}
			return true, v
		},
	})
	resp, err := SendWithSender(c.sender(tls.RenegotiateNever), r)
	logger.Instance.WriteResponse(resp, logger.Filter{})
	Respond(resp, c.ByInspecting())
	return resp, err
}
18326
func (c *Client) Do(req *Request) (*http.Response, error) {
	if c.Logger != nil {
		c.Logger.Printf("[DEBUG] %s %s", req.Method, req.URL)
	}

	var resp *http.Response
	var err error

	for i := 0; ; i++ {
		var code int // HTTP response code

		// Always rewind the request body when non-nil.
		if req.body != nil {
			body, err := req.body()
			if err != nil {
				return resp, err
			}
			if c, ok := body.(io.ReadCloser); ok {
				req.Body = c
			} else {
				req.Body = ioutil.NopCloser(body)
			}
		}

		if c.RequestLogHook != nil {
			c.RequestLogHook(c.Logger, req.Request, i)
		}

		// Attempt the request
		resp, err = c.HTTPClient.Do(req.Request)
		if resp != nil {
			code = resp.StatusCode
		}

		// Check if we should continue with retries.
		checkOK, checkErr := c.CheckRetry(req.Context(), resp, err)

		if err != nil {
			if c.Logger != nil {
				c.Logger.Printf("[ERR] %s %s request failed: %v", req.Method, req.URL, err)
			}
		} else {
			// Call this here to maintain the behavior of logging all requests,
			// even if CheckRetry signals to stop.
			if c.ResponseLogHook != nil {
				// Call the response logger function if provided.
				c.ResponseLogHook(c.Logger, resp)
			}
		}

		// Now decide if we should continue.
		if !checkOK {
			if checkErr != nil {
				err = checkErr
			}
			return resp, err
		}

		// We do this before drainBody beause there's no need for the I/O if
		// we're breaking out
		remain := c.RetryMax - i
		if remain <= 0 {
			break
		}

		// We're going to retry, consume any response to reuse the connection.
		if err == nil && resp != nil {
			c.drainBody(resp.Body)
		}

		wait := c.Backoff(c.RetryWaitMin, c.RetryWaitMax, i, resp)
		desc := fmt.Sprintf("%s %s", req.Method, req.URL)
		if code > 0 {
			desc = fmt.Sprintf("%s (status: %d)", desc, code)
		}
		if c.Logger != nil {
			c.Logger.Printf("[DEBUG] %s: retrying in %s (%d left)", desc, wait, remain)
		}
		select {
		case <-req.Context().Done():
			return nil, req.Context().Err()
		case <-time.After(wait):
		}
	}

	if c.ErrorHandler != nil {
		return c.ErrorHandler(resp, err, c.RetryMax+1)
	}

	// By default, we close the response body and return an error without
	// returning the response
	if resp != nil {
		resp.Body.Close()
	}
	return nil, fmt.Errorf("%s %s giving up after %d attempts",
		req.Method, req.URL, c.RetryMax+1)
}
1360694
func (c *clusterConnection) Do(ctx context.Context, req driver.Request) (driver.Response, error) {
	followLeaderRedirect := true
	if ctx == nil {
		ctx = context.Background()
	} else {
		if v := ctx.Value(keyFollowLeaderRedirect); v != nil {
			if on, ok := v.(bool); ok {
				followLeaderRedirect = on
			}
		}
	}
	// Timeout management.
	// We take the given timeout and divide it in 3 so we allow for other servers
	// to give it a try if an earlier server fails.
	deadline, hasDeadline := ctx.Deadline()
	var timeout time.Duration
	if hasDeadline {
		timeout = deadline.Sub(time.Now())
	} else {
		timeout = c.defaultTimeout
	}

	serverCount := len(c.servers)
	var specificServer driver.Connection
	if v := ctx.Value(keyEndpoint); v != nil {
		if endpoint, ok := v.(string); ok {
			// Specific endpoint specified
			serverCount = 1
			var err error
			specificServer, err = c.getSpecificServer(endpoint)
			if err != nil {
				return nil, driver.WithStack(err)
			}
		}
	}

	timeoutDivider := math.Max(1.0, math.Min(3.0, float64(serverCount)))
	attempt := 1
	s := specificServer
	if s == nil {
		s = c.getCurrentServer()
	}
	for {
		// Send request to specific endpoint with a 1/3 timeout (so we get 3 attempts)
		serverCtx, cancel := context.WithTimeout(ctx, time.Duration(float64(timeout)/timeoutDivider))
		resp, err := s.Do(serverCtx, req)
		cancel()

		isNoLeaderResponse := false
		if err == nil && resp.StatusCode() == 503 {
			// Service unavailable, parse the body, perhaps this is a "no leader"
			// case where we have to failover.
			var aerr driver.ArangoError
			if perr := resp.ParseBody("", &aerr); perr == nil && aerr.HasError {
				if driver.IsNoLeader(aerr) {
					isNoLeaderResponse = true
					// Save error in case we have no more servers
					err = aerr
				}
			}

		}
		if !isNoLeaderResponse || !followLeaderRedirect {
			if err == nil {
				// We're done
				return resp, nil
			}
			// No success yet
			if driver.IsCanceled(err) {
				// Request was cancelled, we return directly.
				return nil, driver.WithStack(err)
			}
			// If we've completely written the request, we return the error,
			// otherwise we'll failover to a new server.
			if req.Written() {
				// Request has been written to network, do not failover
				if driver.IsArangoError(err) {
					// ArangoError, so we got an error response from server.
					return nil, driver.WithStack(err)
				}
				// Not an ArangoError, so it must be some kind of timeout, network ... error.
				return nil, driver.WithStack(&driver.ResponseError{Err: err})
			}
		}

		// Failed, try next server
		attempt++
		if specificServer != nil {
			// A specific server was specified, no failover.
			return nil, driver.WithStack(err)
		}
		if attempt > len(c.servers) {
			// We've tried all servers. Giving up.
			return nil, driver.WithStack(err)
		}
		s = c.getNextServer()
	}
}
435526
func (c *vstConnection) do(ctx context.Context, req driver.Request, transport messageTransport) (driver.Response, error) {
	if ctx == nil {
		ctx = context.Background()
	}
	vstReq, ok := req.(*vstRequest)
	if !ok {
		return nil, driver.WithStack(driver.InvalidArgumentError{Message: "request is not a *vstRequest"})
	}
	msgParts, err := vstReq.createMessageParts()
	if err != nil {
		return nil, driver.WithStack(err)
	}
	resp, err := transport.Send(ctx, msgParts...)
	if err != nil {
		return nil, driver.WithStack(err)
	}
	// All data was send now
	vstReq.WroteRequest()

	// Wait for response
	var msg protocol.Message
	select {
	case msg, ok = <-resp:
		if !ok {
			// Message was canceled / timeout
			return nil, driver.WithStack(context.DeadlineExceeded)
		}
	case <-ctx.Done():
		// Context canceled while waiting here
		return nil, driver.WithStack(ctx.Err())
	}

	//fmt.Printf("Received msg: %d\n", msg.ID)
	var rawResponse *[]byte
	if ctx != nil {
		if v := ctx.Value(keyRawResponse); v != nil {
			if buf, ok := v.(*[]byte); ok {
				rawResponse = buf
			}
		}
	}

	vstResp, err := newResponse(msg.Data, c.endpoint.String(), rawResponse)
	if err != nil {
		fmt.Printf("Cannot decode msg %d: %#v\n", msg.ID, err)
		return nil, driver.WithStack(err)
	}
	if ctx != nil {
		if v := ctx.Value(keyResponse); v != nil {
			if respPtr, ok := v.(*driver.Response); ok {
				*respPtr = vstResp
			}
		}
	}
	return vstResp, nil
}