// Request performs a synchronous request to the system under test.
518714
func (r *redisPubSubRequester) Request() error {
	if err := r.publishConn.Send("PUBLISH", r.channel, r.msg); err != nil {
		return err
	}
	if err := r.publishConn.Flush(); err != nil {
		return err
	}
	switch recv := r.subscribeConn.Receive().(type) {
	case error:
		return recv
	default:
		return nil
	}
}
867073
func (c *Conn) Request(m *protocol.Message) (*protocol.Message, error) {
	m.Id = uint64(rand.Int63())
	m.ResponseRequired = true
	if err := c.Send(m); err != nil {
		return nil, err
	}

	timeout := make(chan bool, 1)
	go func() {
		time.Sleep(10 * time.Second)
		timeout <- true
	}()
	resp := make(chan *protocol.Message, 1)
	c.expectedMessages[m.Id] = resp

	var msg *protocol.Message
	var err error
	select {
	case msg = <-resp:
	case <-timeout:
		err = Timeout
	}
	delete(c.expectedMessages, m.Id)
	return msg, err
}
1293496
func (c *Client) Request(ctx context.Context, requestedAddr tcpip.Address) (cfg Config, reterr error) {
	// TODO(b/127321246): remove calls to {Add,Remove}Address when they're no
	// longer required to send and receive broadcast.
	if err := c.stack.AddAddressWithOptions(c.nicid, ipv4.ProtocolNumber, tcpipHeader.IPv4Any, stack.NeverPrimaryEndpoint); err != nil && err != tcpip.ErrDuplicateAddress {
		return Config{}, fmt.Errorf("dhcp: AddAddressWithOptions(): %s", err)
	}
	defer c.stack.RemoveAddress(c.nicid, tcpipHeader.IPv4Any)

	var wq waiter.Queue
	ep, err := c.stack.NewEndpoint(udp.ProtocolNumber, ipv4.ProtocolNumber, &wq)
	if err != nil {
		return Config{}, fmt.Errorf("dhcp: NewEndpoint(): %s", err)
	}
	defer ep.Close()
	if err := ep.SetSockOpt(tcpip.BroadcastOption(1)); err != nil {
		return Config{}, fmt.Errorf("dhcp: SetSockOpt(BroadcastOption): %s", err)
	}
	if err := ep.Bind(tcpip.FullAddress{
		Addr: tcpipHeader.IPv4Any,
		Port: ClientPort,
		NIC:  c.nicid,
	}); err != nil {
		return Config{}, fmt.Errorf("dhcp: Bind(): %s", err)
	}

	var xid [4]byte
	if _, err := rand.Read(xid[:]); err != nil {
		return Config{}, fmt.Errorf("dhcp: rand.Read(): %s", err)
	}

	// DHCPDISCOVERY
	discOpts := options{
		{optDHCPMsgType, []byte{byte(dhcpDISCOVER)}},
		{optParamReq, []byte{
			1,  // request subnet mask
			3,  // request router
			15, // domain name
			6,  // domain name server
		}},
	}
	if requestedAddr != "" {
		discOpts = append(discOpts, option{optReqIPAddr, []byte(requestedAddr)})
	}
	var clientID []byte
	if len(c.linkAddr) == 6 {
		clientID = append(
			[]byte{1}, // RFC 1700: Hardware Type [Ethernet = 1]
			c.linkAddr...,
		)
		discOpts = append(discOpts, option{optClientID, clientID})
	}
	h := make(header, headerBaseSize+discOpts.len()+1)
	h.init()
	h.setOp(opRequest)
	copy(h.xidbytes(), xid[:])
	h.setBroadcast()
	copy(h.chaddr(), c.linkAddr)
	h.setOptions(discOpts)

	serverAddr := &tcpip.FullAddress{
		Addr: tcpipHeader.IPv4Broadcast,
		Port: ServerPort,
		NIC:  c.nicid,
	}
	wopts := tcpip.WriteOptions{
		To: serverAddr,
	}
	var resCh <-chan struct{}
	if _, resCh, err = ep.Write(tcpip.SlicePayload(h), wopts); err != nil && resCh == nil {
		return Config{}, fmt.Errorf("dhcp discovery write: %v", err)
	}

	if resCh != nil {
		select {
		case <-resCh:
		case <-ctx.Done():
			return Config{}, fmt.Errorf("dhcp client address resolution: %v", tcpip.ErrAborted)
		}

		if _, _, err := ep.Write(tcpip.SlicePayload(h), wopts); err != nil {
			return Config{}, fmt.Errorf("dhcp discovery write: %v", err)
		}
	}

	we, ch := waiter.NewChannelEntry(nil)
	wq.EventRegister(&we, waiter.EventIn)
	defer wq.EventUnregister(&we)

	// DHCPOFFER
	var opts options
	for {
		v, _, err := ep.Read(nil)
		if err == tcpip.ErrWouldBlock {
			select {
			case <-ch:
				continue
			case <-ctx.Done():
				return Config{}, fmt.Errorf("reading dhcp offer: %v", tcpip.ErrAborted)
			}
		}
		h = header(v)
		var valid bool
		var e error
		opts, valid, e = loadDHCPReply(h, dhcpOFFER, xid[:])
		if !valid {
			if e != nil {
				// TODO: handle all the errors?
				// TODO: report malformed server responses
			}
			continue
		}
		break
	}

	var ack bool
	if err := cfg.decode(opts); err != nil {
		return Config{}, fmt.Errorf("dhcp offer: %v", err)
	}

	// DHCPREQUEST
	addr := tcpip.Address(h.yiaddr())
	if err := c.stack.AddAddressWithOptions(c.nicid, ipv4.ProtocolNumber, addr, stack.FirstPrimaryEndpoint); err != nil {
		if err != tcpip.ErrDuplicateAddress {
			return Config{}, fmt.Errorf("adding address: %v", err)
		}
	}
	defer func() {
		if !ack || reterr != nil {
			c.stack.RemoveAddress(c.nicid, addr)
			addr = ""
			cfg = Config{Error: reterr}
		}

		c.mu.Lock()
		oldAddr := c.addr
		c.addr = addr
		c.cfg = cfg
		c.mu.Unlock()

		// Clean up addresses before calling acquiredFunc
		// so nothing else uses them by mistake.
		//
		// (The deferred RemoveAddress call above silently errors.)
		c.stack.RemoveAddress(c.nicid, tcpipHeader.IPv4Any)

		if c.acquiredFunc != nil {
			c.acquiredFunc(oldAddr, addr, cfg)
		}
		if requestedAddr != "" && requestedAddr != addr {
			c.stack.RemoveAddress(c.nicid, requestedAddr)
		}
	}()
	h.init()
	h.setOp(opRequest)
	for i, b := 0, h.yiaddr(); i < len(b); i++ {
		b[i] = 0
	}
	for i, b := 0, h.siaddr(); i < len(b); i++ {
		b[i] = 0
	}
	for i, b := 0, h.giaddr(); i < len(b); i++ {
		b[i] = 0
	}
	reqOpts := []option{
		{optDHCPMsgType, []byte{byte(dhcpREQUEST)}},
		{optReqIPAddr, []byte(addr)},
		{optDHCPServer, []byte(cfg.ServerAddress)},
	}
	if len(clientID) != 0 {
		reqOpts = append(reqOpts, option{optClientID, clientID})
	}
	h.setOptions(reqOpts)
	if _, _, err := ep.Write(tcpip.SlicePayload(h), wopts); err != nil {
		return Config{}, fmt.Errorf("dhcp discovery write: %v", err)
	}

	// DHCPACK
	for {
		v, _, err := ep.Read(nil)
		if err == tcpip.ErrWouldBlock {
			select {
			case <-ch:
				continue
			case <-ctx.Done():
				return Config{}, fmt.Errorf("reading dhcp ack: %v", tcpip.ErrAborted)
			}
		}
		h = header(v)
		var valid bool
		var e error
		opts, valid, e = loadDHCPReply(h, dhcpACK, xid[:])
		if !valid {
			if e != nil {
				// TODO: handle all the errors?
				// TODO: report malformed server responses
			}
			if opts, valid, _ = loadDHCPReply(h, dhcpNAK, xid[:]); valid {
				if msg := opts.message(); msg != "" {
					return Config{}, fmt.Errorf("dhcp: NAK %q", msg)
				}
				return Config{}, fmt.Errorf("dhcp: NAK with no message")
			}
			continue
		}
		break
	}
	ack = true
	return cfg, nil
}
938593
func (c *Client) request(params *url.Values, v *Response) error {
	var body string
	if params != nil {
		body = params.Encode()
	}

	method := "GET"
	requestURL := fmt.Sprintf("%v/?%s", c.BaseURL, body)
	var requestBody io.Reader
	if c.UsePost {
		method = "POST"
		requestURL = c.BaseURL.String()
		requestBody = strings.NewReader(body)
	}
	request, err := http.NewRequest(method, requestURL, requestBody)
	if err != nil {
		return err
	}

	log.Debugf("HTTP REQUEST: %s %s %s", method, requestURL, body)

	if c.UsePost {
		request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	}
	request.Header.Add("Accept", "application/json")
	request.Header.Add("User-Agent", "LinodeGo/"+ClientVersion+" Go/"+runtime.Version())

	response, err := c.HTTPClient.Do(request)
	if err != nil {
		log.Errorf("Failed to get API response: %v", err)
		return err
	}

	defer response.Body.Close()

	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Errorf("Failed to parse API response: %v", err)
		return err
	}

	log.Debugf("HTTP RESPONSE: %s", string(responseBody))

	// Status code 500 is a server error and means nothing can be done at this point.
	if response.StatusCode != 200 {
		return ErrUnexpectedResponse
	}

	if err = json.Unmarshal(responseBody, v); err != nil {
		return err
	}

	if len(v.Errors) > 0 {
		if v.Errors[0].ErrorCode == 4 {
			return ErrAuthentication
		}
		// Need to return all errors to client. Perhaps wrap the error structure as a property for a custom error class
		return errors.New(fmt.Sprintf("API Error: %s, Code %d", v.Errors[0].ErrorMessage, v.Errors[0].ErrorCode))
	}

	return nil
}
279706
func request(c *messagebird.Client, v interface{}, method, path string, data interface{}) error {
	return c.Request(v, method, fmt.Sprintf("%s/%s", apiRoot, path), data)
}
984154
func (c *Client) Request(method, path string, body io.Reader, v interface{}) error {
	req, err := http.NewRequest(method, c.URL+path, body)
	if err != nil {
		return err
	}

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

	if c.authCredentials != nil {
		credentials := fmt.Sprintf("%s:%s", c.authCredentials.username, c.authCredentials.password)
		b64credentials := base64.StdEncoding.EncodeToString([]byte(credentials))
		req.Header.Add("Authorization", fmt.Sprintf("Basic %s", b64credentials))
	} else if c.awsCredentials != nil {
		req = awsauth.Sign4(req, awsauth.Credentials(*c.awsCredentials))
		if req == nil {
			return errors.New("elastic: error signing request")
		}
	}

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

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

	if res.StatusCode >= 300 {
		return fmt.Errorf("%s: %s", res.Status, b)
	}

	if v != nil {
		return json.Unmarshal(b, v)
	}

	return nil
}
1367968
func asyncRequest(request *Request, response *Response, c chan int) {
	syncRequest(request, response)
	c <- 1
}
1014132
func (l *Linode) Request(action string, params Parameters, result interface{}) (*Response, error) {
	// Initialize the request.
	req, err := http.NewRequest("GET", l.apiEndpoint, nil)
	if err != nil {
		return nil, NewError(err)
	}
	params.Set(apiAction, action)
	params.Set(apiKey, l.apiKey)
	req.URL.RawQuery = params.Encode()

	// Make the request.
	resp, err := client.Do(req)
	if err != nil {
		return nil, NewError(err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, NewError(fmt.Errorf("Expected status code %d, received %d", http.StatusOK, resp.StatusCode))
	}

	// Decode the response.
	var response *Response
	decoder := json.NewDecoder(resp.Body)
	if err = decoder.Decode(&response); err != nil {
		return nil, NewError(err)
	}

	// Decode the raw data into action-specific data.
	if result != nil {
		if err = json.Unmarshal(response.RawData, &result); err != nil {
			return nil, NewError(err)
		}
		response.Data = result
	}

	// If we have errors in the response, return both the response as well
	// as an API error.
	if len(response.Errors) != 0 {
		return response, NewApiError(response.Errors[0].Code, response.Errors[0].Message)
	}
	return response, nil
}
369013
func (brq *blockRetrievalQueue) request(ctx context.Context,
	priority int, kmd libkey.KeyMetadata, ptr data.BlockPointer, block data.Block,
	lifetime data.BlockCacheLifetime, action BlockRequestAction) <-chan error {
	brq.vlog.CLogf(ctx, libkb.VLog2,
		"Request of %v, action=%s, priority=%d", ptr, action, priority)

	// Only continue if we haven't been shut down
	brq.doneLock.RLock()
	defer brq.doneLock.RUnlock()

	ch := make(chan error, 1)
	select {
	case <-brq.doneCh:
		ch <- io.EOF
		if action.PrefetchTracked() {
			brq.Prefetcher().CancelPrefetch(ptr)
		}
		return ch
	default:
	}
	if block == nil {
		ch <- errors.New("nil block passed to blockRetrievalQueue.Request")
		if action.PrefetchTracked() {
			brq.Prefetcher().CancelPrefetch(ptr)
		}
		return ch
	}

	// Check caches before locking the mutex.
	prefetchStatus, err := brq.checkCaches(ctx, kmd, ptr, block, action)
	if err == nil {
		if action != BlockRequestSolo {
			brq.vlog.CLogf(
				ctx, libkb.VLog2, "Found %v in caches: %s", ptr, prefetchStatus)
		}
		if action.PrefetchTracked() {
			brq.Prefetcher().ProcessBlockForPrefetch(ctx, ptr, block, kmd,
				priority, lifetime, prefetchStatus, action)
		}
		ch <- nil
		return ch
	}
	err = checkDataVersion(brq.config, data.Path{}, ptr)
	if err != nil {
		if action.PrefetchTracked() {
			brq.Prefetcher().CancelPrefetch(ptr)
		}
		ch <- err
		return ch
	}

	bpLookup := blockPtrLookup{ptr, reflect.TypeOf(block)}

	brq.mtx.Lock()
	defer brq.mtx.Unlock()
	// We might have to retry if the context has been canceled.  This loop will
	// iterate a maximum of 2 times. It either hits the `break` statement at
	// the bottom on the first iteration, or the `continue` statement first
	// which causes it to `break` on the next iteration.
	var br *blockRetrieval
	for {
		exists := false
		br, exists = brq.ptrs[bpLookup]
		if !exists {
			// Add to the heap
			br = &blockRetrieval{
				blockPtr:       ptr,
				kmd:            kmd,
				index:          -1,
				priority:       priority,
				insertionOrder: brq.insertionCount,
				cacheLifetime:  lifetime,
				action:         action,
			}
			br.ctx, br.cancelFunc = NewCoalescingContext(ctx)
			brq.insertionCount++
			brq.ptrs[bpLookup] = br
			heap.Push(brq.heap, br)
			brq.notifyWorker(priority)
		} else {
			err := br.ctx.AddContext(ctx)
			if err == context.Canceled {
				// We need to delete the request pointer, but we'll still let
				// the existing request be processed by a worker.
				delete(brq.ptrs, bpLookup)
				continue
			}
		}
		break
	}
	if br.index == -1 {
		// Log newly-scheduled requests via the normal logger, so we
		// can understand why the bserver fetches certain blocks, and
		// be able to time the request from start to finish.
		brq.log.CDebugf(ctx,
			"Scheduling request of %v, action=%s, priority=%d",
			ptr, action, priority)
	}
	br.reqMtx.Lock()
	defer br.reqMtx.Unlock()
	br.requests = append(br.requests, &blockRetrievalRequest{
		block:  block,
		doneCh: ch,
	})
	if lifetime > br.cacheLifetime {
		br.cacheLifetime = lifetime
	}
	oldPriority := br.priority
	if priority > oldPriority {
		br.priority = priority
		// If the new request priority is higher, elevate the retrieval in the
		// queue.  Skip this if the request is no longer in the queue (which
		// means it's actively being processed).
		if br.index != -1 {
			heap.Fix(brq.heap, br.index)
			if (oldPriority < defaultOnDemandRequestPriority &&
				priority >= defaultOnDemandRequestPriority) ||
				(oldPriority <= throttleRequestPriority &&
					priority > throttleRequestPriority) {
				// We've crossed the priority threshold for a given
				// worker type, so we now need a worker for the new
				// priority level to pick up the request.  This means
				// that we might have up to two workers "activated"
				// per request. However, they won't leak because if a
				// worker sees an empty queue, it continues merrily
				// along.
				brq.notifyWorker(priority)
			}
		}
	}
	// Update the action if needed.
	brq.vlog.CLogf(
		ctx, libkb.VLog2, "Combining actions %s and %s", action, br.action)
	br.action = action.Combine(br.action)
	brq.vlog.CLogf(ctx, libkb.VLog2, "Got action %s", br.action)
	return ch
}
69743
func (r *BloomRequest) Request(reqID uint64, peer *peer) error {
	peer.Log().Debug("Requesting BloomBits", "bloomTrie", r.BloomTrieNum, "bitIdx", r.BitIdx, "sections", r.SectionIndexList)
	reqs := make([]HelperTrieReq, len(r.SectionIndexList))

	var encNumber [10]byte
	binary.BigEndian.PutUint16(encNumber[:2], uint16(r.BitIdx))

	for i, sectionIdx := range r.SectionIndexList {
		binary.BigEndian.PutUint64(encNumber[2:], sectionIdx)
		reqs[i] = HelperTrieReq{
			Type:    htBloomBits,
			TrieIdx: r.BloomTrieNum,
			Key:     common.CopyBytes(encNumber[:]),
		}
	}
	return peer.RequestHelperTrieProofs(reqID, r.GetCost(peer), reqs)
}
753495
func (m *MockisBatchRequest_Request_Request) isBatchRequest_Request_Request() {
	m.ctrl.T.Helper()
	m.ctrl.Call(m, "isBatchRequest_Request_Request")
}
882394
func (r *Request) HTTPRequest() (*http.Request, error) {
	req, err := http.NewRequest(string(r.Method), r.URL.String(), nil)
	if err != nil {
		return nil, err
	}

	// merge headers
	req.Header = r.Headers

	// generate the body
	if r.prepare != nil {
		if err := r.prepare(req); err != nil {
			return nil, err
		}
	}

	return req, nil
}
167460
func (n *natsRequester) Request() error {
	if err := n.conn.Publish(n.subject, n.msg); err != nil {
		return err
	}
	_, err := n.sub.NextMsg(30 * time.Second)
	return err
}
1249683
func (q *Queue) AddRequest(r *colly.Request) error {
	d, err := r.Marshal()
	if err != nil {
		return err
	}
	if err := q.storage.AddRequest(d); err != nil {
		return err
	}
	q.lock.Lock()
	for _, c := range q.threadChans {
		c <- !stop
	}
	q.threadChans = make([]chan bool, 0, q.Threads)
	q.lock.Unlock()
	return nil
}
1324604
func (s *IndicesAnalyzeService) Request(request *IndicesAnalyzeRequest) *IndicesAnalyzeService {
	if request == nil {
		s.request = new(IndicesAnalyzeRequest)
	} else {
		s.request = request
	}
	return s
}
267539
func (c *Client) Get() *Request {
	return NewRequest(c.httpClient, c.base, "GET", c.version, c.authstring, c.userAgent)
}
965454
func (s *Adaptor) request(method string, url string, params url.Values) (m map[string]interface{}, err error) {
	var resp *http.Response

	if method == "POST" {
		resp, err = http.PostForm(url, params)
	} else if method == "GET" {
		resp, err = http.Get(url)
	}

	if err != nil {
		return
	}

	buf, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return
	}

	json.Unmarshal(buf, &m)

	if resp.Status != "200 OK" {
		err = fmt.Errorf("%v: error communicating to the Particle cloud", resp.Status)
	} else if _, ok := m["error"]; ok {
		err = errors.New(m["error"].(string))
	}

	return
}