// parseResponseArray parses an array response in the given response
181860
func parseResponseArray(resp Response, count int, cs contextSettings, results interface{}) (DocumentMetaSlice, ErrorSlice, error) {
	resps, err := resp.ParseArrayBody()
	if err != nil {
		return nil, nil, WithStack(err)
	}
	metas := make(DocumentMetaSlice, count)
	errs := make(ErrorSlice, count)
	returnOldVal := reflect.ValueOf(cs.ReturnOld)
	returnNewVal := reflect.ValueOf(cs.ReturnNew)
	resultsVal := reflect.ValueOf(results)
	for i := 0; i < count; i++ {
		resp := resps[i]
		var meta DocumentMeta
		if err := resp.CheckStatus(200, 201, 202); err != nil {
			errs[i] = err
		} else {
			if err := resp.ParseBody("", &meta); err != nil {
				errs[i] = err
			} else {
				metas[i] = meta
				// Parse returnOld (if needed)
				if cs.ReturnOld != nil {
					returnOldEntryVal := returnOldVal.Index(i).Addr()
					if err := resp.ParseBody("old", returnOldEntryVal.Interface()); err != nil {
						errs[i] = err
					}
				}
				// Parse returnNew (if needed)
				if cs.ReturnNew != nil {
					returnNewEntryVal := returnNewVal.Index(i).Addr()
					if err := resp.ParseBody("new", returnNewEntryVal.Interface()); err != nil {
						errs[i] = err
					}
				}
			}
			if results != nil {
				// Parse compare result document
				resultsEntryVal := resultsVal.Index(i).Addr()
				if err := resp.ParseBody("", resultsEntryVal.Interface()); err != nil {
					errs[i] = err
				}
			}
		}
	}
	return metas, errs, nil
}
493914
func response(ctx context.Context, url string, obj ResponseParser) error {
	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		return err
	}
	req = req.WithContext(ctx)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}

	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	body := strings.Trim(string(data), " []")
	if body == "" {
		return nil
	}
	if err := json.Unmarshal([]byte(body), obj); err != nil {
		Logger.Printf("payload: %s\n", body)
		return err
	}

	return nil
}
108780
func (h *handler) handleResponse(msg *jsonrpcMessage) {
	op := h.respWait[string(msg.ID)]
	if op == nil {
		h.log.Debug("Unsolicited RPC response", "reqid", idForLog{msg.ID})
		return
	}
	delete(h.respWait, string(msg.ID))
	// For normal responses, just forward the reply to Call/BatchCall.
	if op.sub == nil {
		op.resp <- msg
		return
	}
	// For subscription responses, start the subscription if the server
	// indicates success. EthSubscribe gets unblocked in either case through
	// the op.resp channel.
	defer close(op.resp)
	if msg.Error != nil {
		op.err = msg.Error
		return
	}
	if op.err = json.Unmarshal(msg.Result, &op.sub.subid); op.err == nil {
		go op.sub.start()
		h.clientSubs[op.sub.subid] = op.sub
	}
}
218650
func handleResponse(r *http.Response) (*oauth.Token, error) {
	o := &oauth.Token{}
	defer r.Body.Close()
	if r.StatusCode != 200 {
		return o, errors.New("invalid response: " + r.Status)
	}
	b := &respBody{}
	err := json.NewDecoder(r.Body).Decode(b)
	if err != nil {
		return o, err
	}
	o.AccessToken = b.Access
	if b.IdToken != "" {
		// decode returned id token to get expiry
		o.AccessToken = b.IdToken
		s := strings.Split(b.IdToken, ".")
		if len(s) < 2 {
			return nil, errors.New("invalid token received")
		}
		d, err := base64Decode(s[1])
		if err != nil {
			return o, err
		}
		c := &ClaimSet{}
		err = json.NewDecoder(bytes.NewBuffer(d)).Decode(c)
		if err != nil {
			return o, err
		}
		o.Expiry = time.Unix(c.Exp, 0)
		return o, nil
	}
	o.Expiry = time.Now().Add(b.ExpiresIn * time.Second)
	return o, nil
}
155387
func (c *Client) parseStateResponse(resp *http.Response, err error) (*State, error) {
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)

	var state State
	err = json.Unmarshal(body, &state)
	if err != nil {
		return nil, err
	}

	c.Lock()
	c.State = &state
	c.Unlock()

	return c.State, nil
}
668855
func (s *Spec) AllResponseReferences() (result []string) {
	for _, v := range s.references.responses {
		result = append(result, v.String())
	}
	return
}
599753
func (j *JsonQuery) ArrayOfArrays(s ...string) ([][]interface{}, error) {
	array, err := j.Array(s...)
	if err != nil {
		return [][]interface{}{}, err
	}
	toReturn := make([][]interface{}, len(array))
	for index, val := range array {
		toReturn[index], err = arrayFromInterface(val)
		if err != nil {
			return toReturn, err
		}
	}
	return toReturn, nil
}
268941
func (c *Client) parseResponse(r *bufio.Reader) (interface{}, error) {
	line, err := r.ReadString('\n')
	if err != nil {
		if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
			err = ErrTimedOut
		}
		return nil, err
	}
	//log.Printf("line=%#v %x\n", line, &r)
	if len(line) < 1 {
		return nil, ErrServerError
	}
	reply := byte(line[0])
	lineLen := len(line)
	if len(line) > 2 && line[lineLen-2:] == "\r\n" {
		line = line[1 : lineLen-2]
	}
	switch reply {
	case '-': // Error reply
		return nil, errors.New(line)
	case '+': // Status reply
		return line, nil
	case ':': // Integer reply
		resp, err := strconv.Atoi(line)
		if err != nil {
			return nil, err
		}
		return resp, nil
	case '$': // Bulk reply
		valueLen, err := strconv.Atoi(line)
		if err != nil {
			return nil, err
		}
		if valueLen == -1 {
			return "", nil // err = ErrCacheMiss?
		}
		b := make([]byte, valueLen+2) // 2==crlf
		var s byte
		for n := 0; n < cap(b); n++ {
			s, err = r.ReadByte()
			if err != nil {
				return nil, err
			}
			b[n] = s
		}
		if len(b) != cap(b) {
			return nil, fmt.Errorf("unexpected response: %#v", line)
		}
		return string(b[:valueLen]), nil // strip off trailing crlf
	case '*': // Multi-bulk reply
		//fmt.Printf("multibulk line=%#v\n", line)
		nitems, err := strconv.Atoi(line)
		if err != nil {
			return nil, err
		}
		if nitems < 1 {
			return nil, nil
		}
		resp := make([]interface{}, nitems)
		for n := 0; n < nitems; n++ {
			resp[n], err = c.parseResponse(r)
			if err != nil {
				return nil, err
			}
		}
		//log.Printf("multibulk=%#v\n", resp)
		return resp, nil
	default:
		return nil, ErrServerError
	}
}
1273508
func (r *httpJSONResponse) ParseArrayBody() ([]driver.Response, error) {
	if r.bodyArray == nil {
		var bodyArray []map[string]*json.RawMessage
		if err := json.Unmarshal(r.rawResponse, &bodyArray); err != nil {
			return nil, driver.WithStack(err)
		}
		r.bodyArray = bodyArray
	}
	resps := make([]driver.Response, len(r.bodyArray))
	for i, x := range r.bodyArray {
		resps[i] = &httpJSONResponseElement{bodyObject: x}
	}
	return resps, nil
}
809208
func ParseLabelArrayFromArray(base []string) LabelArray {
	array := make(LabelArray, len(base))
	for i := range base {
		array[i] = ParseLabel(base[i])
	}
	return array.Sort()
}
645617
func DecodeResponse(lines []string, v interface{}) error {
	if len(lines) > 1 {
		return NewInvalidResponseError("too many lines", lines)
	} else if len(lines) == 0 {
		return NewInvalidResponseError("no lines", lines)
	}

	input := make(map[string]interface{})
	value := reflect.ValueOf(v)
	var slice reflect.Value
	var elemType reflect.Type
	if value.Kind() == reflect.Ptr {
		slice = value.Elem()
		if slice.Kind() == reflect.Slice {
			elemType = slice.Type().Elem()
		}
	}

	for _, part := range strings.Split(lines[0], "|") {
		for _, val := range strings.Split(part, " ") {
			parts := strings.SplitN(val, "=", 2)
			// TODO(steve): support groups
			key := Decode(parts[0])
			if len(parts) == 2 {
				v := Decode(parts[1])
				if i, err := strconv.Atoi(v); err != nil {
					input[key] = v
				} else {
					input[key] = i
				}
			} else {
				input[key] = ""
			}
		}

		if elemType != nil {
			// Expecting a slice
			if err := decodeSlice(elemType, slice, input); err != nil {
				return err
			}

			// Reset the input map
			input = make(map[string]interface{})
		}
	}

	if elemType != nil {
		// Expecting a slice, already decoded
		return nil
	}

	return decodeMap(input, v)
}
797223
func (p *Parser) parseArray(cur *ListNode) error {
Loop:
	for {
		switch p.next() {
		case eof, '\n':
			return fmt.Errorf("unterminated array")
		case ']':
			break Loop
		}
	}
	text := p.consumeText()
	text = text[1 : len(text)-1]
	if text == "*" {
		text = ":"
	}

	//union operator
	strs := strings.Split(text, ",")
	if len(strs) > 1 {
		union := []*ListNode{}
		for _, str := range strs {
			parser, err := parseAction("union", fmt.Sprintf("[%s]", strings.Trim(str, " ")))
			if err != nil {
				return err
			}
			union = append(union, parser.Root)
		}
		cur.append(newUnion(union))
		return p.parseInsideAction(cur)
	}

	// dict key
	value := dictKeyRex.FindStringSubmatch(text)
	if value != nil {
		parser, err := parseAction("arraydict", fmt.Sprintf(".%s", value[1]))
		if err != nil {
			return err
		}
		for _, node := range parser.Root.Nodes {
			cur.append(node)
		}
		return p.parseInsideAction(cur)
	}

	//slice operator
	value = sliceOperatorRex.FindStringSubmatch(text)
	if value == nil {
		return fmt.Errorf("invalid array index %s", text)
	}
	value = value[1:]
	params := [3]ParamsEntry{}
	for i := 0; i < 3; i++ {
		if value[i] != "" {
			if i > 0 {
				value[i] = value[i][1:]
			}
			if i > 0 && value[i] == "" {
				params[i].Known = false
			} else {
				var err error
				params[i].Known = true
				params[i].Value, err = strconv.Atoi(value[i])
				if err != nil {
					return fmt.Errorf("array index %s is not a number", value[i])
				}
			}
		} else {
			if i == 1 {
				params[i].Known = true
				params[i].Value = params[0].Value + 1
				params[i].Derived = true
			} else {
				params[i].Known = false
				params[i].Value = 0
			}
		}
	}
	cur.append(newArray(params))
	return p.parseInsideAction(cur)
}
843410
func parseHandshakeResponseHeader(ctx context.Context, packet *handshakeResponse41, data []byte) (parsedBytes int, err error) {
	// Ensure there are enough data to read:
	// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::SSLRequest
	if len(data) < 4+4+1+23 {
		logutil.Logger(ctx).Error("got malformed handshake response", zap.ByteString("packetData", data))
		return 0, mysql.ErrMalformPacket
	}

	offset := 0
	// capability
	capability := binary.LittleEndian.Uint32(data[:4])
	packet.Capability = capability
	offset += 4
	// skip max packet size
	offset += 4
	// charset, skip, if you want to use another charset, use set names
	packet.Collation = data[offset]
	offset++
	// skip reserved 23[00]
	offset += 23

	return offset, nil
}
234280
func parseResponseStatus(resp string, errorMap errorMap) error {
	code := 0
	reason := resp
	t := strings.SplitN(resp, " ", 2)
	if len(t) == 2 {
		ncode, err := strconv.Atoi(t[0])
		if err == nil {
			code = ncode
			reason = t[1]
		}
	}
	if errorMap != nil {
		if err, ok := errorMap[code]; ok {
			return err
		}
	}
	if 200 <= code && code <= 299 {
		return nil
	}
	return newError(code, reason)
}
468320
func parseSubscribeResponse(body []byte, resp *http.Response) (*SubscribeResponse, error) {

	subResp := new(SubscribeResponse)

	subResp.Status = resp.Status
	subResp.StatusCode = resp.StatusCode

	if err := json.Unmarshal(body, &subResp); err != nil {
		return nil, err
	}
	return subResp, nil
}
1001614
func GetResponseAndBytes(url string) (*http.Response, []byte, error) {
	resp, err := http.Get(url)
	if err != nil {
		return resp, []byte{}, err
	}
	bytes, err := ResponseBody(resp)
	return resp, bytes, err
}
555889
func ExpectJSONArray(t T, r *http.Response, callback func(array []interface{})) bool {
	if r == nil {
		logerror(t, serrorf("ExpectJSONArray: no response available"))
		return false
	}
	if r.Body == nil {
		logerror(t, serrorf("ExpectJSONArray: no body to read"))
		return false
	}
	data, err := ioutil.ReadAll(r.Body)
	defer r.Body.Close()
	if err != nil {
		if verboseOnFailure {
			Dump(t, r)
		}
		logerror(t, serrorf("ExpectJSONArray: unable to read response body:%v", err))
		return false
	}
	// put the body back for re-reads
	r.Body = ioutil.NopCloser(bytes.NewReader(data))

	slice := []interface{}{}
	err = json.Unmarshal(data, &slice)
	if err != nil {
		if verboseOnFailure {
			Dump(t, r)
		}
		logerror(t, serrorf("ExpectJSONArray: unable to unmarshal Json:%v", err))
		return false
	}
	callback(slice)
	return true
}