// Do submits requests with bearer token authorization, using the AccessToken as the bearer token.
//
// Will automatically refresh the AccessToken and retry the request if the token has expired.
966479
func (a *OAuthStrategy) Do(req *http.Request) (*http.Response, error) {
	if err := a.Login(); err != nil {
		return nil, err
	}

	req.Header.Set("Authorization", "Bearer "+a.AccessToken())

	clone, err := cloneRequest(req)

	if err != nil {
		return nil, errors.New("failed to clone request body: " + err.Error())
	}

	req.Header.Set("Authorization", "Bearer "+a.AccessToken())
	resp, err := a.ApiClient.Do(req)

	if err != nil {
		return resp, err
	}

	expired, err := tokenExpired(resp)

	if err != nil || !expired {
		return resp, err
	}

	if err := a.Refresh(); err != nil {
		return nil, err
	}

	req.Header.Set("Authorization", "Bearer "+a.AccessToken())
	return a.ApiClient.Do(clone)
}
210698
func (r *Resource) do(method string) (*Resource, error) {
	url := *r.Api.BaseUrl
	if len(url.Path) > 0 {
		url.Path += "/" + r.Url
	} else {
		url.Path = r.Url
	}
	if r.Api.PathSuffix != "" {
		url.Path += r.Api.PathSuffix
	}

	url.RawQuery = r.QueryValues.Encode()
	req, err := http.NewRequest(method, url.String(), r.Payload)
	if err != nil {
		return r, err
	}

	if r.Api.BasicAuth != nil {
		req.SetBasicAuth(r.Api.BasicAuth.Username, r.Api.BasicAuth.Password)
	}

	if r.Headers != nil {
		for k, _ := range r.Headers {
			req.Header.Set(k, r.Headers.Get(k))
		}
	}

	resp, err := r.Api.Client.Do(req)
	if err != nil {
		return r, err
	}

	r.Raw = resp

	if resp.StatusCode >= 400 {
		return r, nil
	}

	for k, _ := range r.Raw.Header {
		r.SetHeader(k, r.Raw.Header.Get(k));
	}

	defer resp.Body.Close()

	err = json.NewDecoder(resp.Body).Decode(r.Response)
	if err != nil {
		return r, err
	}

	return r, nil
}
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)
}
1271828
func (r *Request) Do() bool {
	if r.do != 0 {
		return r.do == doTrue
	}

	if o := r.Req.IsEdns0(); o != nil {
		if o.Do() {
			r.do = doTrue
		} else {
			r.do = doFalse
		}
		return o.Do()
	}
	r.do = doFalse
	return false
}
1095710
func (c *Client) Do(ctx context.Context, req *http.Request, resBody interface{}) error {
	switch req.Method {
	case http.MethodPost, http.MethodPatch:
		req.Header.Set("Content-Type", "application/json")
	}

	req.Header.Set("Accept", "application/json")

	if s, ok := ctx.Value(signerContext{}).(Signer); ok {
		if err := s.SignRequest(req); err != nil {
			return err
		}
	}

	return c.Client.Do(ctx, req, func(res *http.Response) error {
		switch res.StatusCode {
		case http.StatusOK:
		case http.StatusBadRequest:
			// TODO: structured error types
			detail, err := ioutil.ReadAll(res.Body)
			if err != nil {
				return err
			}
			return fmt.Errorf("%s: %s", res.Status, bytes.TrimSpace(detail))
		default:
			return fmt.Errorf("%s %s: %s", req.Method, req.URL, res.Status)
		}

		if resBody == nil {
			return nil
		}

		switch b := resBody.(type) {
		case io.Writer:
			_, err := io.Copy(b, res.Body)
			return err
		default:
			val := struct {
				Value interface{} `json:"value,omitempty"`
			}{
				resBody,
			}
			return json.NewDecoder(res.Body).Decode(&val)
		}
	})
}
591172
func (c *httpConnection) Do(ctx context.Context, req driver.Request) (driver.Response, error) {
	httpReq, ok := req.(httpRequest)
	if !ok {
		return nil, driver.WithStack(driver.InvalidArgumentError{Message: "request is not a httpRequest"})
	}
	r, err := httpReq.createHTTPRequest(c.endpoint)
	rctx := ctx
	if rctx == nil {
		rctx = context.Background()
	}
	rctx = httptrace.WithClientTrace(rctx, &httptrace.ClientTrace{
		WroteRequest: func(info httptrace.WroteRequestInfo) {
			httpReq.WroteRequest(info)
		},
	})
	r = r.WithContext(rctx)
	if err != nil {
		return nil, driver.WithStack(err)
	}

	// Block on too many concurrent connections
	if c.connPool != nil {
		select {
		case t := <-c.connPool:
			// Ok, we're allowed to continue
			defer func() {
				// Give back token
				c.connPool <- t
			}()
		case <-rctx.Done():
			// Context cancelled or expired
			return nil, driver.WithStack(rctx.Err())
		}
	}

	resp, err := c.client.Do(r)
	if err != nil {
		return nil, driver.WithStack(err)
	}
	var rawResponse *[]byte
	if ctx != nil {
		if v := ctx.Value(keyRawResponse); v != nil {
			if buf, ok := v.(*[]byte); ok {
				rawResponse = buf
			}
		}
	}

	// Read response body
	body, err := readBody(resp)
	if err != nil {
		return nil, driver.WithStack(err)
	}
	if rawResponse != nil {
		*rawResponse = body
	}

	ct := resp.Header.Get("Content-Type")
	var httpResp driver.Response
	switch strings.Split(ct, ";")[0] {
	case "application/json", "application/x-arango-dump":
		httpResp = &httpJSONResponse{resp: resp, rawResponse: body}
	case "application/x-velocypack":
		httpResp = &httpVPackResponse{resp: resp, rawResponse: body}
	default:
		if resp.StatusCode == http.StatusUnauthorized {
			// When unauthorized the server sometimes return a `text/plain` response.
			return nil, driver.WithStack(driver.ArangoError{
				HasError:     true,
				Code:         resp.StatusCode,
				ErrorMessage: string(body),
			})
		}
		// Handle empty 'text/plain' body as empty JSON object
		if len(body) == 0 {
			body = []byte("{}")
			if rawResponse != nil {
				*rawResponse = body
			}
			httpResp = &httpJSONResponse{resp: resp, rawResponse: body}
		} else {
			return nil, driver.WithStack(fmt.Errorf("Unsupported content type '%s' with status %d and content '%s'", ct, resp.StatusCode, string(body)))
		}
	}
	if ctx != nil {
		if v := ctx.Value(keyResponse); v != nil {
			if respPtr, ok := v.(*driver.Response); ok {
				*respPtr = httpResp
			}
		}
	}
	return httpResp, nil
}
879278
func (r *Req) Do(method, rawurl string, vs ...interface{}) (resp *Resp, err error) {
	if rawurl == "" {
		return nil, errors.New("req: url not specified")
	}
	req := &http.Request{
		Method:     method,
		Header:     make(http.Header),
		Proto:      "HTTP/1.1",
		ProtoMajor: 1,
		ProtoMinor: 1,
	}
	resp = &Resp{req: req, r: r}

	var queryParam param
	var formParam param
	var uploads []FileUpload
	var uploadProgress UploadProgress
	var progress func(int64, int64)
	var delayedFunc []func()
	var lastFunc []func()

	for _, v := range vs {
		switch vv := v.(type) {
		case Header:
			for key, value := range vv {
				req.Header.Add(key, value)
			}
		case http.Header:
			for key, values := range vv {
				for _, value := range values {
					req.Header.Add(key, value)
				}
			}
		case *bodyJson:
			fn, err := setBodyJson(req, resp, r.jsonEncOpts, vv.v)
			if err != nil {
				return nil, err
			}
			delayedFunc = append(delayedFunc, fn)
		case *bodyXml:
			fn, err := setBodyXml(req, resp, r.xmlEncOpts, vv.v)
			if err != nil {
				return nil, err
			}
			delayedFunc = append(delayedFunc, fn)
		case url.Values:
			p := param{vv}
			if method == "GET" || method == "HEAD" {
				queryParam.Copy(p)
			} else {
				formParam.Copy(p)
			}
		case Param:
			if method == "GET" || method == "HEAD" {
				queryParam.Adds(vv)
			} else {
				formParam.Adds(vv)
			}
		case QueryParam:
			queryParam.Adds(vv)
		case string:
			setBodyBytes(req, resp, []byte(vv))
		case []byte:
			setBodyBytes(req, resp, vv)
		case bytes.Buffer:
			setBodyBytes(req, resp, vv.Bytes())
		case *http.Client:
			resp.client = vv
		case FileUpload:
			uploads = append(uploads, vv)
		case []FileUpload:
			uploads = append(uploads, vv...)
		case *http.Cookie:
			req.AddCookie(vv)
		case Host:
			req.Host = string(vv)
		case io.Reader:
			fn := setBodyReader(req, resp, vv)
			lastFunc = append(lastFunc, fn)
		case UploadProgress:
			uploadProgress = vv
		case DownloadProgress:
			resp.downloadProgress = vv
		case func(int64, int64):
			progress = vv
		case context.Context:
			req = req.WithContext(vv)
		case error:
			return nil, vv
		}
	}

	if length := req.Header.Get("Content-Length"); length != "" {
		if l, err := strconv.ParseInt(length, 10, 64); err == nil {
			req.ContentLength = l
		}
	}

	if len(uploads) > 0 && (req.Method == "POST" || req.Method == "PUT") { // multipart
		var up UploadProgress
		if uploadProgress != nil {
			up = uploadProgress
		} else if progress != nil {
			up = UploadProgress(progress)
		}
		multipartHelper := &multipartHelper{
			form:           formParam.Values,
			uploads:        uploads,
			uploadProgress: up,
		}
		multipartHelper.Upload(req)
		resp.multipartHelper = multipartHelper
	} else {
		if progress != nil {
			resp.downloadProgress = DownloadProgress(progress)
		}
		if !formParam.Empty() {
			if req.Body != nil {
				queryParam.Copy(formParam)
			} else {
				setBodyBytes(req, resp, []byte(formParam.Encode()))
				setContentType(req, "application/x-www-form-urlencoded; charset=UTF-8")
			}
		}
	}

	if !queryParam.Empty() {
		paramStr := queryParam.Encode()
		if strings.IndexByte(rawurl, '?') == -1 {
			rawurl = rawurl + "?" + paramStr
		} else {
			rawurl = rawurl + "&" + paramStr
		}
	}

	u, err := url.Parse(rawurl)
	if err != nil {
		return nil, err
	}
	req.URL = u

	if host := req.Header.Get("Host"); host != "" {
		req.Host = host
	}

	for _, fn := range delayedFunc {
		fn()
	}

	if resp.client == nil {
		resp.client = r.Client()
	}

	var response *http.Response
	if r.flag&Lcost != 0 {
		before := time.Now()
		response, err = resp.client.Do(req)
		after := time.Now()
		resp.cost = after.Sub(before)
	} else {
		response, err = resp.client.Do(req)
	}
	if err != nil {
		return nil, err
	}

	for _, fn := range lastFunc {
		fn()
	}

	resp.resp = response

	if _, ok := resp.client.Transport.(*http.Transport); ok && response.Header.Get("Content-Encoding") == "gzip" && req.Header.Get("Accept-Encoding") != "" {
		body, err := gzip.NewReader(response.Body)
		if err != nil {
			return nil, err
		}
		response.Body = body
	}

	// output detail if Debug is enabled
	if Debug {
		fmt.Println(resp.Dump())
	}
	return
}
1191101
func (c *Client) Do(ctx context.Context, req *http.Request) (*http.Response, error) {

	if len(c.AuthToken) > 0 {
		// only add this header if not already set (e.g. for authClient)
		if len(req.Header.Get(common.AuthHeaderKey)) == 0 {
			common.AddServiceTokenHeader(req, c.AuthToken)
		}
	}
	if len(c.DownloadServiceToken) > 0 {
		// only add this header if not already set
		if len(req.Header.Get(common.DownloadServiceHeaderKey)) == 0 {
			common.AddDownloadServiceTokenHeader(req, c.DownloadServiceToken)
		}
	}
	if common.IsUserPresent(ctx) {
		// only add this header if not already set
		if len(req.Header.Get(common.UserHeaderKey)) == 0 {
			common.AddUserHeader(req, common.User(ctx))
		}
	}
	if common.IsFlorenceIdentityPresent(ctx) {
		common.SetFlorenceHeader(ctx, req)
	}

	// get any existing correlation-id (might be "id1,id2"), append a new one, add to headers
	upstreamCorrelationIds := common.GetRequestId(ctx)
	addedIdLen := 20
	if upstreamCorrelationIds != "" {
		// get length of (first of) IDs (e.g. "id1" is 3), new ID will be half that size
		addedIdLen = len(upstreamCorrelationIds) / 2
		if commaPosition := strings.Index(upstreamCorrelationIds, ","); commaPosition > 1 {
			addedIdLen = commaPosition / 2
		}
		upstreamCorrelationIds += ","
	}
	common.AddRequestIdHeader(req, upstreamCorrelationIds+common.NewRequestID(addedIdLen))

	doer := func(args ...interface{}) (*http.Response, error) {
		req := args[2].(*http.Request)
		if req.ContentLength > 0 {
			var err error
			req.Body, err = req.GetBody()
			if err != nil {
				return nil, err
			}
		}
		return ctxhttp.Do(args[0].(context.Context), args[1].(*http.Client), req)
	}

	resp, err := doer(ctx, c.HTTPClient, req)
	if err != nil {
		if c.ExponentialBackoff {
			return c.backoff(doer, err, ctx, c.HTTPClient, req)
		}
		return nil, err
	}

	if c.ExponentialBackoff {
		if resp.StatusCode >= http.StatusInternalServerError {
			return c.backoff(doer, err, ctx, c.HTTPClient, req, errors.New("Bad server status"))
		}

		if resp.StatusCode == http.StatusConflict {
			return c.backoff(doer, err, ctx, c.HTTPClient, req, errors.New("Conflict - request could not be completed due to a conflict with the current state of the target resource"))
		}
	}

	return resp, err
}
982860
func (c *Client) Do(ctx context.Context, req *APIRequest, v interface{}, responseType string) (*APIResponse, error) {
	var err error
	var resp *http.Response

	req.HTTP = req.HTTP.WithContext(ctx)

	if resp, err = c.client.Do(req.HTTP); err != nil {
		return nil, err
	}

	r := &APIResponse{
		Request: req,
		HTTP:    resp,
	}

	if v != nil {
		if r.Body, err = readDoResponseBody(v, &r.HTTP.Body, responseType); err != nil {
			return nil, err
		}
	}

	if err = CheckResponse(r); err != nil {
		return r, err
	}

	return r, err
}
984100
func (uhc *unitHTTPClient) Do(req *http.Request, body io.ReadSeeker, response interface{}) error {
	req.URL.Path = path.Join("/units", uhc.unitName, req.URL.Path)
	return uhc.HTTPClient.Do(req, body, response)
}
711984
func (s *FlushService) Do() (*FlushResult, error) {
	// Build url
	path := "/"

	// Indices part
	if len(s.indices) > 0 {
		indexPart := make([]string, 0)
		for _, index := range s.indices {
			index, err := uritemplates.Expand("{index}", map[string]string{
				"index": index,
			})
			if err != nil {
				return nil, err
			}
			indexPart = append(indexPart, index)
		}
		path += strings.Join(indexPart, ",") + "/"
	}
	path += "_flush"

	// Parameters
	params := make(url.Values)
	if s.force != nil {
		params.Set("force", fmt.Sprintf("%v", *s.force))
	}
	if s.full != nil {
		params.Set("full", fmt.Sprintf("%v", *s.full))
	}
	if s.waitIfOngoing != nil {
		params.Set("wait_if_ongoing", fmt.Sprintf("%v", *s.waitIfOngoing))
	}
	if s.ignoreUnavailable != nil {
		params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
	}
	if s.allowNoIndices != nil {
		params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
	}
	if s.expandWildcards != "" {
		params.Set("expand_wildcards", s.expandWildcards)
	}

	// Get response
	res, err := s.client.PerformRequest("POST", path, params, nil)
	if err != nil {
		return nil, err
	}

	// Return result
	ret := new(FlushResult)
	if err := json.Unmarshal(res.Body, ret); err != nil {
		return nil, err
	}
	return ret, nil
}
825474
func (b *IndicesCreateService) Do(ctx context.Context) (*IndicesCreateResult, error) {
	if b.index == "" {
		return nil, errors.New("missing index name")
	}

	// Build url
	path, err := uritemplates.Expand("/{index}", map[string]string{
		"index": b.index,
	})
	if err != nil {
		return nil, err
	}

	params := make(url.Values)
	if b.pretty {
		params.Set("pretty", "true")
	}
	if b.masterTimeout != "" {
		params.Set("master_timeout", b.masterTimeout)
	}
	if b.timeout != "" {
		params.Set("timeout", b.timeout)
	}

	// Setup HTTP request body
	var body interface{}
	if b.bodyJson != nil {
		body = b.bodyJson
	} else {
		body = b.bodyString
	}

	// Get response
	res, err := b.client.PerformRequest(ctx, PerformRequestOptions{
		Method: "PUT",
		Path:   path,
		Params: params,
		Body:   body,
	})
	if err != nil {
		return nil, err
	}

	ret := new(IndicesCreateResult)
	if err := b.client.decoder.Decode(res.Body, ret); err != nil {
		return nil, err
	}
	return ret, nil
}
1042605
func (c *Client) do(req *http.Request, remote string, via []*http.Request) (*http.Response, error) {
	return c.client.Do(req)
}
117824
func (c *Client) Do(req *http.Request) (*Response, error) {
	req = c.Config.AddRequestHeader(req)
	response, err := c.Client.Do(req)
	if err != nil {
		return nil, err
	}
	res := Response(*response)
	return &res, nil
}
555325
func (ccaClient CcaApiClient) Do(request CcaRequest) (*CcaResponse, error) {
	var bodyBuffer io.Reader
	if request.Body != nil {
		bodyBuffer = bytes.NewBuffer(request.Body)
	}
	method := request.Method
	if method == "" {
		method = "GET"
	}
	req, err := http.NewRequest(request.Method, ccaClient.buildUrl(request.Endpoint, request.Options), bodyBuffer)
	if err != nil {
		return nil, err
	}
	req.Header.Add(API_KEY_HEADER, ccaClient.apiKey)
	req.Header.Add("Content-Type", "application/json")
	resp, err := ccaClient.httpClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	return NewCcaResponse(resp)
}
1280141
func (c *Client) Do(request *http.Request) (*http.Response, error) {
	request.Close = true

	var bodyReader *bytes.Reader

	if request.Body != nil {
		reqData, err := ioutil.ReadAll(request.Body)
		if err != nil {
			return nil, err
		}
		bodyReader = bytes.NewReader(reqData)
		request.Body = ioutil.NopCloser(bodyReader) // prevents closing the body between retries
	}

	multiErr := &valkyrie.MultiError{}
	var response *http.Response

	for i := 0; i <= c.retryCount; i++ {
		if response != nil {
			response.Body.Close()
		}

		var err error
		response, err = c.client.Do(request)
		if bodyReader != nil {
			// Reset the body reader after the request since at this point it's already read
			// Note that it's safe to ignore the error here since the 0,0 position is always valid
			_, _ = bodyReader.Seek(0, 0)
		}

		if err != nil {
			multiErr.Push(err.Error())

			backoffTime := c.retrier.NextInterval(i)
			time.Sleep(backoffTime)
			continue
		}

		if response.StatusCode >= http.StatusInternalServerError {
			backoffTime := c.retrier.NextInterval(i)
			time.Sleep(backoffTime)
			continue
		}

		multiErr = &valkyrie.MultiError{} // Clear errors if any iteration succeeds
		break
	}

	return response, multiErr.HasError()
}
775867
func (c *Client) Do(ctx context.Context, r *Request) (*http.Response, error) {
	req, err := r.toHTTP(ctx, c.config)
	if err != nil {
		return nil, err
	}
	c.logRequest(req)
	resp, err := c.config.HTTPClient.Do(req)
	c.logResponse(resp)
	return resp, err
}