// SendRequest sends a request to the server
10765
func (c *Client) SendRequest(route string, data []byte) (uint, error) {
	return c.sendMsg(message.Request, route, data)
}
1184744
func (es *eventStream) sendQuery(q *serf.Query) error {
	id := es.client.RegisterQuery(q)

	header := responseHeader{
		Seq:   es.seq,
		Error: "",
	}
	rec := queryEventRecord{
		Event:   q.EventType().String(),
		ID:      id,
		LTime:   q.LTime,
		Name:    q.Name,
		Payload: q.Payload,
	}
	return es.client.Send(&header, &rec)
}
133168
func (c *Connection) sendQuery(q Query) error {
	buf := &bytes.Buffer{}
	buf.Grow(respHeaderLen)
	buf.Write(buf.Bytes()[:respHeaderLen]) // reserve for header
	enc := json.NewEncoder(buf)

	// Build query
	err := enc.Encode(q.Build())
	if err != nil {
		return RQLDriverError{rqlError(fmt.Sprintf("Error building query: %s", err.Error()))}
	}

	b := buf.Bytes()

	// Write header
	binary.LittleEndian.PutUint64(b, uint64(q.Token))
	binary.LittleEndian.PutUint32(b[8:], uint32(len(b)-respHeaderLen))

	// Set timeout
	if c.opts.WriteTimeout != 0 {
		c.Conn.SetWriteDeadline(time.Now().Add(c.opts.WriteTimeout))
	}

	// Send the JSON encoding of the query itself.
	if err = c.writeData(b); err != nil {
		c.setBad()
		return RQLConnectionError{rqlError(err.Error())}
	}

	return nil
}
626768
func (c *Core) ForwardRequest(req *http.Request) (int, http.Header, []byte, error) {
	c.requestForwardingConnectionLock.RLock()
	defer c.requestForwardingConnectionLock.RUnlock()

	if c.rpcForwardingClient == nil {
		return 0, nil, nil, ErrCannotForward
	}

	origPath := req.URL.Path
	defer func() {
		req.URL.Path = origPath
	}()

	req.URL.Path = req.Context().Value("original_request_path").(string)

	freq, err := forwarding.GenerateForwardedRequest(req)
	if err != nil {
		c.logger.Error("error creating forwarding RPC request", "error", err)
		return 0, nil, nil, fmt.Errorf("error creating forwarding RPC request")
	}
	if freq == nil {
		c.logger.Error("got nil forwarding RPC request")
		return 0, nil, nil, fmt.Errorf("got nil forwarding RPC request")
	}
	resp, err := c.rpcForwardingClient.ForwardRequest(c.rpcClientConnContext, freq)
	if err != nil {
		c.logger.Error("error during forwarded RPC request", "error", err)
		return 0, nil, nil, fmt.Errorf("error during forwarding RPC request")
	}

	var header http.Header
	if resp.HeaderEntries != nil {
		header = make(http.Header)
		for k, v := range resp.HeaderEntries {
			header[k] = v.Values
		}
	}

	// If we are a perf standby and the request was forwarded to the active node
	// we should attempt to wait for the WAL to ship to offer best effort read after
	// write guarantees
	if c.perfStandby && resp.LastRemoteWal > 0 {
		WaitUntilWALShipped(req.Context(), c, resp.LastRemoteWal)
	}

	return int(resp.StatusCode), header, resp.Body, nil
}
304676
func (c *Client) Request() *Request {
	req := NewRequest()
	req.SetClient(c)
	return req
}
278678
func (s *RegionRequestSender) SendReq(bo *Backoffer, req *tikvrpc.Request, regionID RegionVerID, timeout time.Duration) (*tikvrpc.Response, error) {
	resp, _, err := s.SendReqCtx(bo, req, regionID, timeout)
	return resp, err
}
503834
func (r *redisRequester) Request() error {
	_, err := r.conn.Do(r.command, r.args...)
	return err
}
375730
func (c *rpcClient) SendRequest(ctx context.Context, addr string, req *tikvrpc.Request, timeout time.Duration) (*tikvrpc.Response, error) {
	start := time.Now()
	reqType := req.Type.String()
	storeID := strconv.FormatUint(req.Context.GetPeer().GetStoreId(), 10)
	defer func() {
		metrics.TiKVSendReqHistogram.WithLabelValues(reqType, storeID).Observe(time.Since(start).Seconds())
	}()

	connArray, err := c.getConnArray(addr)
	if err != nil {
		return nil, errors.Trace(err)
	}

	if config.GetGlobalConfig().TiKVClient.MaxBatchSize > 0 {
		if batchReq := req.ToBatchCommandsRequest(); batchReq != nil {
			return sendBatchRequest(ctx, addr, connArray, batchReq, timeout)
		}
	}

	if req.IsDebugReq() {
		client := debugpb.NewDebugClient(connArray.Get())
		ctx1, cancel := context.WithTimeout(ctx, timeout)
		defer cancel()
		return tikvrpc.CallDebugRPC(ctx1, client, req)
	}

	client := tikvpb.NewTikvClient(connArray.Get())

	if req.Type != tikvrpc.CmdCopStream {
		ctx1, cancel := context.WithTimeout(ctx, timeout)
		defer cancel()
		return tikvrpc.CallRPC(ctx1, client, req)
	}

	// Coprocessor streaming request.
	// Use context to support timeout for grpc streaming client.
	ctx1, cancel := context.WithCancel(ctx)
	defer cancel()
	resp, err := tikvrpc.CallRPC(ctx1, client, req)
	if err != nil {
		return nil, errors.Trace(err)
	}

	// Put the lease object to the timeout channel, so it would be checked periodically.
	copStream := resp.CopStream
	copStream.Timeout = timeout
	copStream.Lease.Cancel = cancel
	connArray.streamTimeout <- &copStream.Lease

	// Read the first streaming response to get CopStreamResponse.
	// This can make error handling much easier, because SendReq() retry on
	// region error automatically.
	var first *coprocessor.Response
	first, err = copStream.Recv()
	if err != nil {
		if errors.Cause(err) != io.EOF {
			return nil, errors.Trace(err)
		}
		logutil.Logger(context.Background()).Debug("copstream returns nothing for the request.")
	}
	copStream.Response = first
	return resp, nil
}
1159000
func (c *HTTPClient) Send(req *http.Request) HTTPClientInterface {
	c.request = req
	return c
}
1242593
func (d *DNSProvider) sendRequest(method, resource string, payload interface{}, queryArgs map[string]string) (*http.Response, error) {
	url := fmt.Sprintf("%s/Services/REST/v1/%s", d.config.BaseURL, resource)

	body, err := json.Marshal(payload)
	if err != nil {
		return nil, fmt.Errorf("bluecat: %v", err)
	}

	req, err := http.NewRequest(method, url, bytes.NewReader(body))
	if err != nil {
		return nil, fmt.Errorf("bluecat: %v", err)
	}
	req.Header.Set("Content-Type", "application/json")
	if len(d.token) > 0 {
		req.Header.Set("Authorization", d.token)
	}

	// Add all query parameters
	q := req.URL.Query()
	for argName, argVal := range queryArgs {
		q.Add(argName, argVal)
	}
	req.URL.RawQuery = q.Encode()
	resp, err := d.config.HTTPClient.Do(req)
	if err != nil {
		return nil, fmt.Errorf("bluecat: %v", err)
	}

	if resp.StatusCode >= 400 {
		errBytes, _ := ioutil.ReadAll(resp.Body)
		errResp := string(errBytes)
		return nil, fmt.Errorf("bluecat: request failed with HTTP status code %d\n Full message: %s",
			resp.StatusCode, errResp)
	}

	return resp, nil
}
1315834
func (rm *retrieveManager) sendReq(reqID uint64, req *distReq, val validatorFunc) *sentReq {
	r := &sentReq{
		rm:       rm,
		req:      req,
		id:       reqID,
		sentTo:   make(map[distPeer]sentReqToPeer),
		stopCh:   make(chan struct{}),
		eventsCh: make(chan reqPeerEvent, 10),
		validate: val,
	}

	canSend := req.canSend
	req.canSend = func(p distPeer) bool {
		// add an extra check to canSend: the request has not been sent to the same peer before
		r.lock.RLock()
		_, sent := r.sentTo[p]
		r.lock.RUnlock()
		return !sent && canSend(p)
	}

	request := req.request
	req.request = func(p distPeer) func() {
		// before actually sending the request, put an entry into the sentTo map
		r.lock.Lock()
		r.sentTo[p] = sentReqToPeer{false, make(chan bool, 1)}
		r.lock.Unlock()
		return request(p)
	}
	rm.lock.Lock()
	rm.sentReqs[reqID] = r
	rm.lock.Unlock()

	go r.retrieveLoop()
	return r
}
848389
func (m *MockNetworkEntity) SendRequest(ctx context.Context, serverID, route string, v interface{}) (*protos.Response, error) {
	ret := m.ctrl.Call(m, "SendRequest", ctx, serverID, route, v)
	ret0, _ := ret[0].(*protos.Response)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
130700
func (c Client) SendRequest(r *PushRequest) (string, error) {
	// https://help.aliyun.com/document_detail/mobilepush/api-reference/api-list/Push.html?spm=5176.docmobilepush/api-reference/call-method/common-parameters.6.124.OBDIvc
	ps := parameters.NewParameterSet()
	ps.Add("Format", "JSON")
	ps.Add("RegionId", c.Region)
	ps.Add("Version", "2015-08-27")
	ps.Add("AccessKeyId", c.AccessKeyID)
	ps.Add("SignatureMethod", "HMAC-SHA1")
	ps.Add("Timestamp", time.Now().UTC().Format("2006-01-02T15:04:05Z"))
	ps.Add("SignatureVersion", "1.0")
	id, _ := uuid.NewV4()
	ps.Add("SignatureNonce", id.String())
	// basic
	ps.Add("Action", "Push")
	ps.Add("AppKey", r.AppKey)
	// destination
	ps.Add("Target", r.Target)
	ps.Add("TargetValue", r.TargetValue)
	ps.Add("DeviceType", strconv.Itoa(r.DeviceType))
	// push config
	ps.Add("Type", strconv.Itoa(r.Type))
	ps.Add("Title", r.Title)
	ps.Add("Summary", r.Summary)
	ps.Add("Body", r.Body)
	// ios specific
	ps.Add("Remind", strconv.FormatBool(r.Remind))
	if len(r.IOSMusic) > 0 {
		ps.Add("iOSMusic", r.IOSMusic)
	}
	if len(r.IOSBadge) > 0 {
		ps.Add("iOSBadge", r.IOSBadge)
	}
	if len(r.IOSExtParameters) > 0 {
		ps.Add("iOSExtParameters", r.IOSExtParameters)
	}
	if len(r.ApnsEnv) > 0 {
		ps.Add("ApnsEnv", r.ApnsEnv)
	}
	// android specific
	ps.Add("AndroidOpenType", strconv.Itoa(r.AndroidOpenType))
	if len(r.AndroidActivity) > 0 {
		ps.Add("AndroidActivity", r.AndroidActivity)
	}
	if len(r.AndroidMusic) > 0 {
		ps.Add("AndroidMusic", r.AndroidMusic)
	}
	if len(r.AndroidOpenURL) > 0 {
		ps.Add("AndroidOpenUrl", r.AndroidOpenURL)
	}
	if len(r.AndroidExtParameters) > 0 {
		ps.Add("AndroidExtParameters", r.AndroidExtParameters)
	}
	// push control
	if len(r.PushTime) > 0 {
		ps.Add("PushTime", r.PushTime)
	}
	ps.Add("StoreOffline", strconv.FormatBool(r.StoreOffline))
	if r.StoreOffline && len(r.ExpireTime) > 0 {
		ps.Add("ExpireTime", r.ExpireTime)
	}
	// trace
	if len(r.BatchNumber) > 0 {
		ps.Add("BatchNumber", r.BatchNumber)
	}

	ps.Add("Signature", ps.Sign(ps.GetStringToSign(), c.AccessKeySecret))
	resp, err := http.Get(baseURL + "?" + ps.Concatenate())
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(body), nil
}
891768
func sendCode(w http.ResponseWriter, r *http.Request) {
	sess, _ := globalSessions.SessionStart(w, r)
	bc, err := getBaiduClient(sess.SessionID())
	if err != nil {
		log.Println(err)
		return
	}
	r.ParseForm()
	verifyType := r.Form.Get("type")
	token := r.Form.Get("token")
	if token == "" {
		w.Write([]byte(`{"msg":"Token is null."}`))
		return
	}

	msg := bc.SendCodeToUser(verifyType, token)
	w.Write([]byte(`{"msg": "` + msg + `"}`))
}
653682
func (t *HTTPTransporter) SendVoteRequest(server Server, peer *Peer, req *RequestVoteRequest) *RequestVoteResponse {
	var b bytes.Buffer
	if _, err := req.Encode(&b); err != nil {
		traceln("transporter.rv.encoding.error:", err)
		return nil
	}

	url := fmt.Sprintf("%s%s", peer.ConnectionString, t.RequestVotePath())
	traceln(server.Name(), "POST", url)

	httpResp, err := t.httpClient.Post(url, "application/protobuf", &b)
	if httpResp == nil || err != nil {
		traceln("transporter.rv.response.error:", err)
		return nil
	}
	defer httpResp.Body.Close()

	resp := &RequestVoteResponse{}
	if _, err = resp.Decode(httpResp.Body); err != nil && err != io.EOF {
		traceln("transporter.rv.decoding.error:", err)
		return nil
	}

	return resp
}
951892
func (c *Client) Send(req *Request, res Response) error {
	// TODO: handle retry, timeouts, etc.
	return c.send(req, res)
}
1118249
func (c *Client) DoRequest(r *Request) (*http.Response, error) {
	req, err := r.toHTTP()
	if err != nil {
		return nil, err
	}
	return c.Do(req)
}