// Do sends an API request and returns the API response. The API response is
// decoded and stored in the value pointed to by v, or returned as an error if
// an API error has occurred.
358460
func (c *Client) Do(req *http.Request, v interface{}) (*http.Response, error) {
	// Make sure to close the connection after replying to this request
	req.Close = true

	resp, err := c.httpClient.Do(req)
	if err != nil {
		return resp, err
	}
	defer resp.Body.Close()

	if v != nil {
		err = json.NewDecoder(resp.Body).Decode(v)
	}

	if err != nil {
		return nil, fmt.Errorf("error reading response from %s %s: %s", req.Method, req.URL.RequestURI(), err)
	}

	return resp, nil
}
508220
func (m *MetaClient) Do(ctx context.Context, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) {
	type result struct {
		Response *http.Response
		Err      error
	}

	resps := make(chan (result))
	go func() {
		resp, err := m.client.Do(m.URL, path, method, authorizer, params, body)
		resps <- result{resp, err}
	}()

	select {
	case resp := <-resps:
		return resp.Response, resp.Err
	case <-ctx.Done():
		return nil, chronograf.ErrUpstreamTimeout
	}
}
1295253
func (n *Node) do(c *Call) error {
	err := n.send(c.req)
	if err == nil {
		err = c.Wait()
	}
	return err
}
355279
func (c *HTTPClient) Do(req *http.Request) (*http.Response, error) {
	ctx := req.Context()
	v := ctx.Value(RequestIDContextKey)
	if v != nil {
		req.Header.Set(requestIDHeader, v.(string))
	}
	st := time.Now()
	resp, err := c.Client.Do(req)

	logger := c.Logger
	if logger == nil {
		logger = log.DefaultLogger()
	}

	if err == nil && (c.Severity == 0 || !logger.Enabled(c.Severity)) {
		// successful logs are suppressed if c.Severity is 0 or
		// logger threshold is under c.Severity.
		return resp, err
	}

	fields := FieldsFromContext(ctx)
	fields[log.FnType] = "http"
	fields[log.FnResponseTime] = time.Since(st).Seconds()
	fields[log.FnHTTPMethod] = req.Method
	fields[log.FnURL] = req.URL.String()
	fields[log.FnStartAt] = st

	if err != nil {
		fields["error"] = err.Error()
		logger.Error("well: http", fields)
		return resp, err
	}

	fields[log.FnHTTPStatusCode] = resp.StatusCode
	logger.Log(c.Severity, "well: http", fields)
	return resp, err
}
684678
func (c *traceClient) Do(r *http.Request) (*http.Response, error) {
	InjectTrace(r)
	return c.Client.Do(r)
}
1097063
func (c *client) do(method string, resource string, payload string, authNeeded bool) (response []byte, err error) {
	connectTimer := time.NewTimer(c.httpTimeout)

	var rawurl string
	if strings.HasPrefix(resource, "http") {
		rawurl = resource
	} else {
		rawurl = fmt.Sprintf("%s%s/%s", API_BASE, API_VERSION, resource)
	}

	req, err := http.NewRequest(method, rawurl, strings.NewReader(payload))
	if err != nil {
		return
	}
	if method == "POST" || method == "PUT" {
		req.Header.Add("Content-Type", "application/json;charset=utf-8")
	}
	req.Header.Add("Accept", "application/json")

	// Auth
	if authNeeded {
		if len(c.apiKey) == 0 || len(c.apiSecret) == 0 {
			err = errors.New("You need to set API Key and API Secret to call this method")
			return
		}
		nonce := time.Now().UnixNano()
		q := req.URL.Query()
		q.Set("apikey", c.apiKey)
		q.Set("nonce", fmt.Sprintf("%d", nonce))
		req.URL.RawQuery = q.Encode()
		mac := hmac.New(sha512.New, []byte(c.apiSecret))
		_, err = mac.Write([]byte(req.URL.String()))
		sig := hex.EncodeToString(mac.Sum(nil))
		req.Header.Add("apisign", sig)
	}

	resp, err := c.doTimeoutRequest(connectTimer, req)
	if err != nil {
		return
	}

	defer resp.Body.Close()
	response, err = ioutil.ReadAll(resp.Body)
	//fmt.Println(fmt.Sprintf("reponse %s", response), err)
	if err != nil {
		return response, err
	}
	if resp.StatusCode != 200 {
		err = errors.New(resp.Status)
	}
	return response, err
}
1058874
func (h HttpTransport) do(req *http.Request, v interface{}) (*Response, error) {
	resp, err := h.httpDo(h.HTTPClient, req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	response := newResponse(resp)
	err = checkResponse(response)
	if err != nil {
		return response, err
	}

	if v != nil {
		err = json.Unmarshal(response.Body, v)
		if err != nil {
			return response, err
		}
	}

	return response, nil
}
715459
func (c Client) Do(ctx context.Context, method, path string) (*http.Response, error) {

	path = strings.Trim(path, "/")

	var body io.Reader

	if c.bytes != nil {
		buf := bytes.NewBuffer(*c.bytes)
		body = buf
	} else if c.json != nil {
		var buf bytes.Buffer
		if err := json.NewEncoder(&buf).Encode(*c.json); err != nil {
			return nil, err
		}
		body = &buf
	}

	url := c.config.URL + "/" + path
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, err
	}

	headers := map[string]string{}

	// Set authorization header for credentials.
	if c.config.Credentials.Bearer != nil {
		req.Header.Add("Authorization", fmt.Sprintf("%v %v", c.config.Credentials.Bearer.Scheme, c.config.Credentials.Bearer.Token))
	}

	// Copy custom headers from config.
	for key, value := range c.config.Headers {
		headers[key] = value
	}

	// Overwrite with headers set directly on client.
	for key, value := range c.headers {
		headers[key] = value
	}

	for key, value := range headers {
		req.Header.Add(key, value)
	}

	req = req.WithContext(ctx)

	logrus.WithFields(logrus.Fields{
		"method":  method,
		"url":     url,
		"headers": req.Header,
	}).Debug("Sending request.")

	resp, err := c.Client.Do(req)
	if resp != nil {
		// Only log for debug purposes. If an error occurred, the caller should handle
		// that. In the non-error case, the caller may not do anything.
		logrus.WithFields(logrus.Fields{
			"method":  method,
			"url":     url,
			"status":  resp.Status,
			"headers": resp.Header,
		}).Debug("Received response.")
	}

	return resp, err
}
816304
func (c *Client) Do(req *http.Request) (*http.Response, error) {
	err := Sign(c.auth, req)
	if err != nil {
		return nil, err
	}

	return c.client.Do(req)
}
119577
func (c *Client) Do(req *http.Request) (*http.Response, error) {
	resp, err := c.httpClient.Do(req)
	if err != nil {
		return nil, err
	}

	return resp, nil
}
1038655
func (doer httpRequestDoer) Do(req *http.Request) (*http.Response, error) {
	return doer.DoWithBody(req, nil)
}
1166646
func (c *Client) Do(method, url string, headers map[string][]string, body io.Reader) (client.Status, map[string][]string, io.ReadCloser, error) {
	if headers == nil {
		headers = make(map[string][]string)
	}
	u, err := stdurl.ParseRequestURI(url)
	if err != nil {
		return client.Status{}, nil, nil, err
	}
	host := u.Host
	headers["Host"] = []string{host}
	if !strings.Contains(host, ":") {
		host += ":80"
	}
	path := u.Path
	if path == "" {
		path = "/"
	}
	if u.RawQuery != "" {
		path += "?" + u.RawQuery
	}
	conn, err := c.dialer.Dial("tcp", host)
	if err != nil {
		return client.Status{}, nil, nil, err
	}
	req := toRequest(method, path, nil, headers, body)
	if err := conn.WriteRequest(req); err != nil {
		return client.Status{}, nil, nil, err
	}
	resp, err := conn.ReadResponse()
	if err != nil {
		return client.Status{}, nil, nil, err
	}
	_, rstatus, rheaders, rbody := fromResponse(resp)
	if headerValue(rheaders, "Content-Encoding") == "gzip" {
		rbody, err = gzip.NewReader(rbody)
	}
	rc := &readCloser{rbody, conn}
	if rstatus.IsRedirect() && c.FollowRedirects {
		// consume the response body
		_, err := io.Copy(ioutil.Discard, rc)
		if err := firstErr(err, rc.Close()); err != nil {
			return client.Status{}, nil, nil, err // TODO
		}
		loc := headerValue(rheaders, "Location")
		if strings.HasPrefix(loc, "/") {
			loc = fmt.Sprintf("http://%s%s", host, loc)
		}
		return c.Do(method, loc, headers, body)
	}
	return rstatus, rheaders, rc, err
}
58602
func Do(w http.ResponseWriter, req *http.Request) {
	state, lastTry, lastSuccess := GetState()

	w.Header().Set("Content-Type", "application/json")

	var healthStateInfo healthResponse
	if len(state) > 0 {
		w.WriteHeader(http.StatusInternalServerError)
		healthStateInfo = healthResponse{Status: "error", Errors: &[]healthError{}}
		// add errors to healthStateInfo and set its Status to "error"
		for stateKey := range state {
			*(healthStateInfo.Errors) = append(*(healthStateInfo.Errors), healthError{Namespace: stateKey, ErrorMessage: state[stateKey].Error()})
		}
	} else if lastTry.IsZero() {
		w.WriteHeader(http.StatusTooManyRequests)
		return
	} else {
		w.WriteHeader(http.StatusOK)
		healthStateInfo.Status = "OK"
	}
	healthStateInfo.LastChecked = lastTry
	healthStateInfo.LastSuccess = lastSuccess

	healthStateJSON, err := json.Marshal(healthStateInfo)
	if err != nil {
		log.ErrorC("marshal json", err, log.Data{"struct": healthStateInfo})
		return
	}
	if _, err = w.Write(healthStateJSON); err != nil {
		log.ErrorC("writing json body", err, log.Data{"json": string(healthStateJSON)})
	}
}
1049677
func (c *Client) do(method, path string, ct contentType, body ...[]byte) (*rbody.APIResponse, error) {
	var (
		rsp *http.Response
		err error
		req *http.Request
	)
	switch method {
	case "GET":
		req, err = http.NewRequest(method, c.prefix+path, nil)
		if err != nil {
			return nil, err
		}
		addAuth(req, c.Username, c.Password)
		rsp, err = c.http.Do(req)
		if err != nil {
			if strings.Contains(err.Error(), "tls: oversized record") || strings.Contains(err.Error(), "malformed HTTP response") {
				return nil, fmt.Errorf("error connecting to API URI: %s. Do you have an http/https mismatch?", c.URL)
			}
			return nil, fmt.Errorf("URL target is not available. %v", err)
		}
		defer rsp.Body.Close()
	case "PUT":
		var b *bytes.Reader
		if len(body) == 0 {
			b = bytes.NewReader([]byte{})
		} else {
			b = bytes.NewReader(body[0])
		}
		req, err = http.NewRequest(method, c.prefix+path, b)
		if err != nil {
			return nil, fmt.Errorf("URL target is not available. %v", err)
		}
		addAuth(req, c.Username, c.Password)
		req.Header.Add("Content-Type", ct.String())

		rsp, err = c.http.Do(req)
		if err != nil {
			if strings.Contains(err.Error(), "tls: oversized record") || strings.Contains(err.Error(), "malformed HTTP response") {
				return nil, fmt.Errorf("error connecting to API URI: %s. Do you have an http/https mismatch?", c.URL)
			}
			return nil, fmt.Errorf("URL target is not available. %v", err)
		}
		defer rsp.Body.Close()
	case "DELETE":
		var b *bytes.Reader
		if len(body) == 0 {
			b = bytes.NewReader([]byte{})
		} else {
			b = bytes.NewReader(body[0])
		}

		req, err = http.NewRequest(method, c.prefix+path, b)
		if err != nil {
			return nil, fmt.Errorf("URL target is not available. %v", err)
		}
		addAuth(req, c.Username, c.Password)
		req.Header.Add("Content-Type", "application/json")
		rsp, err = c.http.Do(req)
		if err != nil {
			if strings.Contains(err.Error(), "tls: oversized record") || strings.Contains(err.Error(), "malformed HTTP response") {
				return nil, fmt.Errorf("error connecting to API URI: %s. Do you have an http/https mismatch?", c.URL)
			}
			return nil, fmt.Errorf("URL target is not available. %v", err)
		}
		defer rsp.Body.Close()
	case "POST":
		var b *bytes.Reader
		if len(body) == 0 {
			b = bytes.NewReader([]byte{})
		} else {
			b = bytes.NewReader(body[0])
		}
		req, err = http.NewRequest(method, c.prefix+path, b)
		if err != nil {
			return nil, err
		}
		addAuth(req, c.Username, c.Password)
		req.Header.Add("Content-Type", ct.String())
		rsp, err = c.http.Do(req)
		if err != nil {
			if strings.Contains(err.Error(), "tls: oversized record") || strings.Contains(err.Error(), "malformed HTTP response") {
				return nil, fmt.Errorf("error connecting to API URI: %s. Do you have an http/https mismatch?", c.URL)
			}
			return nil, fmt.Errorf("URL target is not available. %v", err)
		}
		defer rsp.Body.Close()
	}
	return httpRespToAPIResp(rsp)
}
1122308
func (c *Client) Do(req *http.Request) (*http.Response, error) {
	req.Header = c.ExtraHeadersFor(req)

	return c.do(req, "", nil)
}
323699
func (l *Client) Do(r *http.Request, response, data interface{}) error {
	// make the request

	res, err := l.client.Do(r)
	if err != nil {
		return err
	}
	defer res.Body.Close()

	// get the response
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return err
	}

	// if we have some struct to unmarshal body into, do that and return
	if response != nil {
		err = buildRespJSON(b, response, data)
		if err != nil {
			return err
		}
		switch rt := response.(type) {
		case *ApiResp:
			// if we have an invalid response code error out
			if res.StatusCode >= 301 {
				return fmt.Errorf(rt.Message)
			}
		}
	}

	// if we have an invalid response code error out
	if res.StatusCode >= 301 {
		return fmt.Errorf("Received non-successful response: %d", res.StatusCode)
	}

	return nil
}
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()
}