// UseRequest registers a new request phase middleware handler.
499373
func (s *Layer) UseRequest(fn c.HandlerFunc) Middleware {
	s.mtx.Lock()
	s.stack = append(s.stack, plugin.NewRequestPlugin(fn))
	s.mtx.Unlock()
	return s
}
587360
func (s *HTTPServer) parseWriteRequest(req *http.Request, w *structs.WriteRequest) {
	parseNamespace(req, &w.Namespace)
	s.parseToken(req, &w.AuthToken)
	s.parseRegion(req, &w.Region)
}
896069
func (s *Server) handleRequest(str quic.Stream, decoder *qpack.Decoder) error {
	frame, err := parseNextFrame(str)
	if err != nil {
		str.CancelWrite(quic.ErrorCode(errorRequestCanceled))
		return err
	}
	hf, ok := frame.(*headersFrame)
	if !ok {
		str.CancelWrite(quic.ErrorCode(errorUnexpectedFrame))
		return errors.New("expected first frame to be a headers frame")
	}
	// TODO: check length
	headerBlock := make([]byte, hf.Length)
	if _, err := io.ReadFull(str, headerBlock); err != nil {
		str.CancelWrite(quic.ErrorCode(errorIncompleteRequest))
		return err
	}
	hfs, err := decoder.DecodeFull(headerBlock)
	if err != nil {
		// TODO: use the right error code
		str.CancelWrite(quic.ErrorCode(errorGeneralProtocolError))
		return err
	}
	req, err := requestFromHeaders(hfs)
	if err != nil {
		return err
	}
	req.Body = newRequestBody(str)

	if s.logger.Debug() {
		s.logger.Infof("%s %s%s, on stream %d", req.Method, req.Host, req.RequestURI, str.StreamID())
	} else {
		s.logger.Infof("%s %s%s", req.Method, req.Host, req.RequestURI)
	}

	req = req.WithContext(str.Context())
	responseWriter := newResponseWriter(str, s.logger)
	handler := s.Handler
	if handler == nil {
		handler = http.DefaultServeMux
	}

	var panicked, readEOF bool
	func() {
		defer func() {
			if p := recover(); p != nil {
				// Copied from net/http/server.go
				const size = 64 << 10
				buf := make([]byte, size)
				buf = buf[:runtime.Stack(buf, false)]
				s.logger.Errorf("http: panic serving: %v\n%s", p, buf)
				panicked = true
			}
		}()
		handler.ServeHTTP(responseWriter, req)
		// read the eof
		if _, err = str.Read([]byte{}); err == io.EOF {
			readEOF = true
		}
	}()

	if panicked {
		responseWriter.WriteHeader(500)
	} else {
		responseWriter.WriteHeader(200)
	}

	if !readEOF {
		str.CancelRead(quic.ErrorCode(errorEarlyResponse))
	}
	return nil
}
1312692
func (rs *RequestServer) nextRequest(r *Request) string {
	rs.openRequestLock.Lock()
	defer rs.openRequestLock.Unlock()
	rs.handleCount++
	handle := strconv.Itoa(rs.handleCount)
	r.handle = handle
	rs.openRequests[handle] = r
	return handle
}
1012494
func (ur UploadRequest) HTTPRequest() (*http.Request, error) {
	// TODO(ericsnow) What about the rest of the URL?
	urlStr := NewEndpointPath(ur.Application, ur.Name)

	req, err := http.NewRequest(http.MethodPut, urlStr, nil)
	if err != nil {
		return nil, errors.Trace(err)
	}

	req.Header.Set(HeaderContentType, ContentTypeRaw)
	req.Header.Set(HeaderContentSha384, ur.Fingerprint.String())
	req.Header.Set(HeaderContentLength, fmt.Sprint(ur.Size))
	setFilename(ur.Filename, req)

	req.ContentLength = ur.Size

	if ur.PendingID != "" {
		query := req.URL.Query()
		query.Set(QueryParamPendingID, ur.PendingID)
		req.URL.RawQuery = query.Encode()
	}

	return req, nil
}
1066121
func (s *Segment) RecordRequest(req *http.Request, namespace string) {
	s.Lock()
	defer s.Unlock()

	if s.HTTP == nil {
		s.HTTP = &HTTP{}
	}

	s.Namespace = namespace
	s.HTTP.Request = requestData(req)
}
1290999
func (auth *v2Auth) Request(c *Connection) (*http.Request, error) {
	auth.Region = c.Region
	// Toggle useApiKey if not first run and not OK yet
	if auth.notFirst && !auth.useApiKeyOk {
		auth.useApiKey = !auth.useApiKey
	}
	auth.notFirst = true
	// Create a V2 auth request for the body of the connection
	var v2i interface{}
	if !auth.useApiKey {
		// Normal swift authentication
		v2 := v2AuthRequest{}
		v2.Auth.PasswordCredentials.UserName = c.UserName
		v2.Auth.PasswordCredentials.Password = c.ApiKey
		v2.Auth.Tenant = c.Tenant
		v2.Auth.TenantId = c.TenantId
		v2i = v2
	} else {
		// Rackspace special with API Key
		v2 := v2AuthRequestRackspace{}
		v2.Auth.ApiKeyCredentials.UserName = c.UserName
		v2.Auth.ApiKeyCredentials.ApiKey = c.ApiKey
		v2.Auth.Tenant = c.Tenant
		v2.Auth.TenantId = c.TenantId
		v2i = v2
	}
	body, err := json.Marshal(v2i)
	if err != nil {
		return nil, err
	}
	url := c.AuthUrl
	if !strings.HasSuffix(url, "/") {
		url += "/"
	}
	url += "tokens"
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("User-Agent", c.UserAgent)
	return req, nil
}
1281355
func (q *InMemoryQueueStorage) AddRequest(r []byte) error {
	q.lock.Lock()
	defer q.lock.Unlock()
	// Discard URLs if size limit exceeded
	if q.MaxSize > 0 && q.size >= q.MaxSize {
		return nil
	}
	i := &inMemoryQueueItem{Request: r}
	if q.first == nil {
		q.first = i
	} else {
		q.last.Next = i
	}
	q.last = i
	q.size++
	return nil
}
764842
func userAgent(req *http.Request) {
	ua := fmt.Sprintf("%s/%s;%s",
		UserAgentBase,
		UserAgentVersion,
		runtime.Version(),
	)
	req.Header.Add("User-Agent", ua)
}
647409
func (c *UnidlingController) awaitRequest() bool {
	infoRaw, stop := c.queue.Get()
	if stop {
		return false
	}

	defer c.queue.Done(infoRaw)

	info := infoRaw.(types.NamespacedName)
	lastFired := c.lastFiredCache.Get(info)

	var retry bool
	var err error
	if retry, err = c.handleRequest(info, lastFired); err == nil {
		// if there was no error, we succeeded in the unidling, and we need to
		// tell the rate limitter to stop tracking this request
		c.queue.Forget(infoRaw)
		return true
	}

	// check to see if we think the error was transient (e.g. server error on the update request),
	// and if not, do not retry
	if !retry {
		utilruntime.HandleError(fmt.Errorf("Unable to process unidling event for %s/%s at (%s), will not retry: %v", info.Namespace, info.Name, lastFired, err))
		return true
	}

	// Otherwise, if we have an error, we were at least partially unsuccessful in unidling, so
	// we requeue the event to process later

	// don't try to process failing requests forever
	if c.queue.NumRequeues(infoRaw) > MaxRetries {
		utilruntime.HandleError(fmt.Errorf("Unable to process unidling event for %s/%s (at %s), will not retry again: %v", info.Namespace, info.Name, lastFired, err))
		c.queue.Forget(infoRaw)
		return true
	}

	klog.V(4).Infof("Unable to fully process unidling request for %s/%s (at %s), will retry: %v", info.Namespace, info.Name, lastFired, err)
	c.queue.AddRateLimited(infoRaw)
	return true
}
140735
func (m *Melody) HandleRequest(w http.ResponseWriter, r *http.Request) error {
	return m.HandleRequestWithKeys(w, r, nil)
}
524084
func (s *Server) handleRequest(req *Request, conn conn) error {
	ctx := context.Background()

	// Resolve the address if we have a FQDN
	dest := req.DestAddr
	if dest.FQDN != "" {
		ctx_, addr, err := s.config.Resolver.Resolve(ctx, dest.FQDN)
		if err != nil {
			if err := sendReply(conn, hostUnreachable, nil); err != nil {
				return fmt.Errorf("Failed to send reply: %v", err)
			}
			return fmt.Errorf("Failed to resolve destination '%v': %v", dest.FQDN, err)
		}
		ctx = ctx_
		dest.IP = addr
	}

	// Apply any address rewrites
	req.realDestAddr = req.DestAddr
	if s.config.Rewriter != nil {
		ctx, req.realDestAddr = s.config.Rewriter.Rewrite(ctx, req)
	}

	// Switch on the command
	switch req.Command {
	case ConnectCommand:
		return s.handleConnect(ctx, conn, req)
	case BindCommand:
		return s.handleBind(ctx, conn, req)
	case AssociateCommand:
		return s.handleAssociate(ctx, conn, req)
	default:
		if err := sendReply(conn, commandNotSupported, nil); err != nil {
			return fmt.Errorf("Failed to send reply: %v", err)
		}
		return fmt.Errorf("Unsupported command: %v", req.Command)
	}
}
360186
func (s seriesSelector) userRequested(requestedSeries string) (string, error) {
	series, err := charm.SeriesForCharm(requestedSeries, s.supportedSeries)
	if s.force {
		series = requestedSeries
	} else if err != nil {
		return "", err
	}

	// either it's a supported series or the user used --force, so just
	// give them what they asked for.
	if s.fromBundle {
		logger.Infof(msgBundleSeries, series)
		return series, nil
	}
	logger.Infof(msgUserRequestedSeries, series)
	return series, nil
}
27773
func (h *Handler) u2fRegisterRequest(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
	token := p[0].Value
	u2fRegisterRequest, err := h.auth.GetUserInviteU2FRegisterRequest(token)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return u2fRegisterRequest, nil
}
955576
func (auth *v1Auth) Request(c *Connection) (*http.Request, error) {
	req, err := http.NewRequest("GET", c.AuthUrl, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("User-Agent", c.UserAgent)
	req.Header.Set("X-Auth-Key", c.ApiKey)
	req.Header.Set("X-Auth-User", c.UserName)
	return req, nil
}
1147032
func (c *Client) NewRequest(method, path string, request interface{}) (*http.Request, error) {
	var u *url.URL
	var err error

	if c.BaseURL != "" {
		u, err = url.Parse(c.BaseURL)
		if err != nil {
			return nil, err
		}
	}

	qv, err := query.Values(request)
	if err != nil {
		return nil, err
	}
	qs := encode(qv)
	if qs != "" && method == http.MethodGet || method == http.MethodDelete {
		if strings.Contains(path, "?") {
			path += "&" + qs
		} else {
			path += "?" + qs
		}
	}
	if path != "" {
		rel, err := url.Parse(path)
		if err != nil {
			return nil, err
		}
		if u != nil {
			u = u.ResolveReference(rel)
		} else {
			u = rel
		}
	}
	if u == nil {
		return nil, errors.New("No URL is provided.")
	}

	req, err := http.NewRequest(method, u.String(), bytes.NewBufferString(qs))
	if err != nil {
		return nil, err
	}

	req.Header.Add("Accept", "application/json")
	req.Header.Add("User-Agent", c.UserAgent)
	for k, v := range c.headers {
		req.Header.Add(k, v)
	}
	if method == http.MethodPost || method == http.MethodPut {
		req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
		req.Header.Add("Content-Length", strconv.Itoa(len(qs)))
	}
	if c.Debug {
		dump, err := httputil.DumpRequestOut(req, true)
		if err == nil {
			fmt.Println(string(dump))
		}
	}
	return req, nil
}
1309848
func ParseRequest(req *http.Request) Group {
	if req == nil {
		return nil
	}

	return ParseHeader(req.Header)
}