// HandleResponse manages the http.Response content from a
// bridge Get/Put/Post/Delete by checking it for errors
// and invalid return types.
330102
func HandleResponse(resp *http.Response) ([]byte, io.Reader, error) {
	body, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
	if err != nil {
		trace("Error parsing bridge description xml.", nil)
		return []byte{}, nil, err
	}
	reader := bytes.NewReader(body)
	if strings.Contains(string(body), "\"error\"") {
		errString := string(body)
		errNum := errString[strings.Index(errString, "type\":")+6 : strings.Index(errString, ",\"address")]
		errDesc := errString[strings.Index(errString, "description\":\"")+14 : strings.Index(errString, "\"}}")]
		errOut := fmt.Sprintf("Error type %s: %s.", errNum, errDesc)
		err = errors.New(errOut)
		return []byte{}, nil, err
	}
	return body, reader, nil
}
850367
func (c *Client) HandleResponse(res *http.Response, rc client.ResponseClass, err error) (mesos.Response, error) {
	if err != nil {
		if res != nil && res.Body != nil {
			res.Body.Close()
		}
		return nil, err
	}

	result := &Response{
		Closer: res.Body,
		Header: res.Header,
	}
	if err = c.errorMapper(res); err != nil {
		return result, err
	}

	err = validateSuccessfulResponse(c.codec, res, rc)
	if err != nil {
		res.Body.Close()
		return nil, err
	}

	switch res.StatusCode {
	case http.StatusOK:
		debug.Log("request OK, decoding response")

		sf := newSourceFactory(rc, res.ContentLength > -1)
		if sf == nil {
			if rc != client.ResponseClassNoData {
				panic("nil Source for response that expected data")
			}
			// we don't expect any data. drain the response body and close it (compliant with golang's expectations
			// for http/1.1 keepalive support.
			defer res.Body.Close()
			_, err = io.Copy(ioutil.Discard, res.Body)
			return nil, err
		}

		result.Decoder = c.codec.NewDecoder(sf.NewSource(res.Body))

	case http.StatusAccepted:
		debug.Log("request Accepted")

		// noop; no decoder for these types of calls
		defer res.Body.Close()
		_, err = io.Copy(ioutil.Discard, res.Body)
		return nil, err

	default:
		debug.Log("unexpected HTTP status", res.StatusCode)

		defer res.Body.Close()
		io.Copy(ioutil.Discard, res.Body) // intentionally discard any error here
		return nil, ProtocolError(fmt.Sprintf("unexpected mesos HTTP response code: %d", res.StatusCode))
	}

	return result, nil
}
656791
func (m *Mux) UseResponse(fn c.HandlerFunc) *Mux {
	m.Middleware.UseResponse(fn)
	return m
}
331542
func (fn AddOneHandlerFunc) Handle(params AddOneParams, principal interface{}) middleware.Responder {
	return fn(params, principal)
}
974058
func Handler(w http.ResponseWriter, r *http.Request) {
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		return
	}
	c := &connection{send: make(chan []byte, 256), ws: ws}
	wsHub.register <- c
	defer func() { wsHub.unregister <- c }()
	go c.writer()
	c.reader()
}
110413
func (parser *StandardResultParser) ParseResponse(response *SolrResponse, sr *SolrResult) (err error) {
	if resp, ok := response.Response["response"].(map[string]interface{}); ok {
		ParseDocResponse(resp, sr.Results)
	} else if grouped, ok := response.Response["grouped"].(map[string]interface{}); ok {
		sr.Grouped = grouped
	} else {
		err = fmt.Errorf(`Standard parser can only parse solr response with response object,
					ie response.response and response.response.docs. Or grouped response
					Please use other parser or implement your own parser`)
	}

	return err
}
996344
func (r *resp) receiveResponse() *response {
	// Receive first line.
	line, err := r.reader.ReadBytes('\n')
	if err != nil {
		rerr := errors.Annotate(err, ErrConnectionBroken, errorMessages, "receive after "+r.cmd)
		return &response{receivingError, 0, nil, rerr}
	}
	content := line[1 : len(line)-2]
	// First byte defines kind.
	switch line[0] {
	case '+':
		// Status response.
		return &response{statusResponse, 0, line[:len(line)-2], nil}
	case '-':
		// Error response.
		return &response{errorResponse, 0, line[:len(line)-2], nil}
	case ':':
		// Integer response.
		return &response{integerResponse, 0, content, nil}
	case '$':
		// Bulk response or null bulk response.
		count, err := strconv.Atoi(string(content))
		if err != nil {
			return &response{receivingError, 0, nil, errors.Annotate(err, ErrServerResponse, errorMessages)}
		}
		if count == -1 {
			// Null bulk response.
			return &response{nullBulkResponse, 0, nil, nil}
		}
		// Receive the bulk data.
		toRead := count + 2
		buffer := make([]byte, toRead)
		n, err := io.ReadFull(r.reader, buffer)
		if err != nil {
			return &response{receivingError, 0, nil, err}
		}
		if n < toRead {
			return &response{receivingError, 0, nil, errors.New(ErrServerResponse, errorMessages)}
		}
		return &response{bulkResponse, 0, buffer[0:count], nil}
	case '*':
		// Array reply. Check for timeout.
		length, err := strconv.Atoi(string(content))
		if err != nil {
			return &response{receivingError, 0, nil, errors.Annotate(err, ErrServerResponse, errorMessages)}
		}
		if length == -1 {
			// Timeout.
			return &response{timeoutError, 0, nil, nil}
		}
		return &response{arrayResponse, length, nil, nil}
	}
	return &response{receivingError, 0, nil, errors.New(ErrInvalidResponse, errorMessages, string(line))}
}
735008
func JSONResponse(w http.ResponseWriter, v interface{}) error {
	w.Header().Set(HeaderContentType, JSONType)
	return json.NewEncoder(w).Encode(v)
}
314223
func (s *SocketServer) handleResponses(closeConn chan error, conn net.Conn, responses <-chan *types.Response) {
	var count int
	var bufWriter = bufio.NewWriter(conn)
	for {
		var res = <-responses
		err := types.WriteMessage(res, bufWriter)
		if err != nil {
			closeConn <- fmt.Errorf("Error writing message: %v", err.Error())
			return
		}
		if _, ok := res.Value.(*types.Response_Flush); ok {
			err = bufWriter.Flush()
			if err != nil {
				closeConn <- fmt.Errorf("Error flushing write buffer: %v", err.Error())
				return
			}
		}
		count++
	}
}
45904
func (s *Server) Handle(route string, method string, httpHandler http.Handler) {
	s.addRoute(route, method, httpHandler)
}
7610
func (f *lightFetcher) processResponse(req fetchRequest, resp fetchResponse) bool {
	if uint64(len(resp.headers)) != req.amount || resp.headers[0].Hash() != req.hash {
		req.peer.Log().Debug("Response content mismatch", "requested", len(resp.headers), "reqfrom", resp.headers[0], "delivered", req.amount, "delfrom", req.hash)
		return false
	}
	headers := make([]*types.Header, req.amount)
	for i, header := range resp.headers {
		headers[int(req.amount)-1-i] = header
	}

	if _, err := f.chain.InsertHeaderChain(headers, 1); err != nil {
		if err == consensus.ErrFutureBlock {
			return true
		}
		log.Debug("Failed to insert header chain", "err", err)
		return false
	}
	tds := make([]*big.Int, len(headers))
	for i, header := range headers {
		td := f.chain.GetTd(header.Hash(), header.Number.Uint64())
		if td == nil {
			log.Debug("Total difficulty not found for header", "index", i+1, "number", header.Number, "hash", header.Hash())
			return false
		}
		tds[i] = td
	}
	f.newHeaders(headers, tds)
	return true
}
220308
func EncodeResponse(w http.ResponseWriter, res interface{}, err bool) {
	w.Header().Set("Content-Type", DefaultContentTypeV1_1)
	if err {
		w.WriteHeader(http.StatusInternalServerError)
	}
	json.NewEncoder(w).Encode(res)
}
527240
func (bc *brokerConsumer) handleResponses() {
	for child := range bc.subscriptions {
		result := child.responseResult
		child.responseResult = nil

		switch result {
		case nil:
			// no-op
		case errTimedOut:
			Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because consuming was taking too long\n",
				bc.broker.ID(), child.topic, child.partition)
			delete(bc.subscriptions, child)
		case ErrOffsetOutOfRange:
			// there's no point in retrying this it will just fail the same way again
			// shut it down and force the user to choose what to do
			child.sendError(result)
			Logger.Printf("consumer/%s/%d shutting down because %s\n", child.topic, child.partition, result)
			close(child.trigger)
			delete(bc.subscriptions, child)
		case ErrUnknownTopicOrPartition, ErrNotLeaderForPartition, ErrLeaderNotAvailable, ErrReplicaNotAvailable:
			// not an error, but does need redispatching
			Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because %s\n",
				bc.broker.ID(), child.topic, child.partition, result)
			child.trigger <- none{}
			delete(bc.subscriptions, child)
		default:
			// dunno, tell the user and try redispatching
			child.sendError(result)
			Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because %s\n",
				bc.broker.ID(), child.topic, child.partition, result)
			child.trigger <- none{}
			delete(bc.subscriptions, child)
		}
	}
}
1254704
func (l *bufferedLog) AddResponse(r auditlog.ResponseErrors) error {
	l.mu.Lock()
	if len(l.buffer) > 0 {
		l.deferMessage(r)
		l.mu.Unlock()
		return nil
	}
	l.mu.Unlock()
	// We've already flushed messages, forward this on
	// immediately.
	return l.dest.AddResponse(r)
}
561450
func (c *Client) newResponse(res *http.Response) (*Response, error) {
	r := &Response{
		StatusCode: res.StatusCode,
		Header:     res.Header,
	}
	if res.Body != nil {
		slurp, err := ioutil.ReadAll(res.Body)
		if err != nil {
			return nil, err
		}
		// HEAD requests return a body but no content
		if len(slurp) > 0 {
			if err := c.decoder.Decode(slurp, &r.Body); err != nil {
				return nil, err
			}
		}
	}
	return r, nil
}
131989
func getResponse(r io.Reader) (*http.Response, []byte, error) {
	rawResponse := bytes.NewBuffer(make([]byte, 0, 256))
	// Save the bytes read while reading the response headers into the rawResponse buffer
	resp, err := http.ReadResponse(bufio.NewReader(io.TeeReader(r, rawResponse)), nil)
	if err != nil {
		return nil, nil, err
	}
	// return the http response and the raw bytes consumed from the reader in the process
	return resp, rawResponse.Bytes(), nil
}
506158
func JSONResponse(w http.ResponseWriter, code int, data interface{}) {
	w.Header()["Content-Type"] = []string{"application/json"}
	w.WriteHeader(code)
	switch code {
	case 204, 304:
		/* no body */
	default:
		if data == nil {
			data = ResourceError{code, "Server Error"}
		}
		b, e := json.MarshalIndent(data, "", "  ")
		if e != nil {
			code = http.StatusInternalServerError
			b, _ = json.MarshalIndent(ResourceError{500, "Server Error"}, "", "  ")
		}
		fmt.Fprintf(w, "%s\n", string(b))
	}
}