...

Source file src/github.com/Azure/azure-sdk-for-go/services/cognitiveservices/v1.0/autosuggest/client.go

Documentation: github.com/Azure/azure-sdk-for-go/services/cognitiveservices/v1.0/autosuggest

     1  // Package autosuggest implements the Azure ARM Autosuggest service API version 1.0.
     2  //
     3  // Autosuggest supplies search terms derived from a root text sent to the service.  The terms Autosuggest supplies are
     4  // related to the root text based on similarity and their frequency or ratings of usefulness in other searches. For
     5  // examples that show how to use Autosuggest, see [Search using
     6  // AutoSuggest](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference).
     7  package autosuggest
     8  
     9  // Copyright (c) Microsoft Corporation. All rights reserved.
    10  // Licensed under the MIT License. See License.txt in the project root for license information.
    11  //
    12  // Code generated by Microsoft (R) AutoRest Code Generator.
    13  // Changes may cause incorrect behavior and will be lost if the code is regenerated.
    14  
    15  import (
    16  	"context"
    17  	"github.com/Azure/go-autorest/autorest"
    18  	"github.com/Azure/go-autorest/autorest/azure"
    19  	"github.com/Azure/go-autorest/tracing"
    20  	"net/http"
    21  )
    22  
    23  const (
    24  	// DefaultEndpoint is the default value for endpoint
    25  	DefaultEndpoint = "https://api.cognitive.microsoft.com"
    26  )
    27  
    28  // BaseClient is the base client for Autosuggest.
    29  type BaseClient struct {
    30  	autorest.Client
    31  	Endpoint string
    32  }
    33  
    34  // New creates an instance of the BaseClient client.
    35  func New() BaseClient {
    36  	return NewWithoutDefaults(DefaultEndpoint)
    37  }
    38  
    39  // NewWithoutDefaults creates an instance of the BaseClient client.
    40  func NewWithoutDefaults(endpoint string) BaseClient {
    41  	return BaseClient{
    42  		Client:   autorest.NewClientWithUserAgent(UserAgent()),
    43  		Endpoint: endpoint,
    44  	}
    45  }
    46  
    47  // AutoSuggest sends the auto suggest request.
    48  // Parameters:
    49  // query - the user's search term.
    50  // acceptLanguage - a comma-delimited list of one or more languages to use for user interface strings. The list
    51  // is in decreasing order of preference. For additional information, including expected format, see
    52  // [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the setLang query
    53  // parameter are mutually exclusive; do not specify both. If you set this header, you must also specify the
    54  // [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference#cc) query
    55  // parameter. To determine the market to return results for, Bing uses the first supported language it finds
    56  // from the list and combines it with the cc parameter value. If the list does not include a supported
    57  // language, Bing finds the closest language and market that supports the request or it uses an aggregated or
    58  // default market for the results. To determine the market that Bing used, see the BingAPIs-Market header. Use
    59  // this header and the cc query parameter only if you specify multiple languages. Otherwise, use the
    60  // [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference#mkt) and
    61  // [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference#setlang)
    62  // query parameters. A user interface string is a string that's used as a label in a user interface. There are
    63  // few user interface strings in the JSON response objects. Any links to Bing.com properties in the response
    64  // objects apply the specified language.
    65  // pragma - by default, Bing returns cached content, if available. To prevent Bing from returning cached
    66  // content, set the Pragma header to no-cache (for example, Pragma: no-cache).
    67  // userAgent - the user agent originating the request. Bing uses the user agent to provide mobile users with an
    68  // optimized experience. Although optional, you are encouraged to always specify this header. The user-agent
    69  // should be the same string that any commonly used browser sends. For information about user agents, see [RFC
    70  // 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The following are examples of user-agent
    71  // strings. Windows Phone: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0;
    72  // ARM; Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build /
    73  // GINGERBREAD) AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla /
    74  // 5.0 (iPhone; CPU iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142
    75  // iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3; WOW64; Trident / 7.0; Touch;
    76  // rv:11.0) like Gecko. iPad: Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML,
    77  // like Gecko) Version / 7.0 Mobile / 11A465 Safari / 9537.53
    78  // clientID - bing uses this header to provide users with consistent behavior across Bing API calls. Bing often
    79  // flights new features and improvements, and it uses the client ID as a key for assigning traffic on different
    80  // flights. If you do not use the same client ID for a user across multiple requests, then Bing may assign the
    81  // user to multiple conflicting flights. Being assigned to multiple conflicting flights can lead to an
    82  // inconsistent user experience. For example, if the second request has a different flight assignment than the
    83  // first, the experience may be unexpected. Also, Bing can use the client ID to tailor web results to that
    84  // client ID’s search history, providing a richer experience for the user. Bing also uses this header to help
    85  // improve result rankings by analyzing the activity generated by a client ID. The relevance improvements help
    86  // with better quality of results delivered by Bing APIs and in turn enables higher click-through rates for the
    87  // API consumer. IMPORTANT: Although optional, you should consider this header required. Persisting the client
    88  // ID across multiple requests for the same end user and device combination enables 1) the API consumer to
    89  // receive a consistent user experience, and 2) higher click-through rates via better quality of results from
    90  // the Bing APIs. Each user that uses your application on the device must have a unique, Bing generated client
    91  // ID. If you do not include this header in the request, Bing generates an ID and returns it in the
    92  // X-MSEdge-ClientID response header. The only time that you should NOT include this header in a request is the
    93  // first time the user uses your app on that device. Use the client ID for each Bing API request that your app
    94  // makes for this user on the device. Persist the client ID. To persist the ID in a browser app, use a
    95  // persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session cookie. For other
    96  // apps such as mobile apps, use the device's persistent storage to persist the ID. The next time the user uses
    97  // your app on that device, get the client ID that you persisted. Bing responses may or may not include this
    98  // header. If the response includes this header, capture the client ID and use it for all subsequent Bing
    99  // requests for the user on that device. If you include the X-MSEdge-ClientID, you must not include cookies in
   100  // the request.
   101  // clientIP - the IPv4 or IPv6 address of the client device. The IP address is used to discover the user's
   102  // location. Bing uses the location information to determine safe search behavior. Although optional, you are
   103  // encouraged to always specify this header and the X-Search-Location header. Do not obfuscate the address (for
   104  // example, by changing the last octet to 0). Obfuscating the address results in the location not being
   105  // anywhere near the device's actual location, which may result in Bing serving erroneous results.
   106  // location - a semicolon-delimited list of key/value pairs that describe the client's geographical location.
   107  // Bing uses the location information to determine safe search behavior and to return relevant local content.
   108  // Specify the key/value pair as <key>:<value>. The following are the keys that you use to specify the user's
   109  // location. lat (required): The latitude of the client's location, in degrees. The latitude must be greater
   110  // than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and
   111  // positive values indicate northern latitudes. long (required): The longitude of the client's location, in
   112  // degrees. The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative
   113  // values indicate western longitudes and positive values indicate eastern longitudes. re (required): The
   114  // radius, in meters, which specifies the horizontal accuracy of the coordinates. Pass the value returned by
   115  // the device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation,
   116  // and 18,000m for reverse IP lookup. ts (optional): The UTC UNIX timestamp of when the client was at the
   117  // location. (The UNIX timestamp is the number of seconds since January 1, 1970.) head (optional): The client's
   118  // relative heading or direction of travel. Specify the direction of travel as degrees from 0 through 360,
   119  // counting clockwise relative to true north. Specify this key only if the sp key is nonzero. sp (optional):
   120  // The horizontal velocity (speed), in meters per second, that the client device is traveling. alt (optional):
   121  // The altitude of the client device, in meters. are (optional): The radius, in meters, that specifies the
   122  // vertical accuracy of the coordinates. Specify this key only if you specify the alt key. Although many of the
   123  // keys are optional, the more information that you provide, the more accurate the location results are.
   124  // Although optional, you are encouraged to always specify the user's geographical location. Providing the
   125  // location is especially important if the client's IP address does not accurately reflect the user's physical
   126  // location (for example, if the client uses VPN). For optimal results, you should include this header and the
   127  // X-MSEdge-ClientIP header, but at a minimum, you should include this header.
   128  // countryCode - a 2-character country code of the country where the results come from. This API supports only
   129  // the United States market. If you specify this query parameter, it must be set to us. If you set this
   130  // parameter, you must also specify the Accept-Language header. Bing uses the first supported language it finds
   131  // from the languages list, and combine that language with the country code that you specify to determine the
   132  // market to return results for. If the languages list does not include a supported language, Bing finds the
   133  // closest language and market that supports the request, or it may use an aggregated or default market for the
   134  // results instead of a specified one. You should use this query parameter and the Accept-Language query
   135  // parameter only if you specify multiple languages; otherwise, you should use the mkt and setLang query
   136  // parameters. This parameter and the mkt query parameter are mutually exclusive—do not specify both.
   137  // market - the market where the results come from. You are strongly encouraged to always specify the market,
   138  // if known. Specifying the market helps Bing route the request and return an appropriate and optimal response.
   139  // This parameter and the cc query parameter are mutually exclusive—do not specify both.
   140  // safeSearch - filter suggestions for adult content. The following are the possible filter values. Off: Return
   141  // suggestions with adult text, images, or videos. Moderate: Return suggestion with adult text but not adult
   142  // images or videos. Strict: Do not return news articles with adult text, images, or videos. If the request
   143  // comes from a market that Bing's adult policy requires that safeSearch is set to Strict, Bing ignores the
   144  // safeSearch value and uses Strict. If you use the site: query operator, there is the chance that the response
   145  // may contain adult content regardless of what the safeSearch query parameter is set to. Use site: only if you
   146  // are aware of the content on the site and your scenario supports the possibility of adult content.
   147  // setLang - the language to use for user interface strings. Specify the language using the ISO 639-1 2-letter
   148  // language code. For example, the language code for English is EN. The default is EN (English). Although
   149  // optional, you should always specify the language. Typically, you set setLang to the same language specified
   150  // by mkt unless the user wants the user interface strings displayed in a different language. This parameter
   151  // and the Accept-Language header are mutually exclusive; do not specify both. A user interface string is a
   152  // string that's used as a label in a user interface. There are few user interface strings in the JSON response
   153  // objects. Also, any links to Bing.com properties in the response objects apply the specified language.
   154  // responseFormat - the media type to use for the response. The following are the possible case-insensitive
   155  // values: JSON, JSONLD. The default is JSON. If you specify JSONLD, the response body includes JSON-LD objects
   156  // that contain the search results.
   157  func (client BaseClient) AutoSuggest(ctx context.Context, query string, acceptLanguage string, pragma string, userAgent string, clientID string, clientIP string, location string, countryCode string, market string, safeSearch SafeSearch, setLang string, responseFormat []ResponseFormat) (result Suggestions, err error) {
   158  	if tracing.IsEnabled() {
   159  		ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.AutoSuggest")
   160  		defer func() {
   161  			sc := -1
   162  			if result.Response.Response != nil {
   163  				sc = result.Response.Response.StatusCode
   164  			}
   165  			tracing.EndSpan(ctx, sc, err)
   166  		}()
   167  	}
   168  	req, err := client.AutoSuggestPreparer(ctx, query, acceptLanguage, pragma, userAgent, clientID, clientIP, location, countryCode, market, safeSearch, setLang, responseFormat)
   169  	if err != nil {
   170  		err = autorest.NewErrorWithError(err, "autosuggest.BaseClient", "AutoSuggest", nil, "Failure preparing request")
   171  		return
   172  	}
   173  
   174  	resp, err := client.AutoSuggestSender(req)
   175  	if err != nil {
   176  		result.Response = autorest.Response{Response: resp}
   177  		err = autorest.NewErrorWithError(err, "autosuggest.BaseClient", "AutoSuggest", resp, "Failure sending request")
   178  		return
   179  	}
   180  
   181  	result, err = client.AutoSuggestResponder(resp)
   182  	if err != nil {
   183  		err = autorest.NewErrorWithError(err, "autosuggest.BaseClient", "AutoSuggest", resp, "Failure responding to request")
   184  		return
   185  	}
   186  
   187  	return
   188  }
   189  
   190  // AutoSuggestPreparer prepares the AutoSuggest request.
   191  func (client BaseClient) AutoSuggestPreparer(ctx context.Context, query string, acceptLanguage string, pragma string, userAgent string, clientID string, clientIP string, location string, countryCode string, market string, safeSearch SafeSearch, setLang string, responseFormat []ResponseFormat) (*http.Request, error) {
   192  	urlParameters := map[string]interface{}{
   193  		"Endpoint": client.Endpoint,
   194  	}
   195  
   196  	queryParameters := map[string]interface{}{
   197  		"q": autorest.Encode("query", query),
   198  	}
   199  	if len(countryCode) > 0 {
   200  		queryParameters["cc"] = autorest.Encode("query", countryCode)
   201  	}
   202  	if len(market) > 0 {
   203  		queryParameters["mkt"] = autorest.Encode("query", market)
   204  	} else {
   205  		queryParameters["mkt"] = autorest.Encode("query", "en-us")
   206  	}
   207  	if len(string(safeSearch)) > 0 {
   208  		queryParameters["safeSearch"] = autorest.Encode("query", safeSearch)
   209  	}
   210  	if len(setLang) > 0 {
   211  		queryParameters["setLang"] = autorest.Encode("query", setLang)
   212  	}
   213  	if responseFormat != nil && len(responseFormat) > 0 {
   214  		queryParameters["ResponseFormat"] = autorest.Encode("query", responseFormat, ",")
   215  	}
   216  
   217  	preparer := autorest.CreatePreparer(
   218  		autorest.AsGet(),
   219  		autorest.WithCustomBaseURL("{Endpoint}/bing/v7.0", urlParameters),
   220  		autorest.WithPath("/Suggestions"),
   221  		autorest.WithQueryParameters(queryParameters),
   222  		autorest.WithHeader("X-BingApis-SDK", "true"))
   223  	if len(acceptLanguage) > 0 {
   224  		preparer = autorest.DecoratePreparer(preparer,
   225  			autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
   226  	}
   227  	if len(pragma) > 0 {
   228  		preparer = autorest.DecoratePreparer(preparer,
   229  			autorest.WithHeader("Pragma", autorest.String(pragma)))
   230  	}
   231  	if len(userAgent) > 0 {
   232  		preparer = autorest.DecoratePreparer(preparer,
   233  			autorest.WithHeader("User-Agent", autorest.String(userAgent)))
   234  	}
   235  	if len(clientID) > 0 {
   236  		preparer = autorest.DecoratePreparer(preparer,
   237  			autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
   238  	}
   239  	if len(clientIP) > 0 {
   240  		preparer = autorest.DecoratePreparer(preparer,
   241  			autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
   242  	}
   243  	if len(location) > 0 {
   244  		preparer = autorest.DecoratePreparer(preparer,
   245  			autorest.WithHeader("X-Search-Location", autorest.String(location)))
   246  	}
   247  	return preparer.Prepare((&http.Request{}).WithContext(ctx))
   248  }
   249  
   250  // AutoSuggestSender sends the AutoSuggest request. The method will close the
   251  // http.Response Body if it receives an error.
   252  func (client BaseClient) AutoSuggestSender(req *http.Request) (*http.Response, error) {
   253  	return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
   254  }
   255  
   256  // AutoSuggestResponder handles the response to the AutoSuggest request. The method always
   257  // closes the http.Response Body.
   258  func (client BaseClient) AutoSuggestResponder(resp *http.Response) (result Suggestions, err error) {
   259  	err = autorest.Respond(
   260  		resp,
   261  		azure.WithErrorUnlessStatusCode(http.StatusOK),
   262  		autorest.ByUnmarshallingJSON(&result),
   263  		autorest.ByClosing())
   264  	result.Response = autorest.Response{Response: resp}
   265  	return
   266  }
   267  

View as plain text