...

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

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

     1  package localsearch
     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  // LocalClient is the the Local Search client lets you send a search query to Bing and get back search results that
    18  // include local businesses such as restaurants, hotels, retail stores, or other local businesses. The query can
    19  // specify the name of the local business or it can ask for a list (for example, restaurants near me).
    20  type LocalClient struct {
    21  	BaseClient
    22  }
    23  
    24  // NewLocalClient creates an instance of the LocalClient client.
    25  func NewLocalClient() LocalClient {
    26  	return NewLocalClientWithBaseURI(DefaultBaseURI)
    27  }
    28  
    29  // NewLocalClientWithBaseURI creates an instance of the LocalClient client using a custom endpoint.  Use this when
    30  // interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
    31  func NewLocalClientWithBaseURI(baseURI string) LocalClient {
    32  	return LocalClient{NewWithBaseURI(baseURI)}
    33  }
    34  
    35  // Search sends the search request.
    36  // Parameters:
    37  // query - the user's search term.
    38  // acceptLanguage - a comma-delimited list of one or more languages to use for user interface strings. The list
    39  // is in decreasing order of preference. For additional information, including expected format, see
    40  // [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the setLang query
    41  // parameter are mutually exclusive; do not specify both. If you set this header, you must also specify the cc
    42  // query parameter. Bing will use the first supported language it finds from the list, and combine that
    43  // language with the cc parameter value to determine the market to return results for. If the list does not
    44  // include a supported language, Bing will find the closest language and market that supports the request, and
    45  // may use an aggregated or default market for the results instead of a specified one. You should use this
    46  // header and the cc query parameter only if you specify multiple languages; otherwise, you should use the mkt
    47  // and setLang query parameters. A user interface string is a string that's used as a label in a user
    48  // interface. There are very few user interface strings in the JSON response objects. Any links in the response
    49  // objects to Bing.com properties will apply the specified language.
    50  // pragma - by default, Bing returns cached content, if available. To prevent Bing from returning cached
    51  // content, set the Pragma header to no-cache (for example, Pragma: no-cache).
    52  // userAgent - the user agent originating the request. Bing uses the user agent to provide mobile users with an
    53  // optimized experience. Although optional, you are strongly encouraged to always specify this header. The
    54  // user-agent should be the same string that any commonly used browser would send. For information about user
    55  // agents, see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
    56  // clientID - bing uses this header to provide users with consistent behavior across Bing API calls. Bing often
    57  // flights new features and improvements, and it uses the client ID as a key for assigning traffic on different
    58  // flights. If you do not use the same client ID for a user across multiple requests, then Bing may assign the
    59  // user to multiple conflicting flights. Being assigned to multiple conflicting flights can lead to an
    60  // inconsistent user experience. For example, if the second request has a different flight assignment than the
    61  // first, the experience may be unexpected. Also, Bing can use the client ID to tailor web results to that
    62  // client ID’s search history, providing a richer experience for the user. Bing also uses this header to help
    63  // improve result rankings by analyzing the activity generated by a client ID. The relevance improvements help
    64  // with better quality of results delivered by Bing APIs and in turn enables higher click-through rates for the
    65  // API consumer. IMPORTANT: Although optional, you should consider this header required. Persisting the client
    66  // ID across multiple requests for the same end user and device combination enables 1) the API consumer to
    67  // receive a consistent user experience, and 2) higher click-through rates via better quality of results from
    68  // the Bing APIs. Each user that uses your application on the device must have a unique, Bing generated client
    69  // ID. If you do not include this header in the request, Bing generates an ID and returns it in the
    70  // X-MSEdge-ClientID response header. The only time that you should NOT include this header in a request is the
    71  // first time the user uses your app on that device. Use the client ID for each Bing API request that your app
    72  // makes for this user on the device. Persist the client ID. To persist the ID in a browser app, use a
    73  // persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session cookie. For other
    74  // apps such as mobile apps, use the device's persistent storage to persist the ID. The next time the user uses
    75  // your app on that device, get the client ID that you persisted. Bing responses may or may not include this
    76  // header. If the response includes this header, capture the client ID and use it for all subsequent Bing
    77  // requests for the user on that device. If you include the X-MSEdge-ClientID, you must not include cookies in
    78  // the request.
    79  // clientIP - the IPv4 or IPv6 address of the client device. The IP address is used to discover the user's
    80  // location. Bing uses the location information to determine safe search behavior. Although optional, you are
    81  // encouraged to always specify this header and the X-Search-Location header. Do not obfuscate the address (for
    82  // example, by changing the last octet to 0). Obfuscating the address results in the location not being
    83  // anywhere near the device's actual location, which may result in Bing serving erroneous results.
    84  // location - a semicolon-delimited list of key/value pairs that describe the client's geographical location.
    85  // Bing uses the location information to determine safe search behavior and to return relevant local content.
    86  // Specify the key/value pair as <key>:<value>. The following are the keys that you use to specify the user's
    87  // location. lat (required): The latitude of the client's location, in degrees. The latitude must be greater
    88  // than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and
    89  // positive values indicate northern latitudes. long (required): The longitude of the client's location, in
    90  // degrees. The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative
    91  // values indicate western longitudes and positive values indicate eastern longitudes. re (required): The
    92  // radius, in meters, which specifies the horizontal accuracy of the coordinates. Pass the value returned by
    93  // the device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation,
    94  // and 18,000m for reverse IP lookup. ts (optional): The UTC UNIX timestamp of when the client was at the
    95  // location. (The UNIX timestamp is the number of seconds since January 1, 1970.) head (optional): The client's
    96  // relative heading or direction of travel. Specify the direction of travel as degrees from 0 through 360,
    97  // counting clockwise relative to true north. Specify this key only if the sp key is nonzero. sp (optional):
    98  // The horizontal velocity (speed), in meters per second, that the client device is traveling. alt (optional):
    99  // The altitude of the client device, in meters. are (optional): The radius, in meters, that specifies the
   100  // vertical accuracy of the coordinates. Specify this key only if you specify the alt key. Although many of the
   101  // keys are optional, the more information that you provide, the more accurate the location results are.
   102  // Although optional, you are encouraged to always specify the user's geographical location. Providing the
   103  // location is especially important if the client's IP address does not accurately reflect the user's physical
   104  // location (for example, if the client uses VPN). For optimal results, you should include this header and the
   105  // X-MSEdge-ClientIP header, but at a minimum, you should include this header.
   106  // countryCode - a 2-character country code of the country where the results come from. This API supports only
   107  // the United States market. If you specify this query parameter, it must be set to us. If you set this
   108  // parameter, you must also specify the Accept-Language header. Bing uses the first supported language it finds
   109  // from the languages list, and combine that language with the country code that you specify to determine the
   110  // market to return results for. If the languages list does not include a supported language, Bing finds the
   111  // closest language and market that supports the request, or it may use an aggregated or default market for the
   112  // results instead of a specified one. You should use this query parameter and the Accept-Language query
   113  // parameter only if you specify multiple languages; otherwise, you should use the mkt and setLang query
   114  // parameters. This parameter and the mkt query parameter are mutually exclusive—do not specify both.
   115  // market - the market where the results come from. You are strongly encouraged to always specify the market,
   116  // if known. Specifying the market helps Bing route the request and return an appropriate and optimal response.
   117  // This parameter and the cc query parameter are mutually exclusive—do not specify both.
   118  // localCategories - comma-delimited list of business categories to search for. Supported categories can be
   119  // high-level such as EatDrink, Shop, SeeDo.
   120  // localCircularView - preferred location to search around, expressed as Latitude, longitude and radius in
   121  // meters. For example 47.61503,-122.1719,5000. Note that circular view should only be used to indicate a
   122  // search around a point on the map, not as an approximation for a view port of a map rectangle.
   123  // localMapView - preferred bounding box for results, specified in NW_latitude, NW_Longitude, SE_Latitude,
   124  // SE_Longitude format. For example 47.64,-122.13,47.63,-122.12. These values are lat, long pairs for the
   125  // Northwest corner and the Southeast corner of a rectangle.
   126  // count - preferred number of results to return. If not specified, then Bing returns 1-20 of the most relevant
   127  // results.
   128  // first - first result to return. zero-based. default is 0.
   129  // responseFormat - the media type to use for the response. The following are the possible case-insensitive
   130  // values: JSON, JSONLD. The default is JSON. If you specify JSONLD, the response body includes JSON-LD objects
   131  // that contain the search results.
   132  // safeSearch - a filter used to filter adult content. Off: Return webpages with adult text, images, or videos.
   133  // Moderate: Return webpages with adult text, but not adult images or videos. Strict: Do not return webpages
   134  // with adult text, images, or videos. The default is Moderate. If the request comes from a market that Bing's
   135  // adult policy requires that safeSearch is set to Strict, Bing ignores the safeSearch value and uses Strict.
   136  // If you use the site: query operator, there is the chance that the response may contain adult content
   137  // regardless of what the safeSearch query parameter is set to. Use site: only if you are aware of the content
   138  // on the site and your scenario supports the possibility of adult content.
   139  // setLang - the language to use for user interface strings. Specify the language using the ISO 639-1 2-letter
   140  // language code. For example, the language code for English is EN. The default is EN (English). Although
   141  // optional, you should always specify the language. Typically, you set setLang to the same language specified
   142  // by mkt unless the user wants the user interface strings displayed in a different language. This parameter
   143  // and the Accept-Language header are mutually exclusive; do not specify both. A user interface string is a
   144  // string that's used as a label in a user interface. There are few user interface strings in the JSON response
   145  // objects. Also, any links to Bing.com properties in the response objects apply the specified language.
   146  func (client LocalClient) Search(ctx context.Context, query string, acceptLanguage string, pragma string, userAgent string, clientID string, clientIP string, location string, countryCode string, market string, localCategories string, localCircularView string, localMapView string, count string, first string, responseFormat []ResponseFormat, safeSearch SafeSearch, setLang string) (result SearchResponse, err error) {
   147  	if tracing.IsEnabled() {
   148  		ctx = tracing.StartSpan(ctx, fqdn+"/LocalClient.Search")
   149  		defer func() {
   150  			sc := -1
   151  			if result.Response.Response != nil {
   152  				sc = result.Response.Response.StatusCode
   153  			}
   154  			tracing.EndSpan(ctx, sc, err)
   155  		}()
   156  	}
   157  	req, err := client.SearchPreparer(ctx, query, acceptLanguage, pragma, userAgent, clientID, clientIP, location, countryCode, market, localCategories, localCircularView, localMapView, count, first, responseFormat, safeSearch, setLang)
   158  	if err != nil {
   159  		err = autorest.NewErrorWithError(err, "localsearch.LocalClient", "Search", nil, "Failure preparing request")
   160  		return
   161  	}
   162  
   163  	resp, err := client.SearchSender(req)
   164  	if err != nil {
   165  		result.Response = autorest.Response{Response: resp}
   166  		err = autorest.NewErrorWithError(err, "localsearch.LocalClient", "Search", resp, "Failure sending request")
   167  		return
   168  	}
   169  
   170  	result, err = client.SearchResponder(resp)
   171  	if err != nil {
   172  		err = autorest.NewErrorWithError(err, "localsearch.LocalClient", "Search", resp, "Failure responding to request")
   173  		return
   174  	}
   175  
   176  	return
   177  }
   178  
   179  // SearchPreparer prepares the Search request.
   180  func (client LocalClient) SearchPreparer(ctx context.Context, query string, acceptLanguage string, pragma string, userAgent string, clientID string, clientIP string, location string, countryCode string, market string, localCategories string, localCircularView string, localMapView string, count string, first string, responseFormat []ResponseFormat, safeSearch SafeSearch, setLang string) (*http.Request, error) {
   181  	queryParameters := map[string]interface{}{
   182  		"q": autorest.Encode("query", query),
   183  	}
   184  	if len(countryCode) > 0 {
   185  		queryParameters["cc"] = autorest.Encode("query", countryCode)
   186  	}
   187  	if len(market) > 0 {
   188  		queryParameters["mkt"] = autorest.Encode("query", market)
   189  	} else {
   190  		queryParameters["mkt"] = autorest.Encode("query", "en-us")
   191  	}
   192  	if len(localCategories) > 0 {
   193  		queryParameters["localcategories"] = autorest.Encode("query", localCategories)
   194  	}
   195  	if len(localCircularView) > 0 {
   196  		queryParameters["localcircularview"] = autorest.Encode("query", localCircularView)
   197  	}
   198  	if len(localMapView) > 0 {
   199  		queryParameters["localmapview"] = autorest.Encode("query", localMapView)
   200  	}
   201  	if len(count) > 0 {
   202  		queryParameters["count"] = autorest.Encode("query", count)
   203  	}
   204  	if len(first) > 0 {
   205  		queryParameters["first"] = autorest.Encode("query", first)
   206  	}
   207  	if responseFormat != nil && len(responseFormat) > 0 {
   208  		queryParameters["ResponseFormat"] = autorest.Encode("query", responseFormat, ",")
   209  	}
   210  	if len(string(safeSearch)) > 0 {
   211  		queryParameters["SafeSearch"] = autorest.Encode("query", safeSearch)
   212  	}
   213  	if len(setLang) > 0 {
   214  		queryParameters["SetLang"] = autorest.Encode("query", setLang)
   215  	}
   216  
   217  	preparer := autorest.CreatePreparer(
   218  		autorest.AsGet(),
   219  		autorest.WithBaseURL(client.BaseURI),
   220  		autorest.WithPath("/v7.0/localbusinesses/search"),
   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  // SearchSender sends the Search request. The method will close the
   251  // http.Response Body if it receives an error.
   252  func (client LocalClient) SearchSender(req *http.Request) (*http.Response, error) {
   253  	return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
   254  }
   255  
   256  // SearchResponder handles the response to the Search request. The method always
   257  // closes the http.Response Body.
   258  func (client LocalClient) SearchResponder(resp *http.Response) (result SearchResponse, 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