1package websearch 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 9import ( 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// WebClient is the the Web Search API lets you send a search query to Bing and get back search results that include 18// links to webpages, images, and more. 19type WebClient struct { 20 BaseClient 21} 22 23// NewWebClient creates an instance of the WebClient client. 24func NewWebClient() WebClient { 25 return WebClient{New()} 26} 27 28// Search sends the search request. 29// Parameters: 30// query - the user's search query term. The term may not be empty. The term may contain Bing Advanced 31// Operators. For example, to limit results to a specific domain, use the site: operator. 32// acceptLanguage - a comma-delimited list of one or more languages to use for user interface strings. The list 33// is in decreasing order of preference. For additional information, including expected format, see 34// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the setLang query 35// parameter are mutually exclusive; do not specify both. If you set this header, you must also specify the cc 36// query parameter. Bing will use the first supported language it finds from the list, and combine that 37// language with the cc parameter value to determine the market to return results for. If the list does not 38// include a supported language, Bing will find the closest language and market that supports the request, and 39// may use an aggregated or default market for the results instead of a specified one. You should use this 40// header and the cc query parameter only if you specify multiple languages; otherwise, you should use the mkt 41// and setLang query parameters. A user interface string is a string that's used as a label in a user 42// interface. There are very few user interface strings in the JSON response objects. Any links in the response 43// objects to Bing.com properties will apply the specified language. 44// pragma - by default, Bing returns cached content, if available. To prevent Bing from returning cached 45// content, set the Pragma header to no-cache (for example, Pragma: no-cache). 46// userAgent - the user agent originating the request. Bing uses the user agent to provide mobile users with an 47// optimized experience. Although optional, you are strongly encouraged to always specify this header. The 48// user-agent should be the same string that any commonly used browser would send. For information about user 49// agents, see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). 50// clientID - bing uses this header to provide users with consistent behavior across Bing API calls. Bing often 51// flights new features and improvements, and it uses the client ID as a key for assigning traffic on different 52// flights. If you do not use the same client ID for a user across multiple requests, then Bing may assign the 53// user to multiple conflicting flights. Being assigned to multiple conflicting flights can lead to an 54// inconsistent user experience. For example, if the second request has a different flight assignment than the 55// first, the experience may be unexpected. Also, Bing can use the client ID to tailor web results to that 56// client ID’s search history, providing a richer experience for the user. Bing also uses this header to help 57// improve result rankings by analyzing the activity generated by a client ID. The relevance improvements help 58// with better quality of results delivered by Bing APIs and in turn enables higher click-through rates for the 59// API consumer. IMPORTANT: Although optional, you should consider this header required. Persisting the client 60// ID across multiple requests for the same end user and device combination enables 1) the API consumer to 61// receive a consistent user experience, and 2) higher click-through rates via better quality of results from 62// the Bing APIs. Each user that uses your application on the device must have a unique, Bing generated client 63// ID. If you do not include this header in the request, Bing generates an ID and returns it in the 64// X-MSEdge-ClientID response header. The only time that you should NOT include this header in a request is the 65// first time the user uses your app on that device. Use the client ID for each Bing API request that your app 66// makes for this user on the device. Persist the client ID. To persist the ID in a browser app, use a 67// persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session cookie. For other 68// apps such as mobile apps, use the device's persistent storage to persist the ID. The next time the user uses 69// your app on that device, get the client ID that you persisted. Bing responses may or may not include this 70// header. If the response includes this header, capture the client ID and use it for all subsequent Bing 71// requests for the user on that device. If you include the X-MSEdge-ClientID, you must not include cookies in 72// the request. 73// clientIP - the IPv4 or IPv6 address of the client device. The IP address is used to discover the user's 74// location. Bing uses the location information to determine safe search behavior. Although optional, you are 75// encouraged to always specify this header and the X-Search-Location header. Do not obfuscate the address (for 76// example, by changing the last octet to 0). Obfuscating the address results in the location not being 77// anywhere near the device's actual location, which may result in Bing serving erroneous results. 78// location - a semicolon-delimited list of key/value pairs that describe the client's geographical location. 79// Bing uses the location information to determine safe search behavior and to return relevant local content. 80// Specify the key/value pair as <key>:<value>. The following are the keys that you use to specify the user's 81// location. lat (required): The latitude of the client's location, in degrees. The latitude must be greater 82// than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and 83// positive values indicate northern latitudes. long (required): The longitude of the client's location, in 84// degrees. The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative 85// values indicate western longitudes and positive values indicate eastern longitudes. re (required): The 86// radius, in meters, which specifies the horizontal accuracy of the coordinates. Pass the value returned by 87// the device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation, 88// and 18,000m for reverse IP lookup. ts (optional): The UTC UNIX timestamp of when the client was at the 89// location. (The UNIX timestamp is the number of seconds since January 1, 1970.) head (optional): The client's 90// relative heading or direction of travel. Specify the direction of travel as degrees from 0 through 360, 91// counting clockwise relative to true north. Specify this key only if the sp key is nonzero. sp (optional): 92// The horizontal velocity (speed), in meters per second, that the client device is traveling. alt (optional): 93// The altitude of the client device, in meters. are (optional): The radius, in meters, that specifies the 94// vertical accuracy of the coordinates. Specify this key only if you specify the alt key. Although many of the 95// keys are optional, the more information that you provide, the more accurate the location results are. 96// Although optional, you are encouraged to always specify the user's geographical location. Providing the 97// location is especially important if the client's IP address does not accurately reflect the user's physical 98// location (for example, if the client uses VPN). For optimal results, you should include this header and the 99// X-MSEdge-ClientIP header, but at a minimum, you should include this header. 100// answerCount - the number of answers that you want the response to include. The answers that Bing returns are 101// based on ranking. For example, if Bing returns webpages, images, videos, and relatedSearches for a request 102// and you set this parameter to two (2), the response includes webpages and images.If you included the 103// responseFilter query parameter in the same request and set it to webpages and news, the response would 104// include only webpages. 105// countryCode - a 2-character country code of the country where the results come from. This API supports only 106// the United States market. If you specify this query parameter, it must be set to us. If you set this 107// parameter, you must also specify the Accept-Language header. Bing uses the first supported language it finds 108// from the languages list, and combine that language with the country code that you specify to determine the 109// market to return results for. If the languages list does not include a supported language, Bing finds the 110// closest language and market that supports the request, or it may use an aggregated or default market for the 111// results instead of a specified one. You should use this query parameter and the Accept-Language query 112// parameter only if you specify multiple languages; otherwise, you should use the mkt and setLang query 113// parameters. This parameter and the mkt query parameter are mutually exclusive—do not specify both. 114// count - the number of search results to return in the response. The default is 10 and the maximum value is 115// 50. The actual number delivered may be less than requested.Use this parameter along with the offset 116// parameter to page results.For example, if your user interface displays 10 search results per page, set count 117// to 10 and offset to 0 to get the first page of results. For each subsequent page, increment offset by 10 118// (for example, 0, 10, 20). It is possible for multiple pages to include some overlap in results. 119// freshness - filter search results by the following age values: Day—Return webpages that Bing discovered 120// within the last 24 hours. Week—Return webpages that Bing discovered within the last 7 days. Month—Return 121// webpages that discovered within the last 30 days. This filter applies only to webpage results and not to the 122// other results such as news and images. 123// market - the market where the results come from. Typically, mkt is the country where the user is making the 124// request from. However, it could be a different country if the user is not located in a country where Bing 125// delivers results. The market must be in the form <language code>-<country code>. For example, en-US. The 126// string is case insensitive. If known, you are encouraged to always specify the market. Specifying the market 127// helps Bing route the request and return an appropriate and optimal response. If you specify a market that is 128// not listed in Market Codes, Bing uses a best fit market code based on an internal mapping that is subject to 129// change. This parameter and the cc query parameter are mutually exclusive—do not specify both. 130// offset - the zero-based offset that indicates the number of search results to skip before returning results. 131// The default is 0. The offset should be less than (totalEstimatedMatches - count). Use this parameter along 132// with the count parameter to page results. For example, if your user interface displays 10 search results per 133// page, set count to 10 and offset to 0 to get the first page of results. For each subsequent page, increment 134// offset by 10 (for example, 0, 10, 20). it is possible for multiple pages to include some overlap in results. 135// promote - a comma-delimited list of answers that you want the response to include regardless of their 136// ranking. For example, if you set answerCount) to two (2) so Bing returns the top two ranked answers, but you 137// also want the response to include news, you'd set promote to news. If the top ranked answers are webpages, 138// images, videos, and relatedSearches, the response includes webpages and images because news is not a ranked 139// answer. But if you set promote to video, Bing would promote the video answer into the response and return 140// webpages, images, and videos. The answers that you want to promote do not count against the answerCount 141// limit. For example, if the ranked answers are news, images, and videos, and you set answerCount to 1 and 142// promote to news, the response contains news and images. Or, if the ranked answers are videos, images, and 143// news, the response contains videos and news. Possible values are Computation, Images, News, RelatedSearches, 144// SpellSuggestions, TimeZone, Videos, Webpages. Use only if you specify answerCount. 145// responseFilter - a comma-delimited list of answers to include in the response. If you do not specify this 146// parameter, the response includes all search answers for which there's relevant data. Possible filter values 147// are Computation, Images, News, RelatedSearches, SpellSuggestions, TimeZone, Videos, Webpages. Although you 148// may use this filter to get a single answer, you should instead use the answer-specific endpoint in order to 149// get richer results. For example, to receive only images, send the request to one of the Image Search API 150// endpoints. The RelatedSearches and SpellSuggestions answers do not support a separate endpoint like the 151// Image Search API does (only the Web Search API returns them). To include answers that would otherwise be 152// excluded because of ranking, see the promote query parameter. 153// safeSearch - a filter used to filter adult content. Off: Return webpages with adult text, images, or videos. 154// Moderate: Return webpages with adult text, but not adult images or videos. Strict: Do not return webpages 155// with adult text, images, or videos. The default is Moderate. If the request comes from a market that Bing's 156// adult policy requires that safeSearch is set to Strict, Bing ignores the safeSearch value and uses Strict. 157// If you use the site: query operator, there is the chance that the response may contain adult content 158// regardless of what the safeSearch query parameter is set to. Use site: only if you are aware of the content 159// on the site and your scenario supports the possibility of adult content. 160// setLang - the language to use for user interface strings. Specify the language using the ISO 639-1 2-letter 161// language code. For example, the language code for English is EN. The default is EN (English). Although 162// optional, you should always specify the language. Typically, you set setLang to the same language specified 163// by mkt unless the user wants the user interface strings displayed in a different language. This parameter 164// and the Accept-Language header are mutually exclusive; do not specify both. A user interface string is a 165// string that's used as a label in a user interface. There are few user interface strings in the JSON response 166// objects. Also, any links to Bing.com properties in the response objects apply the specified language. 167// textDecorations - a Boolean value that determines whether display strings should contain decoration markers 168// such as hit highlighting characters. If true, the strings may include markers. The default is false. To 169// specify whether to use Unicode characters or HTML tags as the markers, see the textFormat query parameter. 170// textFormat - the type of markers to use for text decorations (see the textDecorations query parameter). 171// Possible values are Raw—Use Unicode characters to mark content that needs special formatting. The Unicode 172// characters are in the range E000 through E019. For example, Bing uses E000 and E001 to mark the beginning 173// and end of query terms for hit highlighting. HTML—Use HTML tags to mark content that needs special 174// formatting. For example, use <b> tags to highlight query terms in display strings. The default is Raw. For 175// display strings that contain escapable HTML characters such as <, >, and &, if textFormat is set to HTML, 176// Bing escapes the characters as appropriate (for example, < is escaped to <). 177func (client WebClient) Search(ctx context.Context, query string, acceptLanguage string, pragma string, userAgent string, clientID string, clientIP string, location string, answerCount *int32, countryCode string, count *int32, freshness Freshness, market string, offset *int32, promote []AnswerType, responseFilter []AnswerType, safeSearch SafeSearch, setLang string, textDecorations *bool, textFormat TextFormat) (result SearchResponse, err error) { 178 if tracing.IsEnabled() { 179 ctx = tracing.StartSpan(ctx, fqdn+"/WebClient.Search") 180 defer func() { 181 sc := -1 182 if result.Response.Response != nil { 183 sc = result.Response.Response.StatusCode 184 } 185 tracing.EndSpan(ctx, sc, err) 186 }() 187 } 188 req, err := client.SearchPreparer(ctx, query, acceptLanguage, pragma, userAgent, clientID, clientIP, location, answerCount, countryCode, count, freshness, market, offset, promote, responseFilter, safeSearch, setLang, textDecorations, textFormat) 189 if err != nil { 190 err = autorest.NewErrorWithError(err, "websearch.WebClient", "Search", nil, "Failure preparing request") 191 return 192 } 193 194 resp, err := client.SearchSender(req) 195 if err != nil { 196 result.Response = autorest.Response{Response: resp} 197 err = autorest.NewErrorWithError(err, "websearch.WebClient", "Search", resp, "Failure sending request") 198 return 199 } 200 201 result, err = client.SearchResponder(resp) 202 if err != nil { 203 err = autorest.NewErrorWithError(err, "websearch.WebClient", "Search", resp, "Failure responding to request") 204 return 205 } 206 207 return 208} 209 210// SearchPreparer prepares the Search request. 211func (client WebClient) SearchPreparer(ctx context.Context, query string, acceptLanguage string, pragma string, userAgent string, clientID string, clientIP string, location string, answerCount *int32, countryCode string, count *int32, freshness Freshness, market string, offset *int32, promote []AnswerType, responseFilter []AnswerType, safeSearch SafeSearch, setLang string, textDecorations *bool, textFormat TextFormat) (*http.Request, error) { 212 urlParameters := map[string]interface{}{ 213 "Endpoint": client.Endpoint, 214 } 215 216 queryParameters := map[string]interface{}{ 217 "q": autorest.Encode("query", query), 218 } 219 if answerCount != nil { 220 queryParameters["answerCount"] = autorest.Encode("query", *answerCount) 221 } 222 if len(countryCode) > 0 { 223 queryParameters["cc"] = autorest.Encode("query", countryCode) 224 } 225 if count != nil { 226 queryParameters["count"] = autorest.Encode("query", *count) 227 } 228 if len(string(freshness)) > 0 { 229 queryParameters["freshness"] = autorest.Encode("query", freshness) 230 } 231 if len(market) > 0 { 232 queryParameters["mkt"] = autorest.Encode("query", market) 233 } else { 234 queryParameters["mkt"] = autorest.Encode("query", "en-us") 235 } 236 if offset != nil { 237 queryParameters["offset"] = autorest.Encode("query", *offset) 238 } 239 if promote != nil && len(promote) > 0 { 240 queryParameters["promote"] = autorest.Encode("query", promote, ",") 241 } 242 if responseFilter != nil && len(responseFilter) > 0 { 243 queryParameters["responseFilter"] = autorest.Encode("query", responseFilter, ",") 244 } 245 if len(string(safeSearch)) > 0 { 246 queryParameters["safeSearch"] = autorest.Encode("query", safeSearch) 247 } 248 if len(setLang) > 0 { 249 queryParameters["setLang"] = autorest.Encode("query", setLang) 250 } 251 if textDecorations != nil { 252 queryParameters["textDecorations"] = autorest.Encode("query", *textDecorations) 253 } 254 if len(string(textFormat)) > 0 { 255 queryParameters["textFormat"] = autorest.Encode("query", textFormat) 256 } 257 258 preparer := autorest.CreatePreparer( 259 autorest.AsGet(), 260 autorest.WithCustomBaseURL("{Endpoint}/bing/v7.0", urlParameters), 261 autorest.WithPath("/search"), 262 autorest.WithQueryParameters(queryParameters), 263 autorest.WithHeader("X-BingApis-SDK", "true")) 264 if len(acceptLanguage) > 0 { 265 preparer = autorest.DecoratePreparer(preparer, 266 autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage))) 267 } 268 if len(pragma) > 0 { 269 preparer = autorest.DecoratePreparer(preparer, 270 autorest.WithHeader("Pragma", autorest.String(pragma))) 271 } 272 if len(userAgent) > 0 { 273 preparer = autorest.DecoratePreparer(preparer, 274 autorest.WithHeader("User-Agent", autorest.String(userAgent))) 275 } 276 if len(clientID) > 0 { 277 preparer = autorest.DecoratePreparer(preparer, 278 autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID))) 279 } 280 if len(clientIP) > 0 { 281 preparer = autorest.DecoratePreparer(preparer, 282 autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP))) 283 } 284 if len(location) > 0 { 285 preparer = autorest.DecoratePreparer(preparer, 286 autorest.WithHeader("X-Search-Location", autorest.String(location))) 287 } 288 return preparer.Prepare((&http.Request{}).WithContext(ctx)) 289} 290 291// SearchSender sends the Search request. The method will close the 292// http.Response Body if it receives an error. 293func (client WebClient) SearchSender(req *http.Request) (*http.Response, error) { 294 return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) 295} 296 297// SearchResponder handles the response to the Search request. The method always 298// closes the http.Response Body. 299func (client WebClient) SearchResponder(resp *http.Response) (result SearchResponse, err error) { 300 err = autorest.Respond( 301 resp, 302 azure.WithErrorUnlessStatusCode(http.StatusOK), 303 autorest.ByUnmarshallingJSON(&result), 304 autorest.ByClosing()) 305 result.Response = autorest.Response{Response: resp} 306 return 307} 308