// NewRequest 创建新的请求实例
//
// client 如果为空，则会采用 http.DefaultClient 作为其值。
507933
func NewRequest(a *assert.Assertion, client *http.Client, method, path string) *Request {
	if client == nil {
		client = http.DefaultClient
	}

	return &Request{
		assertion: a,
		client:    client,
		method:    method,
		path:      path,
	}
}
193216
func NewRequest(method string, urlStr string, body io.Reader) (*http.Request, error) {
	request, err := http.NewRequest(method, urlStr, body)
	if err != nil {
		return nil, err
	}

	request.Header.Set("Content-Type", jsh.ContentType)
	request.Header.Set("Content-Length", strconv.Itoa(int(request.ContentLength)))

	return request, err
}
374298
func NewHTTPRequest(r *http.Request) *HTTPRequest {
	if r == nil {
		return &HTTPRequest{}
	}

	r.ParseForm()

	return &HTTPRequest{
		HostName:    r.Host,
		URL:         r.URL.String(),
		HTTPMethod:  r.Method,
		IPAddress:   r.RemoteAddr,
		QueryString: arrayMapToStringMap(r.URL.Query()),
		Form:        arrayMapToStringMap(r.PostForm),
		Headers:     arrayMapToStringMap(r.Header),
	}
}
132813
func (srv *Server) NewRequest(method, path string) *Request {
	req := NewRequest(srv.assertion, srv.client, method, path)
	req.prefix = srv.server.URL

	return req
}
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
}
235311
func newRequest(server, method string, URI string, body io.Reader) (*http.Request, error) {
	URL := fmt.Sprintf("%s%s", server, URI)
	req, err := http.NewRequest(method, URL, body)
	if err != nil {
		return nil, err
	}

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

	return req, nil
}
725404
func (c *Client) newRequest(method, path string) *request {
	r := &request{
		config: &c.config,
		method: method,
		url: &url.URL{
			Scheme: c.config.Scheme,
			Host:   c.config.Address,
			Path:   path,
		},
		params: make(map[string][]string),
	}
	if c.config.Datacenter != "" {
		r.params.Set("dc", c.config.Datacenter)
	}
	if c.config.WaitTime != 0 {
		r.params.Set("wait", durToMsec(r.config.WaitTime))
	}
	if c.config.Token != "" {
		r.params.Set("token", r.config.Token)
	}
	return r
}
644376
func (c *Client) NewRequest(method, urlStr string, body interface{}, apiVersion string) (req *APIRequest, err error) {
	var rel *url.URL
	var buf io.ReadWriter
	req = &APIRequest{}

	// I'm not sure how to get this method to return an error intentionally for testing. For testing purposes, I've
	// added a switch so that the error handling in dependent methods can be tested.
	if os.Getenv("GOCD_RAISE_ERROR_NEW_REQUEST") == "yes" {
		return req, errors.New("Mock Testing Error")
	}

	// Some calls
	if strings.HasPrefix(urlStr, "/") {
		urlStr = urlStr[1:]
	} else {
		urlStr = "api/" + urlStr
	}
	if rel, err = url.Parse(urlStr); err != nil {
		return req, err
	}

	u := c.params.BuildPath(rel)

	if body != nil {
		buf = new(bytes.Buffer)

		enc := json.NewEncoder(buf)
		enc.SetIndent("", "  ")
		err := enc.Encode(body)

		if err != nil {
			return nil, err
		}
		bdy, _ := ioutil.ReadAll(buf)
		req.Body = string(bdy)

		buf = new(bytes.Buffer)
		enc = json.NewEncoder(buf)
		enc.SetIndent("", "  ")
		enc.Encode(body)
	}

	if req.HTTP, err = http.NewRequest(method, u.String(), buf); err != nil {
		return req, err
	}

	if body != nil {
		req.HTTP.Header.Set("Content-Type", "application/json")
	}
	if apiVersion != "" {
		req.HTTP.Header.Set("Accept", apiVersion)
	}
	req.HTTP.Header.Set("User-Agent", c.params.UserAgent)

	if c.cookie == "" {
		if c.params.Username != "" && c.params.Password != "" {
			req.HTTP.SetBasicAuth(c.params.Username, c.params.Password)
		}
	} else {
		req.HTTP.Header.Set("Cookie", c.cookie)
	}

	return
}
79993
func (c *Client) NewRequest(urlStr string) (req *Request, err error) {
	req, err = newRequest(c, urlStr)
	if err != nil {
		return
	}

	c.applyRequestHeaders(req)

	return
}
1174076
func NewRequest(w http.ResponseWriter, r *http.Request, debug bool) *Request {
	return &Request{
		Req:   r,
		w:     w,
		debug: debug,
	}
}
296670
func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {
	rel, err := url.Parse(urlStr)
	if err != nil {
		return nil, err
	}
	// Relative URLs should be specified without a preceding slash since baseURL will have the trailing slash
	rel.Path = strings.TrimLeft(rel.Path, "/")

	u := c.baseURL.ResolveReference(rel)

	var buf io.ReadWriter
	if body != nil {
		buf = new(bytes.Buffer)
		err = json.NewEncoder(buf).Encode(body)
		if err != nil {
			return nil, err
		}
	}

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

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

	// Set authentication information
	if c.Authentication.authType == authTypeSession {
		// Set session cookie if there is one
		if c.session != nil {
			for _, cookie := range c.session.Cookies {
				req.AddCookie(cookie)
			}
		}
	} else if c.Authentication.authType == authTypeBasic {
		// Set basic auth information
		if c.Authentication.username != "" {
			req.SetBasicAuth(c.Authentication.username, c.Authentication.password)
		}
	}

	return req, nil
}
138314
func (c *KinesisVideo) newRequest(op *request.Operation, params, data interface{}) *request.Request {
	req := c.NewRequest(op, params, data)

	// Run custom request initialization if present
	if initRequest != nil {
		initRequest(req)
	}

	return req
}
317337
func (h *Handler) NewRequest(ctx context.Context, feed *Feed) (request *Request, err error) {
	if feed == nil {
		return nil, NewError(ErrInvalidValue, "feed cannot be nil")
	}

	now := TimestampProvider.Now().Time
	request = new(Request)
	request.Header.Version = ProtocolVersion

	query := NewQueryLatest(feed, lookup.NoClue)

	feedUpdate, err := h.Lookup(ctx, query)
	if err != nil {
		if err.(*Error).code != ErrNotFound {
			return nil, err
		}
		// not finding updates means that there is a network error
		// or that the feed really does not have updates
	}

	request.Feed = *feed

	// if we already have an update, then find next epoch
	if feedUpdate != nil {
		request.Epoch = lookup.GetNextEpoch(feedUpdate.Epoch, now)
	} else {
		request.Epoch = lookup.GetFirstEpoch(now)
	}

	return request, nil
}
436430
func (c *httpConnection) NewRequest(method, path string) (driver.Request, error) {
	switch method {
	case "GET", "POST", "DELETE", "HEAD", "PATCH", "PUT", "OPTIONS":
	// Ok
	default:
		return nil, driver.WithStack(driver.InvalidArgumentError{Message: fmt.Sprintf("Invalid method '%s'", method)})
	}
	ct := c.contentType
	if ct != driver.ContentTypeJSON && strings.Contains(path, "_api/gharial") {
		// Currently (3.1.18) calls to this API do not work well with vpack.
		ct = driver.ContentTypeJSON
	}
	switch ct {
	case driver.ContentTypeJSON:
		r := &httpJSONRequest{
			method: method,
			path:   path,
		}
		return r, nil
	case driver.ContentTypeVelocypack:
		r := &httpVPackRequest{
			method: method,
			path:   path,
		}
		return r, nil
	default:
		return nil, driver.WithStack(fmt.Errorf("Unsupported content type %d", int(c.contentType)))
	}
}
648790
func (c *Client) NewRequest(method, requestPath string) *Request {
	c.modifyLock.RLock()
	addr := c.addr
	token := c.token
	mfaCreds := c.mfaCreds
	wrappingLookupFunc := c.wrappingLookupFunc
	headers := c.headers
	policyOverride := c.policyOverride
	c.modifyLock.RUnlock()

	// if SRV records exist (see https://tools.ietf.org/html/draft-andrews-http-srv-02), lookup the SRV
	// record and take the highest match; this is not designed for high-availability, just discovery
	var host string = addr.Host
	if addr.Port() == "" {
		// Internet Draft specifies that the SRV record is ignored if a port is given
		_, addrs, err := net.LookupSRV("http", "tcp", addr.Hostname())
		if err == nil && len(addrs) > 0 {
			host = fmt.Sprintf("%s:%d", addrs[0].Target, addrs[0].Port)
		}
	}

	req := &Request{
		Method: method,
		URL: &url.URL{
			User:   addr.User,
			Scheme: addr.Scheme,
			Host:   host,
			Path:   path.Join(addr.Path, requestPath),
		},
		ClientToken: token,
		Params:      make(map[string][]string),
	}

	var lookupPath string
	switch {
	case strings.HasPrefix(requestPath, "/v1/"):
		lookupPath = strings.TrimPrefix(requestPath, "/v1/")
	case strings.HasPrefix(requestPath, "v1/"):
		lookupPath = strings.TrimPrefix(requestPath, "v1/")
	default:
		lookupPath = requestPath
	}

	req.MFAHeaderVals = mfaCreds

	if wrappingLookupFunc != nil {
		req.WrapTTL = wrappingLookupFunc(method, lookupPath)
	} else {
		req.WrapTTL = DefaultWrappingLookupFunc(method, lookupPath)
	}

	if headers != nil {
		req.Headers = headers
	}

	req.PolicyOverride = policyOverride

	return req
}
900855
func (c *Client) newRequest(method string, args *dnode.Partial) (*Request, func(interface{}, *Error)) {
	// Parse dnode method arguments: [options]
	var options callOptions
	args.One().MustUnmarshal(&options)

	// Notify the handlers registered with Kite.OnFirstRequest().
	if _, ok := c.session.(*sockjsclient.WebsocketSession); !ok {
		c.firstRequestHandlersNotified.Do(func() {
			c.m.Lock()
			c.Kite = options.Kite
			c.m.Unlock()
			c.LocalKite.callOnFirstRequestHandlers(c)
		})
	}

	request := &Request{
		ID:        utils.RandomString(16),
		Method:    method,
		Args:      options.WithArgs,
		LocalKite: c.LocalKite,
		Client:    c,
		Auth:      options.Auth,
		Context:   c.context(),
	}

	// Call response callback function, send back our response
	callFunc := func(result interface{}, err *Error) {
		if options.ResponseCallback.Caller == nil {
			return
		}

		// Only argument to the callback.
		response := Response{
			Result: result,
			Error:  err,
		}

		if err := options.ResponseCallback.Call(response); err != nil {
			c.LocalKite.Log.Error(err.Error())
		}
	}

	return request, callFunc
}
1370848
func (adm AdminClient) newRequest(method string, reqData requestData) (req *http.Request, err error) {
	// If no method is supplied default to 'POST'.
	if method == "" {
		method = "POST"
	}

	// Default all requests to ""
	location := ""

	// Construct a new target URL.
	targetURL, err := adm.makeTargetURL(reqData)
	if err != nil {
		return nil, err
	}

	// Initialize a new HTTP request for the method.
	req, err = http.NewRequest(method, targetURL.String(), nil)
	if err != nil {
		return nil, err
	}

	adm.setUserAgent(req)
	for k, v := range reqData.customHeaders {
		req.Header.Set(k, v[0])
	}
	if length := len(reqData.content); length > 0 {
		req.ContentLength = int64(length)
	}
	req.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum256(reqData.content)))
	req.Body = ioutil.NopCloser(bytes.NewReader(reqData.content))

	req = s3signer.SignV4(*req, adm.accessKeyID, adm.secretAccessKey, "", location)
	return req, nil
}