// Extract response elements to be sent with event notifiation.
429684
func extractRespElements(w http.ResponseWriter) map[string]string {

	return map[string]string{
		"requestId":      w.Header().Get(responseRequestIDKey),
		"content-length": w.Header().Get("Content-Length"),
		// Add more fields here.
	}
}
577943
func (a *APIDefinition) IterateResponses(it ResponseIterator) error {
	names := make([]string, len(a.Responses))
	i := 0
	for n := range a.Responses {
		names[i] = n
		i++
	}
	sort.Strings(names)
	for _, n := range names {
		if err := it(a.Responses[n]); err != nil {
			return err
		}
	}
	return nil
}
307842
func extractRequestInfoFromReq(req *http.Request) *RequestJSON {
	proto := "http://"
	if req.TLS != nil {
		proto = "https://"
	}
	return &RequestJSON{
		ClientIP:   req.RemoteAddr,
		HTTPMethod: req.Method,
		URL:        proto + req.Host + req.RequestURI,
		Referer:    req.Referer(),
		Headers:    parseRequestHeaders(req.Header),
	}
}
1014303
func encodeResponseJSON(response interface{}) []byte {
	var bytesBuffer bytes.Buffer
	e := json.NewEncoder(&bytesBuffer)
	e.Encode(response)
	return bytesBuffer.Bytes()
}
885794
func ReadResponse(body io.ReadCloser) (*Response, error) {
	parser := xml.NewDecoder(body)
	for {
		token, err := parser.Token()
		if err != nil {
			return nil, err
		}
		switch t := token.(type) {
		case xml.StartElement:
			// clear any accumulated data
			switch t.Name.Local {
			case XMLElemRETS, XMLElemRETSStatus:
				return ResponseTag(t).Parse()
			}
		}
	}
}
1102306
func SelectResponseFromHTTPResponse(b []byte) (*SelectResponse, error) {
	j, err := BytesToJSON(&b)
	if err != nil {
		return nil, err
	}

	resp, err := BuildResponse(j)
	if err != nil {
		return nil, err
	}

	return resp, nil
}
1240635
func (r *Response) Element() *etree.Element {
	el := etree.NewElement("samlp:Response")
	el.CreateAttr("xmlns:saml", "urn:oasis:names:tc:SAML:2.0:assertion")
	el.CreateAttr("xmlns:samlp", "urn:oasis:names:tc:SAML:2.0:protocol")

	// Note: This namespace is not used by any element or attribute name, but
	// is required so that the AttributeValue type element can have a value like
	// "xs:string". If we don't declare it here, then it will be stripped by the
	// cannonicalizer. This could be avoided by providing a prefix list to the
	// cannonicalizer, but prefix lists do not appear to be implemented correctly
	// in some libraries, so the safest action is to always produce XML that is
	// (a) in cannonical form and (b) does not require prefix lists.
	el.CreateAttr("xmlns:xs", "http://www.w3.org/2001/XMLSchema")

	el.CreateAttr("ID", r.ID)
	if r.InResponseTo != "" {
		el.CreateAttr("InResponseTo", r.InResponseTo)
	}
	el.CreateAttr("Version", r.Version)
	el.CreateAttr("IssueInstant", r.IssueInstant.Format(timeFormat))
	if r.Destination != "" {
		el.CreateAttr("Destination", r.Destination)
	}
	if r.Consent != "" {
		el.CreateAttr("Consent", r.Consent)
	}
	if r.Issuer != nil {
		el.AddChild(r.Issuer.Element())
	}
	if r.Signature != nil {
		el.AddChild(r.Signature)
	}
	el.AddChild(r.Status.Element())
	if r.EncryptedAssertion != nil {
		el.AddChild(r.EncryptedAssertion)
	}
	if r.Assertion != nil {
		el.AddChild(r.Assertion.Element())
	}
	return el
}
1058100
func handleResponses(responses chan libhoney.Response, stats *responseStats,
	toBeResent chan event.Event, delaySending chan int,
	options GlobalOptions) {
	go logStats(stats, options.StatusInterval)

	for rsp := range responses {
		stats.update(rsp)
		logfields := logrus.Fields{
			"status_code": rsp.StatusCode,
			"body":        strings.TrimSpace(string(rsp.Body)),
			"duration":    rsp.Duration,
			"error":       rsp.Err,
			"timestamp":   rsp.Metadata.(event.Event).Timestamp,
		}
		// if this is an error we should retry sending, re-enqueue the event
		if options.BackOff && (rsp.StatusCode == 429 || rsp.StatusCode == 500) {
			logfields["retry_send"] = true
			delaySending <- 1000 / int(options.NumSenders) // back off for a little bit
			toBeResent <- rsp.Metadata.(event.Event)       // then retry sending the event
		} else {
			logfields["retry_send"] = false
		}
		logrus.WithFields(logfields).Debug("event send record received")
	}
}
879502
func (c *Client) GetResponseJson(method string, requestUrl string, requestPath string, body string) (responseBody string, err error) {

	//	fmt.Println("method %s, requestPath: %s", requestUrl, requestPath)
	reqest, err := http.NewRequest(method, requestUrl, strings.NewReader(body))
	if err != nil {
		return responseBody, err
	}

	InitBaseHeader(reqest)

	//	如果是post请求，并且有post请求内容则加上Content-MD5头
	if body != "" && method == "POST" {
		reqest.Header.Set("Content-MD5", BodyMd5(body))
	}

	if c.securityToken != "" {
		reqest.Header["x-acs-security-token"] = []string{c.securityToken}
	}

	c.Sign(method, requestPath, reqest, "")

	if method != "POST" {
		reqest.Header.Del("Content-MD5")

	}
	//reqest.Header.Del("Accept-Encoding")
	reqest.Header.Set("Accept-Encoding", "deflate,sdch")

	log.Printf("RequestUrl = %++v", reqest)
	client := &http.Client{}
	t0 := time.Now()
	response, err := client.Do(reqest)
	t1 := time.Now()
	if err != nil {
		return body, err
	}

	if c.debug {
		log.Printf("Invoke %s %s %d (%v)", method, requestUrl, response.StatusCode, t1.Sub(t0))
	}

	rsBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return "", err
	}
	//如果状态吗是非200则进行返回值的过滤,使得pop返回的错误和程序的错误输出一致
	if response.StatusCode != 200 {
		err = errors.New("Response status code faild" + string(rsBody))
		type ResultError struct {
			RequestId string `json:"requestId"`
			HostId    string `json:"hostId"`
			Code      string `json:"code"`
			Message   string `json:"Message"`
		}
		var rsError ResultError
		rsBodyString := string(rsBody)
		_ = json.Unmarshal([]byte(rsBodyString), &rsError)

		newResult := ResultModel{
			rsError.Code,
			rsError.Message,
			false,
		}

		resultJson, _ := json.Marshal(newResult)

		return string(resultJson), err

	}

	return string(rsBody), err
}
821163
func apiResponse(message, docId string, response *http.Response, error error) APIResponse {
	r := APIResponse{
		Message: message,
		DocumentId: docId,
		Error: error,
		HttpResponse: response,
	}

	if response != nil {
		r.RequestId = response.Header.Get("X-Request-Id")
	}

	return r
}
528845
func (c Client) fetchEvents(since int64) (PollResponse, error) {
	u := c.url
	if c.LoggingEnabled {
		log.Println("Checking for changes events since", since, "on URL", u.String())
	}

	query := u.Query()
	query.Set("category", c.category)
	query.Set("since_time", fmt.Sprintf("%d", since))
	query.Set("timeout", fmt.Sprintf("%d", c.Timeout))
	u.RawQuery = query.Encode()

	req, _ := http.NewRequest("GET", u.String(), nil)
	if c.BasicAuthUsername != "" && c.BasicAuthPassword != "" {
		req.SetBasicAuth(c.BasicAuthUsername, c.BasicAuthPassword)
	}

	resp, err := c.HttpClient.Do(req)
	if err != nil {
		msg := fmt.Sprintf("Error while connecting to %s to observe changes. Error was: %s", u, err)
		return PollResponse{}, errors.New(msg)
	}

	if resp.StatusCode != http.StatusOK {
		msg := fmt.Sprintf("Wrong status code received from longpoll server: %d", resp.StatusCode)
		return PollResponse{}, errors.New(msg)
	}

	decoder := json.NewDecoder(resp.Body)
	defer resp.Body.Close()

	var pr PollResponse
	err = decoder.Decode(&pr)
	if err != nil {
		if c.LoggingEnabled {
			log.Println("Error while decoding poll response: %s", err)
		}
		return PollResponse{}, err
	}

	return pr, nil
}
837964
func (h *HTTPBin) ResponseHeaders(w http.ResponseWriter, r *http.Request) {
	args := r.URL.Query()
	for k, vs := range args {
		for _, v := range vs {
			w.Header().Add(http.CanonicalHeaderKey(k), v)
		}
	}
	body, _ := json.Marshal(args)
	if contentType := w.Header().Get("Content-Type"); contentType == "" {
		w.Header().Set("Content-Type", jsonContentType)
	}
	w.Write(body)
}
373211
func (c *ContextTemplateData) IterateResponses(it func(*design.ResponseDefinition) error) error {
	m := make(map[int]*design.ResponseDefinition, len(c.Responses))
	var s []int
	for _, resp := range c.Responses {
		status := resp.Status
		m[status] = resp
		s = append(s, status)
	}
	sort.Ints(s)
	for _, status := range s {
		if err := it(m[status]); err != nil {
			return err
		}
	}
	return nil
}
853861
func getResponseFromJSON(ctx context.Context, r *httpRequest, v interface{}) error {
	r.addHeader("User-Agent", MailgunGoUserAgent)
	response, err := r.makeGetRequest(ctx)
	if err != nil {
		return err
	}
	if notGood(response.Code, expected) {
		return newError(r.URL, expected, response)
	}
	return response.parseFromJSON(v)
}
1285831
func ExtractHeaderValue(header string, resp *http.Response) string {
	h := ExtractHeader(header, resp)
	if len(h) > 0 {
		return h[0]
	}
	return ""
}
1145741
func (s *VolumeService) ExtractVolume(p *ExtractVolumeParams) (*ExtractVolumeResponse, error) {
	resp, err := s.cs.newRequest("extractVolume", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r ExtractVolumeResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
542569
func (client *Client) GetEvents(filters ...Filter) ([]Event, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetEventsRequest,
		Query:       ConvertFilterParameters(filters),
	})
	if err != nil {
		return nil, nil, err
	}

	var fullEventsList []Event
	warnings, err := client.paginate(request, Event{}, func(item interface{}) error {
		if event, ok := item.(Event); ok {
			fullEventsList = append(fullEventsList, event)
		} else {
			return ccerror.UnknownObjectInListError{
				Expected:   Event{},
				Unexpected: item,
			}
		}
		return nil
	})

	return fullEventsList, warnings, err
}