// searchResponses pages through search results and sends search responses to
// resC.
// Builds in resC have ids.
517587
func searchResponses(ctx context.Context, resC chan<- *pb.SearchBuildsResponse, client pb.BuildsClient, req *pb.SearchBuildsRequest) error {
	req = proto.Clone(req).(*pb.SearchBuildsRequest)

	// Ensure next_page_token and build id are requested.
	if len(req.GetFields().GetPaths()) > 0 {
		req.Fields.Paths = append(req.Fields.Paths, "next_page_token", "builds.*.id")
	}

	// Page through results.
	for {
		res, err := client.SearchBuilds(ctx, req)
		if err != nil {
			return err
		}

		select {
		case resC <- res:
		case <-ctx.Done():
			return ctx.Err()
		}

		if res.NextPageToken == "" || len(res.Builds) == 0 {
			return nil
		}

		// Next page...
		req.PageToken = res.NextPageToken
	}
}
370158
func newResponse(r *http.Response) *Response {
	response := &Response{Response: r}
	response.populatePageValues()
	response.Rate = parseRate(r)
	return response
}
445208
func (d *domainClient) SearchInResponseBody(ctx context.Context, args *SearchInResponseBodyArgs) (reply *SearchInResponseBodyReply, err error) {
	reply = new(SearchInResponseBodyReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "Network.searchInResponseBody", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Network.searchInResponseBody", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Network", Op: "SearchInResponseBody", Err: err}
	}
	return
}
1056373
func QueryResponsesEqual(r1, r2 []QueryResponse) bool {
	if len(r1) != len(r2) {
		return false
	}
	for i, r := range r1 {
		if !r.QueryResult.Equal(r2[i].QueryResult) {
			return false
		}
		if !vterrors.Equals(r.QueryError, r2[i].QueryError) {
			return false
		}
	}
	return true
}
103301
func (s *Search) PrefixSearch(args *structs.SearchRequest, reply *structs.SearchResponse) error {
	if done, err := s.srv.forward("Search.PrefixSearch", args, args, reply); done {
		return err
	}
	defer metrics.MeasureSince([]string{"nomad", "search", "prefix_search"}, time.Now())

	aclObj, err := s.srv.ResolveToken(args.AuthToken)
	if err != nil {
		return err
	}

	namespace := args.RequestNamespace()

	// Require either node:read or namespace:read-job
	if !anySearchPerms(aclObj, namespace, args.Context) {
		return structs.ErrPermissionDenied
	}

	reply.Matches = make(map[structs.Context][]string)
	reply.Truncations = make(map[structs.Context]bool)

	// Setup the blocking query
	opts := blockingOptions{
		queryMeta: &reply.QueryMeta,
		queryOpts: &structs.QueryOptions{},
		run: func(ws memdb.WatchSet, state *state.StateStore) error {

			iters := make(map[structs.Context]memdb.ResultIterator)

			contexts := searchContexts(aclObj, namespace, args.Context)

			for _, ctx := range contexts {
				iter, err := getResourceIter(ctx, aclObj, namespace, roundUUIDDownIfOdd(args.Prefix, args.Context), ws, state)
				if err != nil {
					e := err.Error()
					switch {
					// Searching other contexts with job names raises an error, which in
					// this case we want to ignore.
					case strings.Contains(e, "Invalid UUID: encoding/hex"):
					case strings.Contains(e, "UUID have 36 characters"):
					case strings.Contains(e, "must be even length"):
					case strings.Contains(e, "UUID should have maximum of 4"):
					default:
						return err
					}
				} else {
					iters[ctx] = iter
				}
			}

			// Return matches for the given prefix
			for k, v := range iters {
				res, isTrunc := s.getMatches(v, args.Prefix)
				reply.Matches[k] = res
				reply.Truncations[k] = isTrunc
			}

			// Set the index for the context. If the context has been specified, it
			// will be used as the index of the response. Otherwise, the
			// maximum index from all resources will be used.
			for _, ctx := range contexts {
				index, err := state.Index(contextToIndex(ctx))
				if err != nil {
					return err
				}
				if index > reply.Index {
					reply.Index = index
				}
			}

			s.srv.setQueryMeta(&reply.QueryMeta)
			return nil
		}}
	return s.srv.blockingRPC(&opts)
}
383289
func (i *indexImpl) Search(req *SearchRequest) (sr *SearchResult, err error) {
	return i.SearchInContext(context.Background(), req)
}
684739
func (t *Transport) rewriteResponse(req *http.Request, resp *http.Response) (*http.Response, error) {
	origBody := resp.Body
	defer origBody.Close()

	newContent := &bytes.Buffer{}
	var reader io.Reader = origBody
	var writer io.Writer = newContent
	encoding := resp.Header.Get("Content-Encoding")
	switch encoding {
	case "gzip":
		var err error
		reader, err = gzip.NewReader(reader)
		if err != nil {
			return nil, fmt.Errorf("errorf making gzip reader: %v", err)
		}
		gzw := gzip.NewWriter(writer)
		defer gzw.Close()
		writer = gzw
	// TODO: support flate, other encodings.
	case "":
		// This is fine
	default:
		// Some encoding we don't understand-- don't try to parse this
		glog.Errorf("Proxy encountered encoding %v for text/html; can't understand this so not fixing links.", encoding)
		return resp, nil
	}

	urlRewriter := func(targetUrl string) string {
		return t.rewriteURL(targetUrl, req.URL)
	}
	err := rewriteHTML(reader, writer, urlRewriter)
	if err != nil {
		glog.Errorf("Failed to rewrite URLs: %v", err)
		return resp, err
	}

	resp.Body = ioutil.NopCloser(newContent)
	// Update header node with new content-length
	// TODO: Remove any hash/signature headers here?
	resp.Header.Del("Content-Length")
	resp.ContentLength = int64(newContent.Len())

	return resp, err
}
486502
func (q *Query) Respond(buf []byte) error {
	// Create response
	resp := q.createResponse(buf)

	// Encode response
	raw, err := encodeMessage(messageQueryResponseType, resp)
	if err != nil {
		return fmt.Errorf("failed to format response: %v", err)
	}

	if err := q.respondWithMessageAndResponse(raw, resp); err != nil {
		return fmt.Errorf("failed to respond to key query: %v", err)
	}

	return nil
}
338781
func (m *MultiSearchRequestBuilder) Search(interval tsdb.Interval) *SearchRequestBuilder {
	b := NewSearchRequestBuilder(m.version, interval)
	m.requestBuilders = append(m.requestBuilders, b)
	return b
}
1109002
func NewSearchRequest(
	BaseDN string,
	Scope, DerefAliases, SizeLimit, TimeLimit int,
	TypesOnly bool,
	Filter string,
	Attributes []string,
	Controls []Control,
) *SearchRequest {
	return &SearchRequest{
		BaseDN:       BaseDN,
		Scope:        Scope,
		DerefAliases: DerefAliases,
		SizeLimit:    SizeLimit,
		TimeLimit:    TimeLimit,
		TypesOnly:    TypesOnly,
		Filter:       Filter,
		Attributes:   Attributes,
		Controls:     Controls,
	}
}
674573
func (c *Client) Search(query string, all bool) ([]*Printer, error) {
	var mr multipartRequest
	mr.init()
	if query != "" {
		mr.WriteField("q", query)
	}
	if all {
		mr.WriteField("connection_status", "ALL")
	}
	var resp printersResponse
	err := jsonRPC(&c.auth, "POST", cloudprintURL+"/search", &mr, &resp)
	if err != nil {
		return nil, fmt.Errorf("Search: %v", err)
	}
	var list []*Printer
	for _, desc := range resp.Printers {
		list = append(list, desc.Printer())
	}
	return list, nil
}
384963
func (s *HTTPServer) SearchRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	if req.Method == "POST" || req.Method == "PUT" {
		return s.newSearchRequest(resp, req)
	}
	return nil, CodedError(405, ErrInvalidMethod)
}
1077614
func (client *Client) query(req *request, resp interface{}) error {
	err := client.prepare(req)
	if err != nil {
		return err
	}
	r, err := client.run(req, resp)
	if r != nil && r.Body != nil {
		r.Body.Close()
	}
	return err
}
1167386
func (parser *ExtensiveResultParser) ParseResponse(response *SolrResponse, sr *SolrResult) (err error) {
	if resp, ok := response.Response["response"].(map[string]interface{}); ok {
		ParseDocResponse(resp, sr.Results)
	} else {
		err = fmt.Errorf(`Extensive 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
}
1260513
func SendResponse(w http.ResponseWriter, result interface{}) error {
	response := NewSuccessResponse(result)
	w.Header().Set("Content-Type", "application/json")
	enc := json.NewEncoder(w)
	err := enc.Encode(response)
	return err
}
940493
func (o *PostLookupsIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {

	case 200:
		result := NewPostLookupsIDOK()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil

	default:
		result := NewPostLookupsIDDefault(response.Code())
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result
	}
}
1285105
func (s *UserService) Search(query string, params *UserSearchParams) ([]User, *http.Response, error) {
	if params == nil {
		params = &UserSearchParams{}
	}
	params.Query = query
	users := new([]User)
	apiError := new(APIError)
	resp, err := s.sling.New().Get("search.json").QueryStruct(params).Receive(users, apiError)
	return *users, resp, relevantError(err, *apiError)
}