...

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

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

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

View as plain text