// PrepareRequest alters the given HTTP request by setting its Authorization
// header to the string "Bearer " followed by the encapsulated authentication
// token.
196709
func (tc HostCredentialsToken) PrepareRequest(req *http.Request) {
	if req.Header == nil {
		req.Header = http.Header{}
	}
	req.Header.Set("Authorization", "Bearer "+string(tc))
}
1204413
func (bow *Browser) httpRequest(req *http.Request) error {
	if bow.client == nil {
		bow.client = bow.buildClient()
	}
	bow.preSend()
	resp, err := bow.client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	var reader io.Reader
	switch resp.Header.Get("Content-Encoding") {
	case "gzip":
		reader, err = gzip.NewReader(resp.Body)
		if err != nil {
			return err
		}
	case "deflate":
		reader = flate.NewReader(resp.Body)

	default:
		reader = resp.Body
	}

	bow.body, err = ioutil.ReadAll(reader)
	if err != nil {
		return err
	}

	buff := bytes.NewBuffer(bow.body)
	dom, err := goquery.NewDocumentFromReader(buff)
	if err != nil {
		return err
	}

	bow.history.Push(bow.state)
	bow.state = jar.NewHistoryState(req, resp, dom)
	bow.postSend()

	return nil
}
1360764
func (a *basicAuthentication) Prepare(ctx context.Context, conn driver.Connection) error {
	// No need to do anything here
	return nil
}
673767
func (c Client) Request(method string, path string, body []byte) (*http.Response, error) {
	url := c.ControllerURL

	if strings.Contains(path, "?") {
		parts := strings.Split(path, "?")
		url.Path = parts[0]
		url.RawQuery = parts[1]
	} else {
		url.Path = path
	}

	req, err := http.NewRequest(method, url.String(), bytes.NewBuffer(body))

	if err != nil {
		return nil, err
	}

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

	if c.Token != "" {
		req.Header.Add("Authorization", "token "+c.Token)
	}

	addUserAgent(&req.Header)

	res, err := c.HTTPClient.Do(req)

	if err != nil {
		return nil, err
	}

	if err = checkForErrors(res, ""); err != nil {
		return nil, err
	}

	checkAPICompatibility(res.Header.Get("DEIS_API_VERSION"))

	return res, nil
}
1017825
func (ua *UserAgentAuthentication) Request(ctx context.Context, req *http.Request) (*http.Response, error) {
	// nothing to do gtfo
	if ua.UserAgentPassword == "" {
		return ua.Requester(ctx, req)
	}
	//
	retsVersion := ""
	if ua.GetRETSVersion != nil {
		retsVersion = ua.GetRETSVersion(req)
	}
	// we generate this and set it in the headers
	requestID := ""
	if ua.CreateRequestID != nil {
		requestID = ua.CreateRequestID(req)
		req.Header.Set(RETSRequestID, requestID)
	}
	// need to extract this from context that we may not have at this level
	sessionID := ""
	if ua.GetSessionID != nil {
		sessionID = ua.GetSessionID(req)
	}
	uaAuthHeader := ua.header(requestID, sessionID, retsVersion)
	// this will replace an existing value
	req.Header.Set(RETSUAAuth, uaAuthHeader)
	return ua.Requester(ctx, req)
}
1083213
func NewRequest(q string) *Request {
	req := &Request{
		q:      q,
		Header: make(map[string][]string),
	}
	return req
}
1369613
func (api *API) request(ctx context.Context, method, uri string, reqBody io.Reader, authType int, headers http.Header) (*http.Response, error) {
	req, err := http.NewRequest(method, api.BaseURL+uri, reqBody)
	if err != nil {
		return nil, errors.Wrap(err, "HTTP request creation failed")
	}
	req.WithContext(ctx)

	combinedHeaders := make(http.Header)
	copyHeader(combinedHeaders, api.headers)
	copyHeader(combinedHeaders, headers)
	req.Header = combinedHeaders
	if authType&AuthKeyEmail != 0 {
		req.Header.Set("X-Auth-Key", api.APIKey)
		req.Header.Set("X-Auth-Email", api.APIEmail)
	}
	if authType&AuthUserService != 0 {
		req.Header.Set("X-Auth-User-Service-Key", api.APIUserServiceKey)
	}
	if api.UserAgent != "" {
		req.Header.Set("User-Agent", api.UserAgent)
	}

	if req.Header.Get("Content-Type") == "" {
		req.Header.Set("Content-Type", "application/json")
	}

	resp, err := api.httpClient.Do(req)
	if err != nil {
		return nil, errors.Wrap(err, "HTTP request failed")
	}

	return resp, nil
}
738135
func (ks3 *KS3) prepare(req *request) error {
	// Copy so they can be mutated without affecting on retries.
	params := make(url.Values)
	headers := make(http.Header)
	for k, v := range req.params {
		params[k] = v
	}
	for k, v := range req.headers {
		headers[k] = v
	}
	req.params = params
	req.headers = headers

	if !req.prepared {
		req.prepared = true
		if req.method == "" {
			req.method = "GET"
		}

		if !strings.HasPrefix(req.path, "/") {
			req.path = "/" + req.path
		}

		err := ks3.setBaseURL(req)
		if err != nil {
			return err
		}
	}

	if ks3.Auth.Token() != "" {
		req.headers["X-Kss-Security-Token"] = []string{ks3.Auth.Token()}
	}

	// Always sign again as it's not clear how far the
	// server has handled a previous attempt.
	u, err := url.Parse(req.baseurl)
	if err != nil {
		return err
	}

	signpathPartiallyEscaped := partiallyEscapedPath(req.path)
	if len(req.bucket) > 0 {
		signpathPartiallyEscaped = "/" + req.bucket + signpathPartiallyEscaped
	}
	req.headers["Host"] = []string{u.Host}
	req.headers["Date"] = []string{time.Now().In(time.UTC).Format(time.RFC1123)}

	sign(ks3.Auth, req.method, signpathPartiallyEscaped, req.params, req.headers)
	return nil
}
1266409
func (c *Client) RawRequest(verb, p string, ro *RequestOptions) (*http.Request, error) {
	// Ensure we have request options.
	if ro == nil {
		ro = new(RequestOptions)
	}

	// Append the path to the URL.
	u := *c.url
	u.Path = strings.TrimRight(c.url.Path, "/") + "/" + strings.TrimLeft(p, "/")

	// Add the token and other params.
	var params = make(url.Values)
	for k, v := range ro.Params {
		params.Add(k, v)
	}
	u.RawQuery = params.Encode()

	// Create the request object.
	request, err := http.NewRequest(verb, u.String(), ro.Body)
	if err != nil {
		return nil, err
	}

	// Set the API key.
	if len(c.apiKey) > 0 {
		request.Header.Set(APIKeyHeader, c.apiKey)
	}

	// Set the User-Agent.
	request.Header.Set("User-Agent", UserAgent)

	// Add any custom headers.
	for k, v := range ro.Headers {
		request.Header.Add(k, v)
	}

	// Add Content-Length if we have it.
	if ro.BodyLength > 0 {
		request.ContentLength = ro.BodyLength
	}

	return request, nil
}
804321
func (g *Generator) ProcessRequest(req *CertificateRequest) (csr, key []byte, err error) {

	log.Info("generate received request")
	err = g.Validator(req)
	if err != nil {
		log.Warningf("invalid request: %v", err)
		return nil, nil, err
	}

	csr, key, err = ParseRequest(req)
	if err != nil {
		return nil, nil, err
	}
	return
}
834292
func (c *Context) NewRequest(
	hostType string,
	style string,
	authed bool,
	namespace string,
	route string,
	headers map[string]string,
	body io.Reader,
) (*http.Request, error) {
	url := c.URLGenerator(hostType, style, namespace, route)
	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		return nil, err
	}
	for k, v := range headers {
		req.Header.Add(k, v)
	}
	for k, v := range c.HeaderGenerator(hostType, style, namespace, route) {
		req.Header.Add(k, v)
	}
	if req.Header.Get("Host") != "" {
		req.Host = req.Header.Get("Host")
	}
	if !authed {
		req.Header.Del("Authorization")
	}
	return req, nil
}
115811
func (a *vstAuthenticationImpl) PrepareFunc(vstConn *vstConnection) func(ctx context.Context, conn *protocol.Connection) error {
	return func(ctx context.Context, conn *protocol.Connection) error {
		var authReq velocypack.Slice
		var err error

		if a.encryption == "jwt" {
			// Call _open/auth
			// Prepare request
			r, err := vstConn.NewRequest("POST", "/_open/auth")
			if err != nil {
				return driver.WithStack(err)
			}
			r.SetBody(jwtOpenRequest{
				UserName: a.userName,
				Password: a.password,
			})

			// Perform request
			resp, err := vstConn.do(ctx, r, conn)
			if err != nil {
				return driver.WithStack(err)
			}
			if err := resp.CheckStatus(200); err != nil {
				return driver.WithStack(err)
			}

			// Parse response
			var data jwtOpenResponse
			if err := resp.ParseBody("", &data); err != nil {
				return driver.WithStack(err)
			}

			// Create request
			var b velocypack.Builder
			b.OpenArray()
			b.AddValue(velocypack.NewIntValue(1))             // Version
			b.AddValue(velocypack.NewIntValue(1000))          // Type (1000=Auth)
			b.AddValue(velocypack.NewStringValue("jwt"))      // Encryption type
			b.AddValue(velocypack.NewStringValue(data.Token)) // Token
			b.Close()                                         // request
			authReq, err = b.Slice()
			if err != nil {
				return driver.WithStack(err)
			}
		} else {
			// Create request
			var b velocypack.Builder
			b.OpenArray()
			b.AddValue(velocypack.NewIntValue(1))               // Version
			b.AddValue(velocypack.NewIntValue(1000))            // Type (1000=Auth)
			b.AddValue(velocypack.NewStringValue(a.encryption)) // Encryption type
			b.AddValue(velocypack.NewStringValue(a.userName))   // Username
			b.AddValue(velocypack.NewStringValue(a.password))   // Password
			b.Close()                                           // request
			authReq, err = b.Slice()
			if err != nil {
				return driver.WithStack(err)
			}
		}

		// Send request
		respChan, err := conn.Send(ctx, authReq)
		if err != nil {
			return driver.WithStack(err)
		}

		// Wait for response
		m := <-respChan
		resp, err := newResponse(m.Data, "", nil)
		if err != nil {
			return driver.WithStack(err)
		}
		if err := resp.CheckStatus(200); err != nil {
			return driver.WithStack(err)
		}

		// Ok
		return nil
	}
}
1309848
func ParseRequest(req *http.Request) Group {
	if req == nil {
		return nil
	}

	return ParseHeader(req.Header)
}
187693
func (config *Config) prepare() {
	config.origins = strings.Split(config.Origins, ", ")
	config.methods = strings.Split(config.Methods, ", ")
	config.requestHeaders = strings.Split(config.RequestHeaders, ", ")
	config.maxAge = fmt.Sprintf("%.f", config.MaxAge.Seconds())

	// Generates a boolean of value "true".
	config.credentials = fmt.Sprintf("%t", config.Credentials)

	// Convert to lower-case once as request headers are supposed to be a case-insensitive match
	for idx, header := range config.requestHeaders {
		config.requestHeaders[idx] = strings.ToLower(header)
	}
}
247730
func prepRequestBody(body interface{}) (io.Reader, error) {

	switch val := body.(type) {
	case string:
		return strings.NewReader(val), nil
	case nil:
		return nil, nil
	default:
		b, err := json.Marshal(body)
		if err != nil {
			return nil, err
		}

		return bytes.NewReader(b), nil
	}

	return nil, nil
}
988443
func Bearer(token string) macaron.Handler {
	return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
		auth := req.Header.Get("Authorization")
		if !SecureCompare(auth, bearerPrefix+token) {
			bearerUnauthorized(res)
			return
		}
		c.Map(User(""))
	}
}
368680
func makeHttpRequest(pcc *PubControlClient, uri, authHeader string,
	jsonContent []byte) (int, []byte, error) {
	var req *http.Request
	req, err := http.NewRequest("POST", uri, bytes.NewReader(jsonContent))
	if err != nil {
		return 0, nil, err
	}
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Authorization", authHeader)
	resp, err := pcc.httpClient.Do(req)
	if err != nil {
		return 0, nil, err
	}
	defer resp.Body.Close()
	var body []byte
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0, nil, err
	}
	return resp.StatusCode, body, nil
}