github.com/ssdev-go/moby@v17.12.1-ce-rc2+incompatible/client/image_search.go (about)

     1  package client
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  	"net/url"
     8  
     9  	"github.com/docker/docker/api/types"
    10  	"github.com/docker/docker/api/types/filters"
    11  	"github.com/docker/docker/api/types/registry"
    12  	"golang.org/x/net/context"
    13  )
    14  
    15  // ImageSearch makes the docker host to search by a term in a remote registry.
    16  // The list of results is not sorted in any fashion.
    17  func (cli *Client) ImageSearch(ctx context.Context, term string, options types.ImageSearchOptions) ([]registry.SearchResult, error) {
    18  	var results []registry.SearchResult
    19  	query := url.Values{}
    20  	query.Set("term", term)
    21  	query.Set("limit", fmt.Sprintf("%d", options.Limit))
    22  
    23  	if options.Filters.Len() > 0 {
    24  		filterJSON, err := filters.ToJSON(options.Filters)
    25  		if err != nil {
    26  			return results, err
    27  		}
    28  		query.Set("filters", filterJSON)
    29  	}
    30  
    31  	resp, err := cli.tryImageSearch(ctx, query, options.RegistryAuth)
    32  	if resp.statusCode == http.StatusUnauthorized && options.PrivilegeFunc != nil {
    33  		newAuthHeader, privilegeErr := options.PrivilegeFunc()
    34  		if privilegeErr != nil {
    35  			return results, privilegeErr
    36  		}
    37  		resp, err = cli.tryImageSearch(ctx, query, newAuthHeader)
    38  	}
    39  	if err != nil {
    40  		return results, err
    41  	}
    42  
    43  	err = json.NewDecoder(resp.body).Decode(&results)
    44  	ensureReaderClosed(resp)
    45  	return results, err
    46  }
    47  
    48  func (cli *Client) tryImageSearch(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) {
    49  	headers := map[string][]string{"X-Registry-Auth": {registryAuth}}
    50  	return cli.get(ctx, "/images/search", query, headers)
    51  }