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