// DoRegularRequest adds generic test functionality
193242
func DoRegularRequest(requestVerb, url string, ro *RequestOptions) (*Response, error) {
	return buildResponse(buildRequest(requestVerb, url, ro, nil))
}
1177922
func (rs *Ruleset) AddIrregular(singular, plural string) {
	delete(rs.uncountables, singular)
	delete(rs.uncountables, plural)
	rs.AddPlural(singular, plural)
	rs.AddPlural(plural, plural)
	rs.AddSingular(plural, singular)
}
381053
func HTTPRequest(err error) (*http.Request, bool) {
	type httpError interface {
		HTTPRequest() *http.Request
	}

	var req *http.Request

	emperror.ForEachCause(err, func(err error) bool {
		if httpErr, ok := err.(httpError); ok {
			req = httpErr.HTTPRequest()

			return false
		}

		return true
	})

	return req, req != nil
}
612088
func validateRequest(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	devFlag := r.URL.Query().Get("_dev")
	isDev := devFlag != ""
	if !isDev && !IsValidAlexaRequest(w, r) {
		log.Println("Request invalid")
		return
	}
	next(w, r)
}
565884
func (c *Client) Do(req *http.Request) (resp *http.Response, err error) {
	return c.pester(params{method: "Do", req: req, verb: req.Method, url: req.URL.String()})
}
253246
func (c *CircuitBreaker) ProcessRequest(r request.Request) (*http.Response, error) {
	if c.isStandby() {
		c.markToRecordMetrics(r)
		return nil, nil
	}

	// Circuit breaker is in tripped or recovering state
	c.m.Lock()
	defer c.m.Unlock()

	log.Infof("%v is in error handling state", c)

	switch c.state {
	case stateStandby:
		// other goroutine has set it to standby state
		return nil, nil
	case stateTripped:
		if c.tm.UtcNow().Before(c.until) {
			return c.fallback.ProcessRequest(r)
		}
		// We have been in active state enough, enter recovering state
		c.setRecovering()
		fallthrough
	case stateRecovering:
		// We have been in recovering state enough, enter standby
		if c.tm.UtcNow().After(c.until) {
			// instructs ProcessResponse() to record metrics for this request
			c.markToRecordMetrics(r)
			c.setState(stateStandby, c.tm.UtcNow())
			return nil, nil
		}
		if c.rc.allowRequest() {
			// instructs ProcessResponse() to record metrics for this request
			c.markToRecordMetrics(r)
			return nil, nil
		}
		return c.fallback.ProcessRequest(r)
	}

	return nil, nil
}
699578
func ValidateAndNormalizeRequest(c context.Context, oauthScope []string, durationSecs *int64, auditTags []string) error {
	minDur := time.Duration(*durationSecs) * time.Second
	// Test error cases
	switch {
	case len(oauthScope) <= 0:
		return fmt.Errorf("oauth_scope is required")
	case minDur < 0:
		return fmt.Errorf("min_validity_duration must be positive")
	case minDur > maxAllowedMinValidityDuration:
		return fmt.Errorf("min_validity_duration must not exceed %d", maxAllowedMinValidityDuration/time.Second)
	}
	if err := ValidateTags(auditTags); err != nil {
		return fmt.Errorf("bad audit_tags - %s", err)
	}

	// Perform normalization
	if minDur == 0 {
		*durationSecs = int64(DefaultMinValidityDuration.Seconds())
	}
	return nil
}
568325
func (s *Server) HandleAuthorizeRequest(w *Response, r *http.Request) *AuthorizeRequest {
	r.ParseForm()

	// create the authorization request
	unescapedUri, err := url.QueryUnescape(r.FormValue("redirect_uri"))
	if err != nil {
		w.SetErrorState(E_INVALID_REQUEST, "", "")
		w.InternalError = err
		return nil
	}

	ret := &AuthorizeRequest{
		State:       r.FormValue("state"),
		Scope:       r.FormValue("scope"),
		RedirectUri: unescapedUri,
		Authorized:  false,
		HttpRequest: r,
	}

	// must have a valid client
	ret.Client, err = w.Storage.GetClient(r.FormValue("client_id"))
	if err == ErrNotFound {
		w.SetErrorState(E_UNAUTHORIZED_CLIENT, "", ret.State)
		return nil
	}
	if err != nil {
		w.SetErrorState(E_SERVER_ERROR, "", ret.State)
		w.InternalError = err
		return nil
	}
	if ret.Client == nil {
		w.SetErrorState(E_UNAUTHORIZED_CLIENT, "", ret.State)
		return nil
	}
	if ret.Client.GetRedirectUri() == "" {
		w.SetErrorState(E_UNAUTHORIZED_CLIENT, "", ret.State)
		return nil
	}

	// check redirect uri, if there are multiple client redirect uri's
	// don't set the uri
	if ret.RedirectUri == "" && FirstUri(ret.Client.GetRedirectUri(), s.Config.RedirectUriSeparator) == ret.Client.GetRedirectUri() {
		ret.RedirectUri = FirstUri(ret.Client.GetRedirectUri(), s.Config.RedirectUriSeparator)
	}

	if realRedirectUri, err := ValidateUriList(ret.Client.GetRedirectUri(), ret.RedirectUri, s.Config.RedirectUriSeparator); err != nil {
		w.SetErrorState(E_INVALID_REQUEST, "", ret.State)
		w.InternalError = err
		return nil
	} else {
		ret.RedirectUri =  realRedirectUri
	}

	w.SetRedirect(ret.RedirectUri)

	requestType := AuthorizeRequestType(r.FormValue("response_type"))
	if s.Config.AllowedAuthorizeTypes.Exists(requestType) {
		switch requestType {
		case CODE:
			ret.Type = CODE
			ret.Expiration = s.Config.AuthorizationExpiration

			// Optional PKCE support (https://tools.ietf.org/html/rfc7636)
			if codeChallenge := r.FormValue("code_challenge"); len(codeChallenge) == 0 {
				if s.Config.RequirePKCEForPublicClients && CheckClientSecret(ret.Client, "") {
					// https://tools.ietf.org/html/rfc7636#section-4.4.1
					w.SetErrorState(E_INVALID_REQUEST, "code_challenge (rfc7636) required for public clients", ret.State)
					return nil
				}
			} else {
				codeChallengeMethod := r.FormValue("code_challenge_method")
				// allowed values are "plain" (default) and "S256", per https://tools.ietf.org/html/rfc7636#section-4.3
				if len(codeChallengeMethod) == 0 {
					codeChallengeMethod = PKCE_PLAIN
				}
				if codeChallengeMethod != PKCE_PLAIN && codeChallengeMethod != PKCE_S256 {
					// https://tools.ietf.org/html/rfc7636#section-4.4.1
					w.SetErrorState(E_INVALID_REQUEST, "code_challenge_method transform algorithm not supported (rfc7636)", ret.State)
					return nil
				}

				// https://tools.ietf.org/html/rfc7636#section-4.2
				if matched := pkceMatcher.MatchString(codeChallenge); !matched {
					w.SetErrorState(E_INVALID_REQUEST, "code_challenge invalid (rfc7636)", ret.State)
					return nil
				}

				ret.CodeChallenge = codeChallenge
				ret.CodeChallengeMethod = codeChallengeMethod
			}

		case TOKEN:
			ret.Type = TOKEN
			ret.Expiration = s.Config.AccessExpiration
		}
		return ret
	}

	w.SetErrorState(E_UNSUPPORTED_RESPONSE_TYPE, "", ret.State)
	return nil
}
165181
func (conn *Conn) runRequest(
	req boundRequest,
	arg reflect.Value,
	version int,
	recorder Recorder,
) {
	// If the request causes a panic, ensure we log that before closing the connection.
	defer func() {
		if panicResult := recover(); panicResult != nil {
			logger.Criticalf(
				"panic running request %+v with arg %+v: %v\n%v", req, arg, panicResult, string(debug.Stack()))
			conn.writeErrorResponse(&req.hdr, errors.Errorf("%v", panicResult), recorder)
		}
	}()
	defer conn.srvPending.Done()

	// Create a request-specific context, cancelled when the
	// request returns.
	//
	// TODO(axw) provide a means for clients to cancel a request.
	ctx, cancel := context.WithCancel(conn.context)
	defer cancel()

	rv, err := req.Call(ctx, req.hdr.Request.Id, arg)
	if err != nil {
		err = conn.writeErrorResponse(&req.hdr, req.transformErrors(err), recorder)
	} else {
		hdr := &Header{
			RequestId: req.hdr.RequestId,
			Version:   version,
		}
		var rvi interface{}
		if rv.IsValid() {
			rvi = rv.Interface()
		} else {
			rvi = struct{}{}
		}
		if err := recorder.HandleReply(req.hdr.Request, hdr, rvi); err != nil {
			logger.Errorf("error recording reply %+v: %T %+v", hdr, err, err)
		}
		conn.sending.Lock()
		err = conn.codec.WriteMessage(hdr, rvi)
		conn.sending.Unlock()
	}
	if err != nil {
		// If the message failed due to the other end closing the socket, that
		// is expected when an agent restarts so no need to log an  error.
		// The error type here is errors.errorString so all we can do is a match
		// on the error string content.
		msg := err.Error()
		if !strings.Contains(msg, "websocket: close sent") &&
			!strings.Contains(msg, "write: broken pipe") {
			logger.Errorf("error writing response: %T %+v", err, err)
		}
	}
}
844128
func GetRequest(ctx context.Context) (*http.Request, error) {
	if r, ok := ctx.Value("http.request").(*http.Request); r != nil && ok {
		return r, nil
	}
	return nil, ErrNoRequestContext
}
75062
func (s *BackendImplementation) Do(req *http.Request, body *bytes.Buffer, v interface{}) error {
	s.LeveledLogger.Infof("Requesting %v %v%v\n", req.Method, req.URL.Host, req.URL.Path)

	if s.enableTelemetry {
		select {
		case metrics := <-s.requestMetricsBuffer:
			metricsJSON, err := json.Marshal(&requestTelemetry{LastRequestMetrics: metrics})
			if err == nil {
				req.Header.Set("X-Stripe-Client-Telemetry", string(metricsJSON))
			} else {
				s.LeveledLogger.Warnf("Unable to encode client telemetry: %v", err)
			}
		default:
			// There are no metrics available, so don't send any.
			// This default case  needs to be here to prevent Do from blocking on an
			// empty requestMetricsBuffer.
		}
	}

	var res *http.Response
	var err error
	var requestDuration time.Duration
	for retry := 0; ; {
		start := time.Now()

		// This might look a little strange, but we set the request's body
		// outside of `NewRequest` so that we can get a fresh version every
		// time.
		//
		// The background is that back in the era of old style HTTP, it was
		// safe to reuse `Request` objects, but with the addition of HTTP/2,
		// it's now only sometimes safe. Reusing a `Request` with a body will
		// break.
		//
		// See some details here:
		//
		//     https://github.com/golang/go/issues/19653#issuecomment-341539160
		//
		// And our original bug report here:
		//
		//     https://github.com/stripe/stripe-go/issues/642
		//
		// To workaround the problem, we put a fresh `Body` onto the `Request`
		// every time we execute it, and this seems to empirically resolve the
		// problem.
		if body != nil {
			// We can safely reuse the same buffer that we used to encode our body,
			// but return a new reader to it everytime so that each read is from
			// the beginning.
			reader := bytes.NewReader(body.Bytes())

			req.Body = nopReadCloser{reader}

			// And also add the same thing to `Request.GetBody`, which allows
			// `net/http` to get a new body in cases like a redirect. This is
			// usually not used, but it doesn't hurt to set it in case it's
			// needed. See:
			//
			//     https://github.com/stripe/stripe-go/issues/710
			//
			req.GetBody = func() (io.ReadCloser, error) {
				reader := bytes.NewReader(body.Bytes())
				return nopReadCloser{reader}, nil
			}
		}

		res, err = s.HTTPClient.Do(req)

		requestDuration = time.Since(start)

		s.LeveledLogger.Infof("Request completed in %v (retry: %v)", requestDuration, retry)

		// If the response was okay, we're done, and it's safe to break out of
		// the retry loop.
		if !s.shouldRetry(err, res, retry) {
			break
		}

		if err != nil {
			s.LeveledLogger.Errorf("Request failed with error: %v", err)
		} else {
			resBody, err := ioutil.ReadAll(res.Body)
			res.Body.Close()
			if err != nil {
				s.LeveledLogger.Errorf("Cannot read response: %v", err)
			} else {
				s.LeveledLogger.Errorf("Request failed with body: %s (status: %v)",
					string(resBody), res.StatusCode)
			}
		}

		sleepDuration := s.sleepTime(retry)
		retry++

		s.LeveledLogger.Warnf("Initiating retry %v for request %v %v%v after sleeping %v",
			retry, req.Method, req.URL.Host, req.URL.Path, sleepDuration)

		time.Sleep(sleepDuration)
	}

	if err != nil {
		s.LeveledLogger.Errorf("Request failed: %v", err)
		return err
	}

	if s.enableTelemetry {
		reqID := res.Header.Get("Request-Id")
		if len(reqID) > 0 {
			metrics := requestMetrics{
				RequestDurationMS: int(requestDuration / time.Millisecond),
				RequestID:         reqID,
			}

			// If the metrics buffer is full, discard the new metrics. Otherwise, add
			// them to the buffer.
			select {
			case s.requestMetricsBuffer <- metrics:
			default:
			}
		}
	}

	defer res.Body.Close()

	resBody, err := ioutil.ReadAll(res.Body)
	if err != nil {
		s.LeveledLogger.Errorf("Cannot read response: %v", err)
		return err
	}

	if res.StatusCode >= 400 {
		return s.ResponseToError(res, resBody)
	}

	s.LeveledLogger.Debugf("Response: %s\n", string(resBody))

	if v != nil {
		return s.UnmarshalJSONVerbose(res.StatusCode, resBody, v)
	}

	return nil
}
561202
func Req(verb string, url string, ro *RequestOptions) (*Response, error) {
	return DoRegularRequest(verb, url, ro)
}
775322
func (v *ServiceGenerator_Generate_Args) GetRequest() (o *GenerateServiceRequest) {
	if v != nil && v.Request != nil {
		return v.Request
	}

	return
}
300534
func (c *Client) DoRequestWithoutRedirects(r *Request) (*http.Response, error) {
	prevCheckRedirect := c.Config.HttpClient.CheckRedirect
	c.Config.HttpClient.CheckRedirect = func(httpReq *http.Request, via []*http.Request) error {
		return http.ErrUseLastResponse
	}
	defer func() {
		c.Config.HttpClient.CheckRedirect = prevCheckRedirect
	}()
	return c.DoRequest(r)
}
815628
func (c *Client) DoRequest(r *request) (*http.Response, error) {
	req, err := r.toHTTP()
	if err != nil {
		return nil, err
	}
	for key, value := range r.header {
		req.Header.Add(key, value)
	}
	req.SetBasicAuth(c.config.Username, c.config.Password)
	req.Header.Add("User-Agent", "gogo-bosh")
	resp, err := c.config.HttpClient.Do(req)
	if err != nil {
		if strings.Contains(err.Error(), "oauth2: cannot fetch token") {
			c.refreshClient()
			resp, err = c.config.HttpClient.Do(req)
		}
	}
	return resp, err
}
596263
func (req Request) Do(url string) (Response, error) {
	var nilResp Response

	reqDER, err := asn1.Marshal(req)
	if err != nil {
		return nilResp, err
	}

	httpReq, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(reqDER))
	if err != nil {
		return nilResp, err
	}
	httpReq.Header.Add("Content-Type", contentTypeTSQuery)

	httpResp, err := DefaultHTTPClient.Do(httpReq)
	if err != nil {
		return nilResp, err
	}
	if ct := httpResp.Header.Get("Content-Type"); ct != contentTypeTSReply {
		return nilResp, fmt.Errorf("Bad content-type: %s", ct)
	}

	buf := bytes.NewBuffer(make([]byte, 0, httpResp.ContentLength))
	if _, err = io.Copy(buf, httpResp.Body); err != nil {
		return nilResp, err
	}

	return ParseResponse(buf.Bytes())
}
697675
func performRequest(ctx log.Interface, server string, strategy auth.Strategy, method, URI string, headers map[string]string, rbody, res interface{}, redirects int) error {
	body, err := performRequestBody(ctx, server, strategy, method, URI, headers, rbody, redirects)
	if err != nil {
		return err
	}

	defer func() {
		io.Copy(ioutil.Discard, body)
		body.Close()
	}()

	if res != nil {
		decoder := json.NewDecoder(body)
		if err := decoder.Decode(res); err != nil {
			return err
		}
	}

	return nil
}