vendor: update all dependencies to latest versions

This commit is contained in:
Nick Craig-Wood
2018-01-16 13:20:59 +00:00
parent 8e83fb6fb9
commit 7d3a17725d
4878 changed files with 1974213 additions and 201199 deletions
@@ -0,0 +1,44 @@
// Package runtime implements the Azure ARM Runtime service API version v2.0.
//
//
package runtime
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
// BaseClient is the base client for Runtime.
type BaseClient struct {
autorest.Client
AzureRegion AzureRegions
}
// New creates an instance of the BaseClient client.
func New(azureRegion AzureRegions) BaseClient {
return NewWithoutDefaults(azureRegion)
}
// NewWithoutDefaults creates an instance of the BaseClient client.
func NewWithoutDefaults(azureRegion AzureRegions) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
AzureRegion: azureRegion,
}
}
@@ -0,0 +1,148 @@
package runtime
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
// AzureRegions enumerates the values for azure regions.
type AzureRegions string
const (
// Australiaeast ...
Australiaeast AzureRegions = "australiaeast"
// Brazilsouth ...
Brazilsouth AzureRegions = "brazilsouth"
// Eastasia ...
Eastasia AzureRegions = "eastasia"
// Eastus ...
Eastus AzureRegions = "eastus"
// Eastus2 ...
Eastus2 AzureRegions = "eastus2"
// Northeurope ...
Northeurope AzureRegions = "northeurope"
// Southcentralus ...
Southcentralus AzureRegions = "southcentralus"
// Southeastasia ...
Southeastasia AzureRegions = "southeastasia"
// Westcentralus ...
Westcentralus AzureRegions = "westcentralus"
// Westeurope ...
Westeurope AzureRegions = "westeurope"
// Westus ...
Westus AzureRegions = "westus"
// Westus2 ...
Westus2 AzureRegions = "westus2"
)
// APIError error information returned by the API
type APIError struct {
// StatusCode - HTTP Status code
StatusCode *string `json:"statusCode,omitempty"`
// Message - Cause of the error.
Message *string `json:"message,omitempty"`
}
// CompositeChildModel child entity in a LUIS Composite Entity.
type CompositeChildModel struct {
// Type - Type of child entity.
Type *string `json:"type,omitempty"`
// Value - Value extracted by LUIS.
Value *string `json:"value,omitempty"`
}
// CompositeEntityModel LUIS Composite Entity.
type CompositeEntityModel struct {
// ParentType - Type/name of parent entity.
ParentType *string `json:"parentType,omitempty"`
// Value - Value for composite entity extracted by LUIS.
Value *string `json:"value,omitempty"`
// Children - Child entities.
Children *[]CompositeChildModel `json:"children,omitempty"`
}
// EntityModel an entity extracted from the utterance.
type EntityModel struct {
// AdditionalProperties - Unmatched properties from the message are deserialized this collection
AdditionalProperties *map[string]*map[string]interface{} `json:",omitempty"`
// Entity - Name of the entity, as defined in LUIS.
Entity *string `json:"entity,omitempty"`
// Type - Type of the entity, as defined in LUIS.
Type *string `json:"type,omitempty"`
// StartIndex - The position of the first character of the matched entity within the utterance.
StartIndex *float64 `json:"startIndex,omitempty"`
// EndIndex - The position of the last character of the matched entity within the utterance.
EndIndex *float64 `json:"endIndex,omitempty"`
}
// EntityWithResolution ...
type EntityWithResolution struct {
// AdditionalProperties - Unmatched properties from the message are deserialized this collection
AdditionalProperties *map[string]*map[string]interface{} `json:",omitempty"`
// Entity - Name of the entity, as defined in LUIS.
Entity *string `json:"entity,omitempty"`
// Type - Type of the entity, as defined in LUIS.
Type *string `json:"type,omitempty"`
// StartIndex - The position of the first character of the matched entity within the utterance.
StartIndex *float64 `json:"startIndex,omitempty"`
// EndIndex - The position of the last character of the matched entity within the utterance.
EndIndex *float64 `json:"endIndex,omitempty"`
// Resolution - Resolution values for pre-built LUIS entities.
Resolution *map[string]interface{} `json:"resolution,omitempty"`
}
// EntityWithScore ...
type EntityWithScore struct {
// AdditionalProperties - Unmatched properties from the message are deserialized this collection
AdditionalProperties *map[string]*map[string]interface{} `json:",omitempty"`
// Entity - Name of the entity, as defined in LUIS.
Entity *string `json:"entity,omitempty"`
// Type - Type of the entity, as defined in LUIS.
Type *string `json:"type,omitempty"`
// StartIndex - The position of the first character of the matched entity within the utterance.
StartIndex *float64 `json:"startIndex,omitempty"`
// EndIndex - The position of the last character of the matched entity within the utterance.
EndIndex *float64 `json:"endIndex,omitempty"`
// Score - Associated prediction score for the intent (float).
Score *float64 `json:"score,omitempty"`
}
// IntentModel an intent detected from the utterance.
type IntentModel struct {
// Intent - Name of the intent, as defined in LUIS.
Intent *string `json:"intent,omitempty"`
// Score - Associated prediction score for the intent (float).
Score *float64 `json:"score,omitempty"`
}
// LuisResult prediction, based on the input query, containing intent(s) and entities.
type LuisResult struct {
autorest.Response `json:"-"`
// Query - The input utterance that was analized.
Query *string `json:"query,omitempty"`
// AlteredQuery - The corrected utterance (when spell checking was enabled).
AlteredQuery *string `json:"alteredQuery,omitempty"`
TopScoringIntent *IntentModel `json:"topScoringIntent,omitempty"`
// Intents - All the intents (and their score) that were detected from utterance.
Intents *[]IntentModel `json:"intents,omitempty"`
// Entities - The entities extracted from the utterance.
Entities *[]EntityModel `json:"entities,omitempty"`
// CompositeEntities - The composite entities extracted from the utterance.
CompositeEntities *[]CompositeEntityModel `json:"compositeEntities,omitempty"`
}
@@ -0,0 +1,131 @@
package runtime
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// PredictionClient is the client for the Prediction methods of the Runtime service.
type PredictionClient struct {
BaseClient
}
// NewPredictionClient creates an instance of the PredictionClient client.
func NewPredictionClient(azureRegion AzureRegions) PredictionClient {
return PredictionClient{New(azureRegion)}
}
// Resolve gets predictions for a given utterance, in the form of intents and entities. The current maximum query size
// is 500 characters.
//
// appID is the LUIS application ID (Guid). query is the utterance to predict. timezoneOffset is the timezone offset
// for the location of the request. verbose is if true, return all intents instead of just the top scoring intent.
// staging is use the staging endpoint slot. spellCheck is enable spell checking. bingSpellCheckSubscriptionKey is the
// subscription key to use when enabling bing spell check logParameter is log query (default is true)
func (client PredictionClient) Resolve(ctx context.Context, appID string, query string, timezoneOffset *float64, verbose *bool, staging *bool, spellCheck *bool, bingSpellCheckSubscriptionKey string, logParameter *bool) (result LuisResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: query,
Constraints: []validation.Constraint{{Target: "query", Name: validation.MaxLength, Rule: 500, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "runtime.PredictionClient", "Resolve")
}
req, err := client.ResolvePreparer(ctx, appID, query, timezoneOffset, verbose, staging, spellCheck, bingSpellCheckSubscriptionKey, logParameter)
if err != nil {
err = autorest.NewErrorWithError(err, "runtime.PredictionClient", "Resolve", nil, "Failure preparing request")
return
}
resp, err := client.ResolveSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "runtime.PredictionClient", "Resolve", resp, "Failure sending request")
return
}
result, err = client.ResolveResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "runtime.PredictionClient", "Resolve", resp, "Failure responding to request")
}
return
}
// ResolvePreparer prepares the Resolve request.
func (client PredictionClient) ResolvePreparer(ctx context.Context, appID string, query string, timezoneOffset *float64, verbose *bool, staging *bool, spellCheck *bool, bingSpellCheckSubscriptionKey string, logParameter *bool) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"appId": autorest.Encode("path", appID),
}
queryParameters := map[string]interface{}{}
if timezoneOffset != nil {
queryParameters["timezoneOffset"] = autorest.Encode("query", *timezoneOffset)
}
if verbose != nil {
queryParameters["verbose"] = autorest.Encode("query", *verbose)
}
if staging != nil {
queryParameters["staging"] = autorest.Encode("query", *staging)
}
if spellCheck != nil {
queryParameters["spellCheck"] = autorest.Encode("query", *spellCheck)
}
if len(bingSpellCheckSubscriptionKey) > 0 {
queryParameters["bing-spell-check-subscription-key"] = autorest.Encode("query", bingSpellCheckSubscriptionKey)
}
if logParameter != nil {
queryParameters["log"] = autorest.Encode("query", *logParameter)
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/luis/v2.0/apps", urlParameters),
autorest.WithPathParameters("/{appId}", pathParameters),
autorest.WithJSON(query),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ResolveSender sends the Resolve request. The method will close the
// http.Response Body if it receives an error.
func (client PredictionClient) ResolveSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// ResolveResponder handles the response to the Resolve request. The method always
// closes the http.Response Body.
func (client PredictionClient) ResolveResponder(resp *http.Response) (result LuisResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,28 @@
package runtime
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/v12.2.0-beta services"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v12.2.0-beta"
}
@@ -0,0 +1,712 @@
package cognitiveservices
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// AccountsClient is the cognitive Services Management Client
type AccountsClient struct {
BaseClient
}
// NewAccountsClient creates an instance of the AccountsClient client.
func NewAccountsClient(subscriptionID string) AccountsClient {
return NewAccountsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewAccountsClientWithBaseURI creates an instance of the AccountsClient client.
func NewAccountsClientWithBaseURI(baseURI string, subscriptionID string) AccountsClient {
return AccountsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Create create Cognitive Services Account. Accounts is a resource group wide resource type. It holds the keys for
// developer to access intelligent APIs. It's also the resource type for billing.
//
// resourceGroupName is the name of the resource group within the user's subscription. accountName is the name of the
// cognitive services account within the specified resource group. Cognitive Services account names must be between 3
// and 24 characters in length and use numbers and lower-case letters only. parameters is the parameters to provide for
// the created account.
func (client AccountsClient) Create(ctx context.Context, resourceGroupName string, accountName string, parameters AccountCreateParameters) (result Account, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}},
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.Sku", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.Location", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.Properties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "cognitiveservices.AccountsClient", "Create")
}
req, err := client.CreatePreparer(ctx, resourceGroupName, accountName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Create", nil, "Failure preparing request")
return
}
resp, err := client.CreateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Create", resp, "Failure sending request")
return
}
result, err = client.CreateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Create", resp, "Failure responding to request")
}
return
}
// CreatePreparer prepares the Create request.
func (client AccountsClient) CreatePreparer(ctx context.Context, resourceGroupName string, accountName string, parameters AccountCreateParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-02-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) CreateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// CreateResponder handles the response to the Create request. The method always
// closes the http.Response Body.
func (client AccountsClient) CreateResponder(resp *http.Response) (result Account, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes a Cognitive Services account from the resource group.
//
// resourceGroupName is the name of the resource group within the user's subscription. accountName is the name of the
// cognitive services account within the specified resource group. Cognitive Services account names must be between 3
// and 24 characters in length and use numbers and lower-case letters only.
func (client AccountsClient) Delete(ctx context.Context, resourceGroupName string, accountName string) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "cognitiveservices.AccountsClient", "Delete")
}
req, err := client.DeletePreparer(ctx, resourceGroupName, accountName)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client AccountsClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-02-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client AccountsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// GetProperties returns a Cognitive Services account specified by the parameters.
//
// resourceGroupName is the name of the resource group within the user's subscription. accountName is the name of the
// cognitive services account within the specified resource group. Cognitive Services account names must be between 3
// and 24 characters in length and use numbers and lower-case letters only.
func (client AccountsClient) GetProperties(ctx context.Context, resourceGroupName string, accountName string) (result Account, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "cognitiveservices.AccountsClient", "GetProperties")
}
req, err := client.GetPropertiesPreparer(ctx, resourceGroupName, accountName)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "GetProperties", nil, "Failure preparing request")
return
}
resp, err := client.GetPropertiesSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "GetProperties", resp, "Failure sending request")
return
}
result, err = client.GetPropertiesResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "GetProperties", resp, "Failure responding to request")
}
return
}
// GetPropertiesPreparer prepares the GetProperties request.
func (client AccountsClient) GetPropertiesPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-02-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetPropertiesSender sends the GetProperties request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) GetPropertiesSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetPropertiesResponder handles the response to the GetProperties request. The method always
// closes the http.Response Body.
func (client AccountsClient) GetPropertiesResponder(resp *http.Response) (result Account, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List returns all the resources of a particular type belonging to a subscription.
func (client AccountsClient) List(ctx context.Context) (result AccountListResult, err error) {
req, err := client.ListPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "List", resp, "Failure sending request")
return
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client AccountsClient) ListPreparer(ctx context.Context) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-02-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/accounts", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client AccountsClient) ListResponder(resp *http.Response) (result AccountListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByResourceGroup returns all the resources of a particular type belonging to a resource group
//
// resourceGroupName is the name of the resource group within the user's subscription.
func (client AccountsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result AccountListResult, err error) {
req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListByResourceGroup", nil, "Failure preparing request")
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListByResourceGroup", resp, "Failure sending request")
return
}
result, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListByResourceGroup", resp, "Failure responding to request")
}
return
}
// ListByResourceGroupPreparer prepares the ListByResourceGroup request.
func (client AccountsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-02-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always
// closes the http.Response Body.
func (client AccountsClient) ListByResourceGroupResponder(resp *http.Response) (result AccountListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListKeys lists the account keys for the specified Cognitive Services account.
//
// resourceGroupName is the name of the resource group within the user's subscription. accountName is the name of the
// cognitive services account within the specified resource group. Congitive Services account names must be between 3
// and 24 characters in length and use numbers and lower-case letters only.
func (client AccountsClient) ListKeys(ctx context.Context, resourceGroupName string, accountName string) (result AccountKeys, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "cognitiveservices.AccountsClient", "ListKeys")
}
req, err := client.ListKeysPreparer(ctx, resourceGroupName, accountName)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListKeys", nil, "Failure preparing request")
return
}
resp, err := client.ListKeysSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListKeys", resp, "Failure sending request")
return
}
result, err = client.ListKeysResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListKeys", resp, "Failure responding to request")
}
return
}
// ListKeysPreparer prepares the ListKeys request.
func (client AccountsClient) ListKeysPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-02-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/listKeys", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListKeysSender sends the ListKeys request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) ListKeysSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListKeysResponder handles the response to the ListKeys request. The method always
// closes the http.Response Body.
func (client AccountsClient) ListKeysResponder(resp *http.Response) (result AccountKeys, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListSkus list available SKUs for the requested Cognitive Services account
//
// resourceGroupName is the name of the resource group within the user's subscription. accountName is the name of the
// cognitive services account within the specified resource group. Cognitive Services account names must be between 3
// and 24 characters in length and use numbers and lower-case letters only.
func (client AccountsClient) ListSkus(ctx context.Context, resourceGroupName string, accountName string) (result AccountEnumerateSkusResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "cognitiveservices.AccountsClient", "ListSkus")
}
req, err := client.ListSkusPreparer(ctx, resourceGroupName, accountName)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListSkus", nil, "Failure preparing request")
return
}
resp, err := client.ListSkusSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListSkus", resp, "Failure sending request")
return
}
result, err = client.ListSkusResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListSkus", resp, "Failure responding to request")
}
return
}
// ListSkusPreparer prepares the ListSkus request.
func (client AccountsClient) ListSkusPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-02-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/skus", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSkusSender sends the ListSkus request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) ListSkusSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListSkusResponder handles the response to the ListSkus request. The method always
// closes the http.Response Body.
func (client AccountsClient) ListSkusResponder(resp *http.Response) (result AccountEnumerateSkusResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// RegenerateKey regenerates the specified account key for the specified Cognitive Services account.
//
// resourceGroupName is the name of the resource group within the user's subscription. accountName is the name of the
// cognitive services account within the specified resource group. Cognitive Services account names must be between 3
// and 24 characters in length and use numbers and lower-case letters only. body is regenerate key parameters.
func (client AccountsClient) RegenerateKey(ctx context.Context, resourceGroupName string, accountName string, body RegenerateKeyParameters) (result AccountKeys, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "cognitiveservices.AccountsClient", "RegenerateKey")
}
req, err := client.RegenerateKeyPreparer(ctx, resourceGroupName, accountName, body)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "RegenerateKey", nil, "Failure preparing request")
return
}
resp, err := client.RegenerateKeySender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "RegenerateKey", resp, "Failure sending request")
return
}
result, err = client.RegenerateKeyResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "RegenerateKey", resp, "Failure responding to request")
}
return
}
// RegenerateKeyPreparer prepares the RegenerateKey request.
func (client AccountsClient) RegenerateKeyPreparer(ctx context.Context, resourceGroupName string, accountName string, body RegenerateKeyParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-02-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/regenerateKey", pathParameters),
autorest.WithJSON(body),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// RegenerateKeySender sends the RegenerateKey request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) RegenerateKeySender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// RegenerateKeyResponder handles the response to the RegenerateKey request. The method always
// closes the http.Response Body.
func (client AccountsClient) RegenerateKeyResponder(resp *http.Response) (result AccountKeys, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Update updates a Cognitive Services account
//
// resourceGroupName is the name of the resource group within the user's subscription. accountName is the name of the
// cognitive services account within the specified resource group. Cognitive Services account names must be between 3
// and 24 characters in length and use numbers and lower-case letters only. body is the parameters to provide for the
// created account.
func (client AccountsClient) Update(ctx context.Context, resourceGroupName string, accountName string, body AccountUpdateParameters) (result Account, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "cognitiveservices.AccountsClient", "Update")
}
req, err := client.UpdatePreparer(ctx, resourceGroupName, accountName, body)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Update", nil, "Failure preparing request")
return
}
resp, err := client.UpdateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Update", resp, "Failure sending request")
return
}
result, err = client.UpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Update", resp, "Failure responding to request")
}
return
}
// UpdatePreparer prepares the Update request.
func (client AccountsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, body AccountUpdateParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-02-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPatch(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}", pathParameters),
autorest.WithJSON(body),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) UpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client AccountsClient) UpdateResponder(resp *http.Response) (result Account, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,51 @@
// Package cognitiveservices implements the Azure ARM Cognitiveservices service API version 2016-02-01-preview.
//
// Cognitive Services Management Client
package cognitiveservices
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
const (
// DefaultBaseURI is the default URI used for the service Cognitiveservices
DefaultBaseURI = "https://management.azure.com"
)
// BaseClient is the base client for Cognitiveservices.
type BaseClient struct {
autorest.Client
BaseURI string
SubscriptionID string
}
// New creates an instance of the BaseClient client.
func New(subscriptionID string) BaseClient {
return NewWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewWithBaseURI creates an instance of the BaseClient client.
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
SubscriptionID: subscriptionID,
}
}
@@ -0,0 +1,336 @@
package cognitiveservices
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"encoding/json"
"github.com/Azure/go-autorest/autorest"
)
// KeyName enumerates the values for key name.
type KeyName string
const (
// Key1 ...
Key1 KeyName = "Key1"
// Key2 ...
Key2 KeyName = "Key2"
)
// Kind enumerates the values for kind.
type Kind string
const (
// Academic ...
Academic Kind = "Academic"
// BingAutosuggest ...
BingAutosuggest Kind = "Bing.Autosuggest"
// BingSearch ...
BingSearch Kind = "Bing.Search"
// BingSpeech ...
BingSpeech Kind = "Bing.Speech"
// BingSpellCheck ...
BingSpellCheck Kind = "Bing.SpellCheck"
// ComputerVision ...
ComputerVision Kind = "ComputerVision"
// ContentModerator ...
ContentModerator Kind = "ContentModerator"
// Emotion ...
Emotion Kind = "Emotion"
// Face ...
Face Kind = "Face"
// LUIS ...
LUIS Kind = "LUIS"
// Recommendations ...
Recommendations Kind = "Recommendations"
// SpeakerRecognition ...
SpeakerRecognition Kind = "SpeakerRecognition"
// Speech ...
Speech Kind = "Speech"
// SpeechTranslation ...
SpeechTranslation Kind = "SpeechTranslation"
// TextAnalytics ...
TextAnalytics Kind = "TextAnalytics"
// TextTranslation ...
TextTranslation Kind = "TextTranslation"
// WebLM ...
WebLM Kind = "WebLM"
)
// ProvisioningState enumerates the values for provisioning state.
type ProvisioningState string
const (
// Creating ...
Creating ProvisioningState = "Creating"
// Failed ...
Failed ProvisioningState = "Failed"
// ResolvingDNS ...
ResolvingDNS ProvisioningState = "ResolvingDNS"
// Succeeded ...
Succeeded ProvisioningState = "Succeeded"
)
// SkuName enumerates the values for sku name.
type SkuName string
const (
// F0 ...
F0 SkuName = "F0"
// P0 ...
P0 SkuName = "P0"
// P1 ...
P1 SkuName = "P1"
// P2 ...
P2 SkuName = "P2"
// S0 ...
S0 SkuName = "S0"
// S1 ...
S1 SkuName = "S1"
// S2 ...
S2 SkuName = "S2"
// S3 ...
S3 SkuName = "S3"
// S4 ...
S4 SkuName = "S4"
// S5 ...
S5 SkuName = "S5"
// S6 ...
S6 SkuName = "S6"
)
// SkuTier enumerates the values for sku tier.
type SkuTier string
const (
// Free ...
Free SkuTier = "Free"
// Premium ...
Premium SkuTier = "Premium"
// Standard ...
Standard SkuTier = "Standard"
)
// Account cognitive Services Account is an Azure resource representing the provisioned account, its type, location and
// SKU.
type Account struct {
autorest.Response `json:"-"`
// Etag - Entity Tag
Etag *string `json:"etag,omitempty"`
// ID - The id of the created account
ID *string `json:"id,omitempty"`
// Kind - Type of cognitive service account.
Kind *string `json:"kind,omitempty"`
// Location - The location of the resource
Location *string `json:"location,omitempty"`
// Name - The name of the created account
Name *string `json:"name,omitempty"`
*AccountProperties `json:"properties,omitempty"`
Sku *Sku `json:"sku,omitempty"`
// Tags - Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters.
Tags *map[string]*string `json:"tags,omitempty"`
// Type - Resource type
Type *string `json:"type,omitempty"`
}
// UnmarshalJSON is the custom unmarshaler for Account struct.
func (a *Account) UnmarshalJSON(body []byte) error {
var m map[string]*json.RawMessage
err := json.Unmarshal(body, &m)
if err != nil {
return err
}
var v *json.RawMessage
v = m["etag"]
if v != nil {
var etag string
err = json.Unmarshal(*m["etag"], &etag)
if err != nil {
return err
}
a.Etag = &etag
}
v = m["id"]
if v != nil {
var ID string
err = json.Unmarshal(*m["id"], &ID)
if err != nil {
return err
}
a.ID = &ID
}
v = m["kind"]
if v != nil {
var kind string
err = json.Unmarshal(*m["kind"], &kind)
if err != nil {
return err
}
a.Kind = &kind
}
v = m["location"]
if v != nil {
var location string
err = json.Unmarshal(*m["location"], &location)
if err != nil {
return err
}
a.Location = &location
}
v = m["name"]
if v != nil {
var name string
err = json.Unmarshal(*m["name"], &name)
if err != nil {
return err
}
a.Name = &name
}
v = m["properties"]
if v != nil {
var properties AccountProperties
err = json.Unmarshal(*m["properties"], &properties)
if err != nil {
return err
}
a.AccountProperties = &properties
}
v = m["sku"]
if v != nil {
var sku Sku
err = json.Unmarshal(*m["sku"], &sku)
if err != nil {
return err
}
a.Sku = &sku
}
v = m["tags"]
if v != nil {
var tags map[string]*string
err = json.Unmarshal(*m["tags"], &tags)
if err != nil {
return err
}
a.Tags = &tags
}
v = m["type"]
if v != nil {
var typeVar string
err = json.Unmarshal(*m["type"], &typeVar)
if err != nil {
return err
}
a.Type = &typeVar
}
return nil
}
// AccountCreateParameters the parameters to provide for the account.
type AccountCreateParameters struct {
Sku *Sku `json:"sku,omitempty"`
// Kind - Required. Indicates the type of cognitive service account. Possible values include: 'Academic', 'BingAutosuggest', 'BingSearch', 'BingSpeech', 'BingSpellCheck', 'ComputerVision', 'ContentModerator', 'Emotion', 'Face', 'LUIS', 'Recommendations', 'SpeakerRecognition', 'Speech', 'SpeechTranslation', 'TextAnalytics', 'TextTranslation', 'WebLM'
Kind Kind `json:"kind,omitempty"`
// Location - Required. Gets or sets the location of the resource. This will be one of the supported and registered Azure Geo Regions (e.g. West US, East US, Southeast Asia, etc.). The geo region of a resource cannot be changed once it is created, but if an identical geo region is specified on update the request will succeed.
Location *string `json:"location,omitempty"`
// Tags - Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters.
Tags *map[string]*string `json:"tags,omitempty"`
// Properties - Must exist in the request. Must not be null.
Properties *map[string]interface{} `json:"properties,omitempty"`
}
// AccountEnumerateSkusResult the list of cognitive services accounts operation response.
type AccountEnumerateSkusResult struct {
autorest.Response `json:"-"`
// Value - Gets the list of Cognitive Services accounts and their properties.
Value *[]ResourceAndSku `json:"value,omitempty"`
}
// AccountKeys the access keys for the cognitive services account.
type AccountKeys struct {
autorest.Response `json:"-"`
// Key1 - Gets the value of key 1.
Key1 *string `json:"key1,omitempty"`
// Key2 - Gets the value of key 2.
Key2 *string `json:"key2,omitempty"`
}
// AccountListResult the list of cognitive services accounts operation response.
type AccountListResult struct {
autorest.Response `json:"-"`
// Value - Gets the list of Cognitive Services accounts and their properties.
Value *[]Account `json:"value,omitempty"`
}
// AccountProperties ...
type AccountProperties struct {
// ProvisioningState - Gets the status of the cognitive services account at the time the operation was called. Possible values include: 'Creating', 'ResolvingDNS', 'Succeeded', 'Failed'
ProvisioningState ProvisioningState `json:"provisioningState,omitempty"`
// Endpoint - Endpoint of the created account
Endpoint *string `json:"endpoint,omitempty"`
}
// AccountUpdateParameters the parameters to provide for the account.
type AccountUpdateParameters struct {
Sku *Sku `json:"sku,omitempty"`
// Tags - Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters.
Tags *map[string]*string `json:"tags,omitempty"`
}
// Error ...
type Error struct {
Error *ErrorBody `json:"error,omitempty"`
}
// ErrorBody ...
type ErrorBody struct {
// Code - error code
Code *string `json:"code,omitempty"`
// Message - error message
Message *string `json:"message,omitempty"`
}
// RegenerateKeyParameters regenerate key parameters.
type RegenerateKeyParameters struct {
// KeyName - key name to generate (Key1|Key2). Possible values include: 'Key1', 'Key2'
KeyName KeyName `json:"keyName,omitempty"`
}
// ResourceAndSku ...
type ResourceAndSku struct {
// ResourceType - Resource Namespace and Type
ResourceType *string `json:"resourceType,omitempty"`
Sku *Sku `json:"sku,omitempty"`
}
// Sku the SKU of the cognitive services account.
type Sku struct {
// Name - Gets or sets the sku name. Required for account creation, optional for update. Possible values include: 'F0', 'P0', 'P1', 'P2', 'S0', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6'
Name SkuName `json:"name,omitempty"`
// Tier - Gets the sku tier. This is based on the SKU name. Possible values include: 'Free', 'Standard', 'Premium'
Tier SkuTier `json:"tier,omitempty"`
}
@@ -0,0 +1,28 @@
package cognitiveservices
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/v12.2.0-beta services"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v12.2.0-beta"
}
@@ -0,0 +1,759 @@
package cognitiveservices
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// AccountsClient is the cognitive Services Management Client
type AccountsClient struct {
BaseClient
}
// NewAccountsClient creates an instance of the AccountsClient client.
func NewAccountsClient(subscriptionID string) AccountsClient {
return NewAccountsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewAccountsClientWithBaseURI creates an instance of the AccountsClient client.
func NewAccountsClientWithBaseURI(baseURI string, subscriptionID string) AccountsClient {
return AccountsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Create create Cognitive Services Account. Accounts is a resource group wide resource type. It holds the keys for
// developer to access intelligent APIs. It's also the resource type for billing.
//
// resourceGroupName is the name of the resource group within the user's subscription. accountName is the name of
// Cognitive Services account. parameters is the parameters to provide for the created account.
func (client AccountsClient) Create(ctx context.Context, resourceGroupName string, accountName string, parameters AccountCreateParameters) (result Account, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 2, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}},
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.Sku", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.Location", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.Properties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "cognitiveservices.AccountsClient", "Create")
}
req, err := client.CreatePreparer(ctx, resourceGroupName, accountName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Create", nil, "Failure preparing request")
return
}
resp, err := client.CreateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Create", resp, "Failure sending request")
return
}
result, err = client.CreateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Create", resp, "Failure responding to request")
}
return
}
// CreatePreparer prepares the Create request.
func (client AccountsClient) CreatePreparer(ctx context.Context, resourceGroupName string, accountName string, parameters AccountCreateParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-18"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) CreateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// CreateResponder handles the response to the Create request. The method always
// closes the http.Response Body.
func (client AccountsClient) CreateResponder(resp *http.Response) (result Account, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes a Cognitive Services account from the resource group.
//
// resourceGroupName is the name of the resource group within the user's subscription. accountName is the name of
// Cognitive Services account.
func (client AccountsClient) Delete(ctx context.Context, resourceGroupName string, accountName string) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 2, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "cognitiveservices.AccountsClient", "Delete")
}
req, err := client.DeletePreparer(ctx, resourceGroupName, accountName)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client AccountsClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-18"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client AccountsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// GetProperties returns a Cognitive Services account specified by the parameters.
//
// resourceGroupName is the name of the resource group within the user's subscription. accountName is the name of
// Cognitive Services account.
func (client AccountsClient) GetProperties(ctx context.Context, resourceGroupName string, accountName string) (result Account, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 2, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "cognitiveservices.AccountsClient", "GetProperties")
}
req, err := client.GetPropertiesPreparer(ctx, resourceGroupName, accountName)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "GetProperties", nil, "Failure preparing request")
return
}
resp, err := client.GetPropertiesSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "GetProperties", resp, "Failure sending request")
return
}
result, err = client.GetPropertiesResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "GetProperties", resp, "Failure responding to request")
}
return
}
// GetPropertiesPreparer prepares the GetProperties request.
func (client AccountsClient) GetPropertiesPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-18"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetPropertiesSender sends the GetProperties request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) GetPropertiesSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetPropertiesResponder handles the response to the GetProperties request. The method always
// closes the http.Response Body.
func (client AccountsClient) GetPropertiesResponder(resp *http.Response) (result Account, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List returns all the resources of a particular type belonging to a subscription.
func (client AccountsClient) List(ctx context.Context) (result AccountListResultPage, err error) {
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.alr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "List", resp, "Failure sending request")
return
}
result.alr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client AccountsClient) ListPreparer(ctx context.Context) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-18"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/accounts", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client AccountsClient) ListResponder(resp *http.Response) (result AccountListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client AccountsClient) listNextResults(lastResults AccountListResult) (result AccountListResult, err error) {
req, err := lastResults.accountListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client AccountsClient) ListComplete(ctx context.Context) (result AccountListResultIterator, err error) {
result.page, err = client.List(ctx)
return
}
// ListByResourceGroup returns all the resources of a particular type belonging to a resource group
//
// resourceGroupName is the name of the resource group within the user's subscription.
func (client AccountsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result AccountListResultPage, err error) {
result.fn = client.listByResourceGroupNextResults
req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListByResourceGroup", nil, "Failure preparing request")
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.alr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListByResourceGroup", resp, "Failure sending request")
return
}
result.alr, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListByResourceGroup", resp, "Failure responding to request")
}
return
}
// ListByResourceGroupPreparer prepares the ListByResourceGroup request.
func (client AccountsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-18"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always
// closes the http.Response Body.
func (client AccountsClient) ListByResourceGroupResponder(resp *http.Response) (result AccountListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByResourceGroupNextResults retrieves the next set of results, if any.
func (client AccountsClient) listByResourceGroupNextResults(lastResults AccountListResult) (result AccountListResult, err error) {
req, err := lastResults.accountListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required.
func (client AccountsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result AccountListResultIterator, err error) {
result.page, err = client.ListByResourceGroup(ctx, resourceGroupName)
return
}
// ListKeys lists the account keys for the specified Cognitive Services account.
//
// resourceGroupName is the name of the resource group within the user's subscription. accountName is the name of
// Cognitive Services account.
func (client AccountsClient) ListKeys(ctx context.Context, resourceGroupName string, accountName string) (result AccountKeys, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 2, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "cognitiveservices.AccountsClient", "ListKeys")
}
req, err := client.ListKeysPreparer(ctx, resourceGroupName, accountName)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListKeys", nil, "Failure preparing request")
return
}
resp, err := client.ListKeysSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListKeys", resp, "Failure sending request")
return
}
result, err = client.ListKeysResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListKeys", resp, "Failure responding to request")
}
return
}
// ListKeysPreparer prepares the ListKeys request.
func (client AccountsClient) ListKeysPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-18"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/listKeys", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListKeysSender sends the ListKeys request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) ListKeysSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListKeysResponder handles the response to the ListKeys request. The method always
// closes the http.Response Body.
func (client AccountsClient) ListKeysResponder(resp *http.Response) (result AccountKeys, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListSkus list available SKUs for the requested Cognitive Services account
//
// resourceGroupName is the name of the resource group within the user's subscription. accountName is the name of
// Cognitive Services account.
func (client AccountsClient) ListSkus(ctx context.Context, resourceGroupName string, accountName string) (result AccountEnumerateSkusResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 2, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "cognitiveservices.AccountsClient", "ListSkus")
}
req, err := client.ListSkusPreparer(ctx, resourceGroupName, accountName)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListSkus", nil, "Failure preparing request")
return
}
resp, err := client.ListSkusSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListSkus", resp, "Failure sending request")
return
}
result, err = client.ListSkusResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "ListSkus", resp, "Failure responding to request")
}
return
}
// ListSkusPreparer prepares the ListSkus request.
func (client AccountsClient) ListSkusPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-18"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/skus", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSkusSender sends the ListSkus request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) ListSkusSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListSkusResponder handles the response to the ListSkus request. The method always
// closes the http.Response Body.
func (client AccountsClient) ListSkusResponder(resp *http.Response) (result AccountEnumerateSkusResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// RegenerateKey regenerates the specified account key for the specified Cognitive Services account.
//
// resourceGroupName is the name of the resource group within the user's subscription. accountName is the name of
// Cognitive Services account. parameters is regenerate key parameters.
func (client AccountsClient) RegenerateKey(ctx context.Context, resourceGroupName string, accountName string, parameters RegenerateKeyParameters) (result AccountKeys, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 2, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "cognitiveservices.AccountsClient", "RegenerateKey")
}
req, err := client.RegenerateKeyPreparer(ctx, resourceGroupName, accountName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "RegenerateKey", nil, "Failure preparing request")
return
}
resp, err := client.RegenerateKeySender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "RegenerateKey", resp, "Failure sending request")
return
}
result, err = client.RegenerateKeyResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "RegenerateKey", resp, "Failure responding to request")
}
return
}
// RegenerateKeyPreparer prepares the RegenerateKey request.
func (client AccountsClient) RegenerateKeyPreparer(ctx context.Context, resourceGroupName string, accountName string, parameters RegenerateKeyParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-18"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/regenerateKey", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// RegenerateKeySender sends the RegenerateKey request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) RegenerateKeySender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// RegenerateKeyResponder handles the response to the RegenerateKey request. The method always
// closes the http.Response Body.
func (client AccountsClient) RegenerateKeyResponder(resp *http.Response) (result AccountKeys, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Update updates a Cognitive Services account
//
// resourceGroupName is the name of the resource group within the user's subscription. accountName is the name of
// Cognitive Services account. parameters is the parameters to provide for the created account.
func (client AccountsClient) Update(ctx context.Context, resourceGroupName string, accountName string, parameters AccountUpdateParameters) (result Account, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 2, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "cognitiveservices.AccountsClient", "Update")
}
req, err := client.UpdatePreparer(ctx, resourceGroupName, accountName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Update", nil, "Failure preparing request")
return
}
resp, err := client.UpdateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Update", resp, "Failure sending request")
return
}
result, err = client.UpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.AccountsClient", "Update", resp, "Failure responding to request")
}
return
}
// UpdatePreparer prepares the Update request.
func (client AccountsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, parameters AccountUpdateParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-18"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPatch(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client AccountsClient) UpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client AccountsClient) UpdateResponder(resp *http.Response) (result Account, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,115 @@
package cognitiveservices
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// CheckSkuAvailabilityClient is the cognitive Services Management Client
type CheckSkuAvailabilityClient struct {
BaseClient
}
// NewCheckSkuAvailabilityClient creates an instance of the CheckSkuAvailabilityClient client.
func NewCheckSkuAvailabilityClient(subscriptionID string) CheckSkuAvailabilityClient {
return NewCheckSkuAvailabilityClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewCheckSkuAvailabilityClientWithBaseURI creates an instance of the CheckSkuAvailabilityClient client.
func NewCheckSkuAvailabilityClientWithBaseURI(baseURI string, subscriptionID string) CheckSkuAvailabilityClient {
return CheckSkuAvailabilityClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// List check available SKUs.
//
// location is resource location. parameters is check SKU Availablity POST body.
func (client CheckSkuAvailabilityClient) List(ctx context.Context, location string, parameters CheckSkuAvailabilityParameter) (result CheckSkuAvailabilityResultList, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.Skus", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "cognitiveservices.CheckSkuAvailabilityClient", "List")
}
req, err := client.ListPreparer(ctx, location, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.CheckSkuAvailabilityClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.CheckSkuAvailabilityClient", "List", resp, "Failure sending request")
return
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.CheckSkuAvailabilityClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client CheckSkuAvailabilityClient) ListPreparer(ctx context.Context, location string, parameters CheckSkuAvailabilityParameter) (*http.Request, error) {
pathParameters := map[string]interface{}{
"location": autorest.Encode("path", location),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-18"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/checkSkuAvailability", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client CheckSkuAvailabilityClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client CheckSkuAvailabilityClient) ListResponder(resp *http.Response) (result CheckSkuAvailabilityResultList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,51 @@
// Package cognitiveservices implements the Azure ARM Cognitiveservices service API version 2017-04-18.
//
// Cognitive Services Management Client
package cognitiveservices
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
const (
// DefaultBaseURI is the default URI used for the service Cognitiveservices
DefaultBaseURI = "https://management.azure.com"
)
// BaseClient is the base client for Cognitiveservices.
type BaseClient struct {
autorest.Client
BaseURI string
SubscriptionID string
}
// New creates an instance of the BaseClient client.
func New(subscriptionID string) BaseClient {
return NewWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewWithBaseURI creates an instance of the BaseClient client.
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
SubscriptionID: subscriptionID,
}
}
@@ -0,0 +1,614 @@
package cognitiveservices
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"encoding/json"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"net/http"
)
// KeyName enumerates the values for key name.
type KeyName string
const (
// Key1 ...
Key1 KeyName = "Key1"
// Key2 ...
Key2 KeyName = "Key2"
)
// Kind enumerates the values for kind.
type Kind string
const (
// Academic ...
Academic Kind = "Academic"
// BingAutosuggest ...
BingAutosuggest Kind = "Bing.Autosuggest"
// BingAutosuggestv7 ...
BingAutosuggestv7 Kind = "Bing.Autosuggest.v7"
// BingCustomSearch ...
BingCustomSearch Kind = "Bing.CustomSearch"
// BingSearch ...
BingSearch Kind = "Bing.Search"
// BingSearchv7 ...
BingSearchv7 Kind = "Bing.Search.v7"
// BingSpeech ...
BingSpeech Kind = "Bing.Speech"
// BingSpellCheck ...
BingSpellCheck Kind = "Bing.SpellCheck"
// BingSpellCheckv7 ...
BingSpellCheckv7 Kind = "Bing.SpellCheck.v7"
// ComputerVision ...
ComputerVision Kind = "ComputerVision"
// ContentModerator ...
ContentModerator Kind = "ContentModerator"
// CustomSpeech ...
CustomSpeech Kind = "CustomSpeech"
// Emotion ...
Emotion Kind = "Emotion"
// Face ...
Face Kind = "Face"
// LUIS ...
LUIS Kind = "LUIS"
// Recommendations ...
Recommendations Kind = "Recommendations"
// SpeakerRecognition ...
SpeakerRecognition Kind = "SpeakerRecognition"
// Speech ...
Speech Kind = "Speech"
// SpeechTranslation ...
SpeechTranslation Kind = "SpeechTranslation"
// TextAnalytics ...
TextAnalytics Kind = "TextAnalytics"
// TextTranslation ...
TextTranslation Kind = "TextTranslation"
// WebLM ...
WebLM Kind = "WebLM"
)
// ProvisioningState enumerates the values for provisioning state.
type ProvisioningState string
const (
// Creating ...
Creating ProvisioningState = "Creating"
// Deleting ...
Deleting ProvisioningState = "Deleting"
// Failed ...
Failed ProvisioningState = "Failed"
// Moving ...
Moving ProvisioningState = "Moving"
// ResolvingDNS ...
ResolvingDNS ProvisioningState = "ResolvingDNS"
// Succeeded ...
Succeeded ProvisioningState = "Succeeded"
)
// SkuName enumerates the values for sku name.
type SkuName string
const (
// F0 ...
F0 SkuName = "F0"
// P0 ...
P0 SkuName = "P0"
// P1 ...
P1 SkuName = "P1"
// P2 ...
P2 SkuName = "P2"
// S0 ...
S0 SkuName = "S0"
// S1 ...
S1 SkuName = "S1"
// S2 ...
S2 SkuName = "S2"
// S3 ...
S3 SkuName = "S3"
// S4 ...
S4 SkuName = "S4"
// S5 ...
S5 SkuName = "S5"
// S6 ...
S6 SkuName = "S6"
)
// SkuTier enumerates the values for sku tier.
type SkuTier string
const (
// Free ...
Free SkuTier = "Free"
// Premium ...
Premium SkuTier = "Premium"
// Standard ...
Standard SkuTier = "Standard"
)
// Account cognitive Services Account is an Azure resource representing the provisioned account, its type, location and
// SKU.
type Account struct {
autorest.Response `json:"-"`
// Etag - Entity Tag
Etag *string `json:"etag,omitempty"`
// ID - The id of the created account
ID *string `json:"id,omitempty"`
// Kind - Type of cognitive service account.
Kind *string `json:"kind,omitempty"`
// Location - The location of the resource
Location *string `json:"location,omitempty"`
// Name - The name of the created account
Name *string `json:"name,omitempty"`
// AccountProperties - Properties of Cognitive Services account.
*AccountProperties `json:"properties,omitempty"`
// Sku - The SKU of Cognitive Services account.
Sku *Sku `json:"sku,omitempty"`
// Tags - Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters.
Tags *map[string]*string `json:"tags,omitempty"`
// Type - Resource type
Type *string `json:"type,omitempty"`
}
// UnmarshalJSON is the custom unmarshaler for Account struct.
func (a *Account) UnmarshalJSON(body []byte) error {
var m map[string]*json.RawMessage
err := json.Unmarshal(body, &m)
if err != nil {
return err
}
var v *json.RawMessage
v = m["etag"]
if v != nil {
var etag string
err = json.Unmarshal(*m["etag"], &etag)
if err != nil {
return err
}
a.Etag = &etag
}
v = m["id"]
if v != nil {
var ID string
err = json.Unmarshal(*m["id"], &ID)
if err != nil {
return err
}
a.ID = &ID
}
v = m["kind"]
if v != nil {
var kind string
err = json.Unmarshal(*m["kind"], &kind)
if err != nil {
return err
}
a.Kind = &kind
}
v = m["location"]
if v != nil {
var location string
err = json.Unmarshal(*m["location"], &location)
if err != nil {
return err
}
a.Location = &location
}
v = m["name"]
if v != nil {
var name string
err = json.Unmarshal(*m["name"], &name)
if err != nil {
return err
}
a.Name = &name
}
v = m["properties"]
if v != nil {
var properties AccountProperties
err = json.Unmarshal(*m["properties"], &properties)
if err != nil {
return err
}
a.AccountProperties = &properties
}
v = m["sku"]
if v != nil {
var sku Sku
err = json.Unmarshal(*m["sku"], &sku)
if err != nil {
return err
}
a.Sku = &sku
}
v = m["tags"]
if v != nil {
var tags map[string]*string
err = json.Unmarshal(*m["tags"], &tags)
if err != nil {
return err
}
a.Tags = &tags
}
v = m["type"]
if v != nil {
var typeVar string
err = json.Unmarshal(*m["type"], &typeVar)
if err != nil {
return err
}
a.Type = &typeVar
}
return nil
}
// AccountCreateParameters the parameters to provide for the account.
type AccountCreateParameters struct {
// Sku - Required. Gets or sets the SKU of the resource.
Sku *Sku `json:"sku,omitempty"`
// Kind - Required. Gets or sets the Kind of the resource. Possible values include: 'Academic', 'BingAutosuggest', 'BingAutosuggestv7', 'BingCustomSearch', 'BingSearch', 'BingSearchv7', 'BingSpeech', 'BingSpellCheck', 'BingSpellCheckv7', 'ComputerVision', 'ContentModerator', 'CustomSpeech', 'Emotion', 'Face', 'LUIS', 'Recommendations', 'SpeakerRecognition', 'Speech', 'SpeechTranslation', 'TextAnalytics', 'TextTranslation', 'WebLM'
Kind Kind `json:"kind,omitempty"`
// Location - Required. Gets or sets the location of the resource. This will be one of the supported and registered Azure Geo Regions (e.g. West US, East US, Southeast Asia, etc.). The geo region of a resource cannot be changed once it is created, but if an identical geo region is specified on update the request will succeed.
Location *string `json:"location,omitempty"`
// Tags - Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters.
Tags *map[string]*string `json:"tags,omitempty"`
// Properties - Must exist in the request. Must be an empty object. Must not be null.
Properties *map[string]interface{} `json:"properties,omitempty"`
}
// AccountEnumerateSkusResult the list of cognitive services accounts operation response.
type AccountEnumerateSkusResult struct {
autorest.Response `json:"-"`
// Value - Gets the list of Cognitive Services accounts and their properties.
Value *[]ResourceAndSku `json:"value,omitempty"`
}
// AccountKeys the access keys for the cognitive services account.
type AccountKeys struct {
autorest.Response `json:"-"`
// Key1 - Gets the value of key 1.
Key1 *string `json:"key1,omitempty"`
// Key2 - Gets the value of key 2.
Key2 *string `json:"key2,omitempty"`
}
// AccountListResult the list of cognitive services accounts operation response.
type AccountListResult struct {
autorest.Response `json:"-"`
// NextLink - The link used to get the next page of accounts.
NextLink *string `json:"nextLink,omitempty"`
// Value - Gets the list of Cognitive Services accounts and their properties.
Value *[]Account `json:"value,omitempty"`
}
// AccountListResultIterator provides access to a complete listing of Account values.
type AccountListResultIterator struct {
i int
page AccountListResultPage
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *AccountListResultIterator) Next() error {
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err := iter.page.Next()
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter AccountListResultIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter AccountListResultIterator) Response() AccountListResult {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter AccountListResultIterator) Value() Account {
if !iter.page.NotDone() {
return Account{}
}
return iter.page.Values()[iter.i]
}
// IsEmpty returns true if the ListResult contains no values.
func (alr AccountListResult) IsEmpty() bool {
return alr.Value == nil || len(*alr.Value) == 0
}
// accountListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (alr AccountListResult) accountListResultPreparer() (*http.Request, error) {
if alr.NextLink == nil || len(to.String(alr.NextLink)) < 1 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(alr.NextLink)))
}
// AccountListResultPage contains a page of Account values.
type AccountListResultPage struct {
fn func(AccountListResult) (AccountListResult, error)
alr AccountListResult
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *AccountListResultPage) Next() error {
next, err := page.fn(page.alr)
if err != nil {
return err
}
page.alr = next
return nil
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page AccountListResultPage) NotDone() bool {
return !page.alr.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page AccountListResultPage) Response() AccountListResult {
return page.alr
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page AccountListResultPage) Values() []Account {
if page.alr.IsEmpty() {
return nil
}
return *page.alr.Value
}
// AccountProperties properties of Cognitive Services account.
type AccountProperties struct {
// ProvisioningState - Gets the status of the cognitive services account at the time the operation was called. Possible values include: 'Creating', 'ResolvingDNS', 'Moving', 'Deleting', 'Succeeded', 'Failed'
ProvisioningState ProvisioningState `json:"provisioningState,omitempty"`
// Endpoint - Endpoint of the created account.
Endpoint *string `json:"endpoint,omitempty"`
// InternalID - The internal identifier.
InternalID *string `json:"internalId,omitempty"`
}
// AccountUpdateParameters the parameters to provide for the account.
type AccountUpdateParameters struct {
// Sku - Gets or sets the SKU of the resource.
Sku *Sku `json:"sku,omitempty"`
// Tags - Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters.
Tags *map[string]*string `json:"tags,omitempty"`
}
// CheckSkuAvailabilityParameter check SKU availability parameter.
type CheckSkuAvailabilityParameter struct {
// Skus - The SKU of the resource.
Skus *[]SkuName `json:"skus,omitempty"`
// Kind - The Kind of the resource. Possible values include: 'Academic', 'BingAutosuggest', 'BingAutosuggestv7', 'BingCustomSearch', 'BingSearch', 'BingSearchv7', 'BingSpeech', 'BingSpellCheck', 'BingSpellCheckv7', 'ComputerVision', 'ContentModerator', 'CustomSpeech', 'Emotion', 'Face', 'LUIS', 'Recommendations', 'SpeakerRecognition', 'Speech', 'SpeechTranslation', 'TextAnalytics', 'TextTranslation', 'WebLM'
Kind Kind `json:"kind,omitempty"`
// Type - The Type of the resource.
Type *string `json:"type,omitempty"`
}
// CheckSkuAvailabilityResult check SKU availability result.
type CheckSkuAvailabilityResult struct {
// Kind - The Kind of the resource. Possible values include: 'Academic', 'BingAutosuggest', 'BingAutosuggestv7', 'BingCustomSearch', 'BingSearch', 'BingSearchv7', 'BingSpeech', 'BingSpellCheck', 'BingSpellCheckv7', 'ComputerVision', 'ContentModerator', 'CustomSpeech', 'Emotion', 'Face', 'LUIS', 'Recommendations', 'SpeakerRecognition', 'Speech', 'SpeechTranslation', 'TextAnalytics', 'TextTranslation', 'WebLM'
Kind Kind `json:"kind,omitempty"`
// Type - The Type of the resource.
Type *string `json:"type,omitempty"`
// SkuName - The SKU of Cognitive Services account. Possible values include: 'F0', 'P0', 'P1', 'P2', 'S0', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6'
SkuName SkuName `json:"skuName,omitempty"`
// SkuAvailable - Indicates the given SKU is available or not.
SkuAvailable *bool `json:"skuAvailable,omitempty"`
// Reason - Reason why the SKU is not available.
Reason *string `json:"reason,omitempty"`
// Message - Additional error message.
Message *string `json:"message,omitempty"`
}
// CheckSkuAvailabilityResultList check SKU availability result list.
type CheckSkuAvailabilityResultList struct {
autorest.Response `json:"-"`
// Value - Check SKU availability result list.
Value *[]CheckSkuAvailabilityResult `json:"value,omitempty"`
}
// Error cognitive Services error object.
type Error struct {
// Error - The error body.
Error *ErrorBody `json:"error,omitempty"`
}
// ErrorBody cognitive Services error body.
type ErrorBody struct {
// Code - error code
Code *string `json:"code,omitempty"`
// Message - error message
Message *string `json:"message,omitempty"`
}
// OperationDisplayInfo the operation supported by Cognitive Services.
type OperationDisplayInfo struct {
// Description - The description of the operation.
Description *string `json:"description,omitempty"`
// Operation - The action that users can perform, based on their permission level.
Operation *string `json:"operation,omitempty"`
// Provider - Service provider: Microsoft Cognitive Services.
Provider *string `json:"provider,omitempty"`
// Resource - Resource on which the operation is performed.
Resource *string `json:"resource,omitempty"`
}
// OperationEntity the operation supported by Cognitive Services.
type OperationEntity struct {
// Name - Operation name: {provider}/{resource}/{operation}.
Name *string `json:"name,omitempty"`
// Display - The operation supported by Cognitive Services.
Display *OperationDisplayInfo `json:"display,omitempty"`
// Origin - The origin of the operation.
Origin *string `json:"origin,omitempty"`
// Properties - Additional properties.
Properties *map[string]interface{} `json:"properties,omitempty"`
}
// OperationEntityListResult the list of cognitive services accounts operation response.
type OperationEntityListResult struct {
autorest.Response `json:"-"`
// NextLink - The link used to get the next page of operations.
NextLink *string `json:"nextLink,omitempty"`
// Value - The list of operations.
Value *[]OperationEntity `json:"value,omitempty"`
}
// OperationEntityListResultIterator provides access to a complete listing of OperationEntity values.
type OperationEntityListResultIterator struct {
i int
page OperationEntityListResultPage
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *OperationEntityListResultIterator) Next() error {
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err := iter.page.Next()
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter OperationEntityListResultIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter OperationEntityListResultIterator) Response() OperationEntityListResult {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter OperationEntityListResultIterator) Value() OperationEntity {
if !iter.page.NotDone() {
return OperationEntity{}
}
return iter.page.Values()[iter.i]
}
// IsEmpty returns true if the ListResult contains no values.
func (oelr OperationEntityListResult) IsEmpty() bool {
return oelr.Value == nil || len(*oelr.Value) == 0
}
// operationEntityListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (oelr OperationEntityListResult) operationEntityListResultPreparer() (*http.Request, error) {
if oelr.NextLink == nil || len(to.String(oelr.NextLink)) < 1 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(oelr.NextLink)))
}
// OperationEntityListResultPage contains a page of OperationEntity values.
type OperationEntityListResultPage struct {
fn func(OperationEntityListResult) (OperationEntityListResult, error)
oelr OperationEntityListResult
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *OperationEntityListResultPage) Next() error {
next, err := page.fn(page.oelr)
if err != nil {
return err
}
page.oelr = next
return nil
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page OperationEntityListResultPage) NotDone() bool {
return !page.oelr.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page OperationEntityListResultPage) Response() OperationEntityListResult {
return page.oelr
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page OperationEntityListResultPage) Values() []OperationEntity {
if page.oelr.IsEmpty() {
return nil
}
return *page.oelr.Value
}
// RegenerateKeyParameters regenerate key parameters.
type RegenerateKeyParameters struct {
// KeyName - key name to generate (Key1|Key2). Possible values include: 'Key1', 'Key2'
KeyName KeyName `json:"keyName,omitempty"`
}
// ResourceAndSku cognitive Services resource type and SKU.
type ResourceAndSku struct {
// ResourceType - Resource Namespace and Type
ResourceType *string `json:"resourceType,omitempty"`
// Sku - The SKU of Cognitive Services account.
Sku *Sku `json:"sku,omitempty"`
}
// Sku the SKU of the cognitive services account.
type Sku struct {
// Name - Gets or sets the sku name. Required for account creation, optional for update. Possible values include: 'F0', 'P0', 'P1', 'P2', 'S0', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6'
Name SkuName `json:"name,omitempty"`
// Tier - Gets the sku tier. This is based on the SKU name. Possible values include: 'Free', 'Standard', 'Premium'
Tier SkuTier `json:"tier,omitempty"`
}
@@ -0,0 +1,126 @@
package cognitiveservices
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// OperationsClient is the cognitive Services Management Client
type OperationsClient struct {
BaseClient
}
// NewOperationsClient creates an instance of the OperationsClient client.
func NewOperationsClient(subscriptionID string) OperationsClient {
return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client.
func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {
return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// List lists all the available Cognitive Services account operations.
func (client OperationsClient) List(ctx context.Context) (result OperationEntityListResultPage, err error) {
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.OperationsClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.oelr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cognitiveservices.OperationsClient", "List", resp, "Failure sending request")
return
}
result.oelr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.OperationsClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) {
const APIVersion = "2017-04-18"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/providers/Microsoft.CognitiveServices/operations"),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client OperationsClient) ListResponder(resp *http.Response) (result OperationEntityListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client OperationsClient) listNextResults(lastResults OperationEntityListResult) (result OperationEntityListResult, err error) {
req, err := lastResults.operationEntityListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "cognitiveservices.OperationsClient", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "cognitiveservices.OperationsClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cognitiveservices.OperationsClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client OperationsClient) ListComplete(ctx context.Context) (result OperationEntityListResultIterator, err error) {
result.page, err = client.List(ctx)
return
}
@@ -0,0 +1,28 @@
package cognitiveservices
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/v12.2.0-beta services"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v12.2.0-beta"
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,556 @@
package computervision
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"encoding/json"
"github.com/Azure/go-autorest/autorest"
"io"
)
// AzureRegions enumerates the values for azure regions.
type AzureRegions string
const (
// Australiaeast ...
Australiaeast AzureRegions = "australiaeast"
// Brazilsouth ...
Brazilsouth AzureRegions = "brazilsouth"
// Eastasia ...
Eastasia AzureRegions = "eastasia"
// Eastus ...
Eastus AzureRegions = "eastus"
// Eastus2 ...
Eastus2 AzureRegions = "eastus2"
// Northeurope ...
Northeurope AzureRegions = "northeurope"
// Southcentralus ...
Southcentralus AzureRegions = "southcentralus"
// Southeastasia ...
Southeastasia AzureRegions = "southeastasia"
// Westcentralus ...
Westcentralus AzureRegions = "westcentralus"
// Westeurope ...
Westeurope AzureRegions = "westeurope"
// Westus ...
Westus AzureRegions = "westus"
// Westus2 ...
Westus2 AzureRegions = "westus2"
)
// Details enumerates the values for details.
type Details string
const (
// Celebrities ...
Celebrities Details = "Celebrities"
// Landmarks ...
Landmarks Details = "Landmarks"
)
// DomainModels enumerates the values for domain models.
type DomainModels string
const (
// DomainModelsCelebrities ...
DomainModelsCelebrities DomainModels = "Celebrities"
// DomainModelsLandmarks ...
DomainModelsLandmarks DomainModels = "Landmarks"
)
// ErrorCodes enumerates the values for error codes.
type ErrorCodes string
const (
// BadArgument ...
BadArgument ErrorCodes = "BadArgument"
// FailedToProcess ...
FailedToProcess ErrorCodes = "FailedToProcess"
// InternalServerError ...
InternalServerError ErrorCodes = "InternalServerError"
// InvalidDetails ...
InvalidDetails ErrorCodes = "InvalidDetails"
// InvalidImageFormat ...
InvalidImageFormat ErrorCodes = "InvalidImageFormat"
// InvalidImageSize ...
InvalidImageSize ErrorCodes = "InvalidImageSize"
// InvalidImageURL ...
InvalidImageURL ErrorCodes = "InvalidImageUrl"
// NotSupportedImage ...
NotSupportedImage ErrorCodes = "NotSupportedImage"
// NotSupportedLanguage ...
NotSupportedLanguage ErrorCodes = "NotSupportedLanguage"
// NotSupportedVisualFeature ...
NotSupportedVisualFeature ErrorCodes = "NotSupportedVisualFeature"
// StorageException ...
StorageException ErrorCodes = "StorageException"
// Timeout ...
Timeout ErrorCodes = "Timeout"
// Unspecified ...
Unspecified ErrorCodes = "Unspecified"
)
// Gender enumerates the values for gender.
type Gender string
const (
// Female ...
Female Gender = "Female"
// Male ...
Male Gender = "Male"
)
// Language1 enumerates the values for language 1.
type Language1 string
const (
// En ...
En Language1 = "en"
// Zh ...
Zh Language1 = "zh"
)
// OcrLanguages enumerates the values for ocr languages.
type OcrLanguages string
const (
// OcrLanguagesAr ...
OcrLanguagesAr OcrLanguages = "ar"
// OcrLanguagesCs ...
OcrLanguagesCs OcrLanguages = "cs"
// OcrLanguagesDa ...
OcrLanguagesDa OcrLanguages = "da"
// OcrLanguagesDe ...
OcrLanguagesDe OcrLanguages = "de"
// OcrLanguagesEl ...
OcrLanguagesEl OcrLanguages = "el"
// OcrLanguagesEn ...
OcrLanguagesEn OcrLanguages = "en"
// OcrLanguagesEs ...
OcrLanguagesEs OcrLanguages = "es"
// OcrLanguagesFi ...
OcrLanguagesFi OcrLanguages = "fi"
// OcrLanguagesFr ...
OcrLanguagesFr OcrLanguages = "fr"
// OcrLanguagesHu ...
OcrLanguagesHu OcrLanguages = "hu"
// OcrLanguagesIt ...
OcrLanguagesIt OcrLanguages = "it"
// OcrLanguagesJa ...
OcrLanguagesJa OcrLanguages = "ja"
// OcrLanguagesKo ...
OcrLanguagesKo OcrLanguages = "ko"
// OcrLanguagesNb ...
OcrLanguagesNb OcrLanguages = "nb"
// OcrLanguagesNl ...
OcrLanguagesNl OcrLanguages = "nl"
// OcrLanguagesPl ...
OcrLanguagesPl OcrLanguages = "pl"
// OcrLanguagesPt ...
OcrLanguagesPt OcrLanguages = "pt"
// OcrLanguagesRo ...
OcrLanguagesRo OcrLanguages = "ro"
// OcrLanguagesRu ...
OcrLanguagesRu OcrLanguages = "ru"
// OcrLanguagesSk ...
OcrLanguagesSk OcrLanguages = "sk"
// OcrLanguagesSrCyrl ...
OcrLanguagesSrCyrl OcrLanguages = "sr-Cyrl"
// OcrLanguagesSrLatn ...
OcrLanguagesSrLatn OcrLanguages = "sr-Latn"
// OcrLanguagesSv ...
OcrLanguagesSv OcrLanguages = "sv"
// OcrLanguagesTr ...
OcrLanguagesTr OcrLanguages = "tr"
// OcrLanguagesUnk ...
OcrLanguagesUnk OcrLanguages = "unk"
// OcrLanguagesZhHans ...
OcrLanguagesZhHans OcrLanguages = "zh-Hans"
// OcrLanguagesZhHant ...
OcrLanguagesZhHant OcrLanguages = "zh-Hant"
)
// TextOperationStatusCodes enumerates the values for text operation status codes.
type TextOperationStatusCodes string
const (
// Failed ...
Failed TextOperationStatusCodes = "Failed"
// NotStarted ...
NotStarted TextOperationStatusCodes = "Not Started"
// Running ...
Running TextOperationStatusCodes = "Running"
// Succeeded ...
Succeeded TextOperationStatusCodes = "Succeeded"
)
// VisualFeatureTypes enumerates the values for visual feature types.
type VisualFeatureTypes string
const (
// VisualFeatureTypesAdult ...
VisualFeatureTypesAdult VisualFeatureTypes = "Adult"
// VisualFeatureTypesCategories ...
VisualFeatureTypesCategories VisualFeatureTypes = "Categories"
// VisualFeatureTypesColor ...
VisualFeatureTypesColor VisualFeatureTypes = "Color"
// VisualFeatureTypesDescription ...
VisualFeatureTypesDescription VisualFeatureTypes = "Description"
// VisualFeatureTypesFaces ...
VisualFeatureTypesFaces VisualFeatureTypes = "Faces"
// VisualFeatureTypesImageType ...
VisualFeatureTypesImageType VisualFeatureTypes = "ImageType"
// VisualFeatureTypesTags ...
VisualFeatureTypesTags VisualFeatureTypes = "Tags"
)
// AdultInfo an object describing whether the image contains adult-oriented content and/or is racy.
type AdultInfo struct {
// IsAdultContent - A value indicating if the image contains adult-oriented content.
IsAdultContent *bool `json:"isAdultContent,omitempty"`
// IsRacyContent - A value indicating if the image is race.
IsRacyContent *bool `json:"isRacyContent,omitempty"`
// AdultScore - Score from 0 to 1 that indicates how much of adult content is within the image.
AdultScore *float64 `json:"adultScore,omitempty"`
// RacyScore - Score from 0 to 1 that indicates how suggestive is the image.
RacyScore *float64 `json:"racyScore,omitempty"`
}
// Category an object describing identified category.
type Category struct {
// Name - Name of the category.
Name *string `json:"name,omitempty"`
// Score - Scoring of the category.
Score *float64 `json:"score,omitempty"`
// Detail - Additional category detail if available.
Detail *CategoryDetail `json:"detail,omitempty"`
}
// CategoryDetail an object describing additional category details.
type CategoryDetail struct {
// Celebrities - An array of celebrities if any identified.
Celebrities *[]CelebritiesModel `json:"celebrities,omitempty"`
}
// CelebritiesModel an object describing possible celebrity identification.
type CelebritiesModel struct {
// Name - Name of the celebrity.
Name *string `json:"name,omitempty"`
// Confidence - Level of confidence ranging from 0 to 1.
Confidence *float64 `json:"confidence,omitempty"`
FaceRectangle *FaceRectangle `json:"faceRectangle,omitempty"`
}
// ColorInfo an object providing additional metadata describing color attributes.
type ColorInfo struct {
// DominantColorForeground - Possible dominant foreground color.
DominantColorForeground *string `json:"dominantColorForeground,omitempty"`
// DominantColorBackground - Possible dominant background color.
DominantColorBackground *string `json:"dominantColorBackground,omitempty"`
// DominantColors - An array of possible dominant colors.
DominantColors *[]string `json:"dominantColors,omitempty"`
// AccentColor - Possible accent color.
AccentColor *string `json:"accentColor,omitempty"`
// IsBWImg - A value indicating if the image is black and white.
IsBWImg *bool `json:"isBWImg,omitempty"`
}
// DomainModelResult ...
type DomainModelResult struct {
// Celebrities - An array of possible celebritied identified in the image.
Celebrities *[]CelebritiesModel `json:"celebrities,omitempty"`
}
// DomainModelResults result of image analysis using a specific domain model including additional metadata.
type DomainModelResults struct {
autorest.Response `json:"-"`
// DomainModelResult - Result of the image analysis.
*DomainModelResult `json:"result,omitempty"`
// RequestID - Id of the REST API request.
RequestID *string `json:"requestId,omitempty"`
// Metadata - Additional image metadata
Metadata *ImageMetadata `json:"metadata,omitempty"`
}
// UnmarshalJSON is the custom unmarshaler for DomainModelResults struct.
func (dmr *DomainModelResults) UnmarshalJSON(body []byte) error {
var m map[string]*json.RawMessage
err := json.Unmarshal(body, &m)
if err != nil {
return err
}
var v *json.RawMessage
v = m["result"]
if v != nil {
var resultVar DomainModelResult
err = json.Unmarshal(*m["result"], &resultVar)
if err != nil {
return err
}
dmr.DomainModelResult = &resultVar
}
v = m["requestId"]
if v != nil {
var requestID string
err = json.Unmarshal(*m["requestId"], &requestID)
if err != nil {
return err
}
dmr.RequestID = &requestID
}
v = m["metadata"]
if v != nil {
var metadata ImageMetadata
err = json.Unmarshal(*m["metadata"], &metadata)
if err != nil {
return err
}
dmr.Metadata = &metadata
}
return nil
}
// Error ...
type Error struct {
// Code - The error code. Possible values include: 'InvalidImageURL', 'InvalidImageFormat', 'InvalidImageSize', 'NotSupportedVisualFeature', 'NotSupportedImage', 'InvalidDetails', 'NotSupportedLanguage', 'BadArgument', 'FailedToProcess', 'Timeout', 'InternalServerError', 'Unspecified', 'StorageException'
Code ErrorCodes `json:"code,omitempty"`
// Message - A message explaining the error reported by the service.
Message *string `json:"message,omitempty"`
// RequestID - A unique request identifier.
RequestID *string `json:"requestId,omitempty"`
}
// FaceDescription an object describing a face identified in the image.
type FaceDescription struct {
// Age - Possible age of the face.
Age *int32 `json:"age,omitempty"`
// Gender - Possible gender of the face. Possible values include: 'Male', 'Female'
Gender Gender `json:"gender,omitempty"`
FaceRectangle *FaceRectangle `json:"faceRectangle,omitempty"`
}
// FaceRectangle an object describing face rectangle.
type FaceRectangle struct {
// Left - X-coordinate of the top left point of the face.
Left *int32 `json:"left,omitempty"`
// Top - Y-coordinate of the top left point of the face.
Top *int32 `json:"top,omitempty"`
// Width - Width measured from the top-left point of the face.
Width *int32 `json:"width,omitempty"`
// Height - Height measured from the top-left point of the face.
Height *int32 `json:"height,omitempty"`
}
// ImageAnalysis result of AnalyzeImage operation.
type ImageAnalysis struct {
autorest.Response `json:"-"`
// Categories - An array indicating identified categories.
Categories *[]Category `json:"categories,omitempty"`
// Adult - A property scoring on whether the image is adult-oriented and/or racy.
Adult *AdultInfo `json:"adult,omitempty"`
// Color - A property scoring on color spectrums.
Color *ColorInfo `json:"color,omitempty"`
// ImageType - A property indicating type of image (whether it's clipart or line drawing)
ImageType *ImageType `json:"imageType,omitempty"`
// Tags - A list of tags with confidence level.
Tags *[]ImageTag `json:"tags,omitempty"`
// Description - Description of the image.
Description *ImageDescriptionDetails `json:"description,omitempty"`
// Faces - An array of possible faces within the image.
Faces *[]FaceDescription `json:"faces,omitempty"`
// RequestID - Id of the request for tracking purposes.
RequestID *string `json:"requestId,omitempty"`
// Metadata - Image metadata
Metadata *ImageMetadata `json:"metadata,omitempty"`
}
// ImageCaption an image caption, i.e. a brief description of what the image depicts.
type ImageCaption struct {
// Text - The text of the caption
Text *string `json:"text,omitempty"`
// Confidence - The level of confidence the service has in the caption
Confidence *float64 `json:"confidence,omitempty"`
}
// ImageDescription a collection of content tags, along with a list of captions sorted by confidence level, and image
// metadata.
type ImageDescription struct {
autorest.Response `json:"-"`
*ImageDescriptionDetails `json:"description,omitempty"`
}
// UnmarshalJSON is the custom unmarshaler for ImageDescription struct.
func (ID *ImageDescription) UnmarshalJSON(body []byte) error {
var m map[string]*json.RawMessage
err := json.Unmarshal(body, &m)
if err != nil {
return err
}
var v *json.RawMessage
v = m["description"]
if v != nil {
var description ImageDescriptionDetails
err = json.Unmarshal(*m["description"], &description)
if err != nil {
return err
}
ID.ImageDescriptionDetails = &description
}
return nil
}
// ImageDescriptionDetails a collection of content tags, along with a list of captions sorted by confidence level, and
// image metadata.
type ImageDescriptionDetails struct {
// Tags - A collection of image tags.
Tags *[]string `json:"tags,omitempty"`
// Captions - A list of captions, sorted by confidence level.
Captions *[]ImageCaption `json:"captions,omitempty"`
// RequestID - Id of the REST API request.
RequestID *string `json:"requestId,omitempty"`
// Metadata - Image metadata
Metadata *ImageMetadata `json:"metadata,omitempty"`
}
// ImageMetadata image metadata
type ImageMetadata struct {
// Width - Image width
Width *int32 `json:"width,omitempty"`
// Height - Image height
Height *int32 `json:"height,omitempty"`
// Format - Image format
Format *string `json:"format,omitempty"`
}
// ImageTag an image caption, i.e. a brief description of what the image depicts.
type ImageTag struct {
// Name - The tag value
Name *string `json:"name,omitempty"`
// Confidence - The level of confidence the service has in the caption
Confidence *float64 `json:"confidence,omitempty"`
}
// ImageType an object providing possible image types and matching confidence levels.
type ImageType struct {
// ClipArtType - Confidence level that the image is a clip art.
ClipArtType *float64 `json:"clipArtType,omitempty"`
// LineDrawingType - Confidence level that the image is a line drawing.
LineDrawingType *float64 `json:"lineDrawingType,omitempty"`
}
// ImageURL ...
type ImageURL struct {
URL *string `json:"url,omitempty"`
}
// Line ...
type Line struct {
BoundingBox *[]int32 `json:"boundingBox,omitempty"`
Text *string `json:"text,omitempty"`
Words *[]Word `json:"words,omitempty"`
}
// ListModelsResult result of the List Domain Models operation.
type ListModelsResult struct {
autorest.Response `json:"-"`
// ModelsProperty - An array of supported models.
ModelsProperty *[]ModelDescription `json:"models,omitempty"`
}
// ModelDescription an object describing supported model by name and categories.
type ModelDescription struct {
Name *string `json:"name,omitempty"`
Categories *[]string `json:"categories,omitempty"`
}
// OcrLine an object describing a single recognized line of text.
type OcrLine struct {
// BoundingBox - Bounding box of a recognized line. The four integers represent the x-coordinate of the left edge, the y-coordinate of the top edge, width, and height of the bounding box, in the coordinate system of the input image, after it has been rotated around its center according to the detected text angle (see textAngle property), with the origin at the top-left corner, and the y-axis pointing down.
BoundingBox *string `json:"boundingBox,omitempty"`
// Words - An array of objects, where each object represents a recognized word.
Words *[]OcrWord `json:"words,omitempty"`
}
// OcrRegion a region consists of multiple lines (e.g. a column of text in a multi-column document).
type OcrRegion struct {
// BoundingBox - Bounding box of a recognized region. The four integers represent the x-coordinate of the left edge, the y-coordinate of the top edge, width, and height of the bounding box, in the coordinate system of the input image, after it has been rotated around its center according to the detected text angle (see textAngle property), with the origin at the top-left corner, and the y-axis pointing down.
BoundingBox *string `json:"boundingBox,omitempty"`
Lines *[]OcrLine `json:"lines,omitempty"`
}
// OcrResult ...
type OcrResult struct {
autorest.Response `json:"-"`
Language *OcrResult `json:"language,omitempty"`
// TextAngle - The angle, in degrees, of the detected text with respect to the closest horizontal or vertical direction. After rotating the input image clockwise by this angle, the recognized text lines become horizontal or vertical. In combination with the orientation property it can be used to overlay recognition results correctly on the original image, by rotating either the original image or recognition results by a suitable angle around the center of the original image. If the angle cannot be confidently detected, this property is not present. If the image contains text at different angles, only part of the text will be recognized correctly.
TextAngle *float64 `json:"textAngle,omitempty"`
// Orientation - Orientation of the text recognized in the image. The value (up,down,left, or right) refers to the direction that the top of the recognized text is facing, after the image has been rotated around its center according to the detected text angle (see textAngle property).
Orientation *string `json:"orientation,omitempty"`
// Regions - An array of objects, where each object represents a region of recognized text.
Regions *[]OcrRegion `json:"regions,omitempty"`
}
// OcrWord information on a recognized word.
type OcrWord struct {
// BoundingBox - Bounding box of a recognized word. The four integers represent the x-coordinate of the left edge, the y-coordinate of the top edge, width, and height of the bounding box, in the coordinate system of the input image, after it has been rotated around its center according to the detected text angle (see textAngle property), with the origin at the top-left corner, and the y-axis pointing down.
BoundingBox *string `json:"boundingBox,omitempty"`
// Text - String value of a recognized word.
Text *string `json:"text,omitempty"`
}
// ReadCloser ...
type ReadCloser struct {
autorest.Response `json:"-"`
Value *io.ReadCloser `json:"value,omitempty"`
}
// RecognitionResult ...
type RecognitionResult struct {
Lines *[]Line `json:"lines,omitempty"`
}
// TagResult the results of a image tag operation, including any tags and image metadata.
type TagResult struct {
autorest.Response `json:"-"`
// Tags - A list of tags with confidence level.
Tags *[]ImageTag `json:"tags,omitempty"`
// RequestID - Id of the REST API request.
RequestID *string `json:"requestId,omitempty"`
// Metadata - Image metadata
Metadata *ImageMetadata `json:"metadata,omitempty"`
}
// TextOperationResult ...
type TextOperationResult struct {
autorest.Response `json:"-"`
// Status - Status of the text operation. Possible values include: 'NotStarted', 'Running', 'Failed', 'Succeeded'
Status TextOperationStatusCodes `json:"status,omitempty"`
RecognitionResult *RecognitionResult `json:"recognitionResult,omitempty"`
}
// Word ...
type Word struct {
BoundingBox *[]int32 `json:"boundingBox,omitempty"`
Text *string `json:"text,omitempty"`
}
@@ -0,0 +1,28 @@
package computervision
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/v12.2.0-beta services"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v12.2.0-beta"
}
@@ -0,0 +1,59 @@
// Package contentmoderator implements the Azure ARM Contentmoderator service API version 1.0.
//
// You use the API to scan your content as it is generated. Content Moderator then processes your content and sends the
// results along with relevant information either back to your systems or to the built-in review tool. You can use this
// information to take decisions e.g. take it down, send to human judge, etc.
//
// When using the API, images need to have a minimum of 128 pixels and a maximum file size of 4MB.
// Text can be at most 1024 characters long.
// If the content passed to the text API or the image API exceeds the size limits, the API will return an error code
// that informs about the issue.
//
// This API is currently available in:
//
// * West US - westus.api.cognitive.microsoft.com
// * East US 2 - eastus2.api.cognitive.microsoft.com
// * West Central US - westcentralus.api.cognitive.microsoft.com
// * West Europe - westeurope.api.cognitive.microsoft.com
// * Southeast Asia - southeastasia.api.cognitive.microsoft.com .
package contentmoderator
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
// BaseClient is the base client for Contentmoderator.
type BaseClient struct {
autorest.Client
BaseURL AzureRegionBaseURL
}
// New creates an instance of the BaseClient client.
func New(baseURL AzureRegionBaseURL) BaseClient {
return NewWithoutDefaults(baseURL)
}
// NewWithoutDefaults creates an instance of the BaseClient client.
func NewWithoutDefaults(baseURL AzureRegionBaseURL) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURL: baseURL,
}
}
@@ -0,0 +1,910 @@
package contentmoderator
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"io"
"net/http"
)
// ImageModerationClient is the you use the API to scan your content as it is generated. Content Moderator then
// processes your content and sends the results along with relevant information either back to your systems or to the
// built-in review tool. You can use this information to take decisions e.g. take it down, send to human judge, etc.
//
// When using the API, images need to have a minimum of 128 pixels and a maximum file size of 4MB.
// Text can be at most 1024 characters long.
// If the content passed to the text API or the image API exceeds the size limits, the API will return an error code
// that informs about the issue.
//
// This API is currently available in:
//
// * West US - westus.api.cognitive.microsoft.com
// * East US 2 - eastus2.api.cognitive.microsoft.com
// * West Central US - westcentralus.api.cognitive.microsoft.com
// * West Europe - westeurope.api.cognitive.microsoft.com
// * Southeast Asia - southeastasia.api.cognitive.microsoft.com .
type ImageModerationClient struct {
BaseClient
}
// NewImageModerationClient creates an instance of the ImageModerationClient client.
func NewImageModerationClient(baseURL AzureRegionBaseURL) ImageModerationClient {
return ImageModerationClient{New(baseURL)}
}
// EvaluateFileInput returns probabilities of the image containing racy or adult content.
//
// imageStream is the image file. imageStream will be closed upon successful return. Callers should ensure closure when
// receiving an error.cacheImage is whether to retain the submitted image for future use; defaults to false if omitted.
func (client ImageModerationClient) EvaluateFileInput(ctx context.Context, imageStream io.ReadCloser, cacheImage *bool) (result Evaluate, err error) {
req, err := client.EvaluateFileInputPreparer(ctx, imageStream, cacheImage)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "EvaluateFileInput", nil, "Failure preparing request")
return
}
resp, err := client.EvaluateFileInputSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "EvaluateFileInput", resp, "Failure sending request")
return
}
result, err = client.EvaluateFileInputResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "EvaluateFileInput", resp, "Failure responding to request")
}
return
}
// EvaluateFileInputPreparer prepares the EvaluateFileInput request.
func (client ImageModerationClient) EvaluateFileInputPreparer(ctx context.Context, imageStream io.ReadCloser, cacheImage *bool) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
queryParameters := map[string]interface{}{}
if cacheImage != nil {
queryParameters["CacheImage"] = autorest.Encode("query", *cacheImage)
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/moderate/v1.0/ProcessImage/Evaluate"),
autorest.WithFile(imageStream),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// EvaluateFileInputSender sends the EvaluateFileInput request. The method will close the
// http.Response Body if it receives an error.
func (client ImageModerationClient) EvaluateFileInputSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// EvaluateFileInputResponder handles the response to the EvaluateFileInput request. The method always
// closes the http.Response Body.
func (client ImageModerationClient) EvaluateFileInputResponder(resp *http.Response) (result Evaluate, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// EvaluateMethod returns probabilities of the image containing racy or adult content.
//
// cacheImage is whether to retain the submitted image for future use; defaults to false if omitted.
func (client ImageModerationClient) EvaluateMethod(ctx context.Context, cacheImage *bool) (result Evaluate, err error) {
req, err := client.EvaluateMethodPreparer(ctx, cacheImage)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "EvaluateMethod", nil, "Failure preparing request")
return
}
resp, err := client.EvaluateMethodSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "EvaluateMethod", resp, "Failure sending request")
return
}
result, err = client.EvaluateMethodResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "EvaluateMethod", resp, "Failure responding to request")
}
return
}
// EvaluateMethodPreparer prepares the EvaluateMethod request.
func (client ImageModerationClient) EvaluateMethodPreparer(ctx context.Context, cacheImage *bool) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
queryParameters := map[string]interface{}{}
if cacheImage != nil {
queryParameters["CacheImage"] = autorest.Encode("query", *cacheImage)
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/moderate/v1.0/ProcessImage/Evaluate"),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// EvaluateMethodSender sends the EvaluateMethod request. The method will close the
// http.Response Body if it receives an error.
func (client ImageModerationClient) EvaluateMethodSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// EvaluateMethodResponder handles the response to the EvaluateMethod request. The method always
// closes the http.Response Body.
func (client ImageModerationClient) EvaluateMethodResponder(resp *http.Response) (result Evaluate, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// EvaluateURLInput returns probabilities of the image containing racy or adult content.
//
// contentType is the content type. imageURL is the image url. cacheImage is whether to retain the submitted image for
// future use; defaults to false if omitted.
func (client ImageModerationClient) EvaluateURLInput(ctx context.Context, contentType string, imageURL BodyModel, cacheImage *bool) (result Evaluate, err error) {
req, err := client.EvaluateURLInputPreparer(ctx, contentType, imageURL, cacheImage)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "EvaluateURLInput", nil, "Failure preparing request")
return
}
resp, err := client.EvaluateURLInputSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "EvaluateURLInput", resp, "Failure sending request")
return
}
result, err = client.EvaluateURLInputResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "EvaluateURLInput", resp, "Failure responding to request")
}
return
}
// EvaluateURLInputPreparer prepares the EvaluateURLInput request.
func (client ImageModerationClient) EvaluateURLInputPreparer(ctx context.Context, contentType string, imageURL BodyModel, cacheImage *bool) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
queryParameters := map[string]interface{}{}
if cacheImage != nil {
queryParameters["CacheImage"] = autorest.Encode("query", *cacheImage)
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/moderate/v1.0/ProcessImage/Evaluate"),
autorest.WithJSON(imageURL),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("Content-Type", autorest.String(contentType)))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// EvaluateURLInputSender sends the EvaluateURLInput request. The method will close the
// http.Response Body if it receives an error.
func (client ImageModerationClient) EvaluateURLInputSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// EvaluateURLInputResponder handles the response to the EvaluateURLInput request. The method always
// closes the http.Response Body.
func (client ImageModerationClient) EvaluateURLInputResponder(resp *http.Response) (result Evaluate, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// FindFaces returns the list of faces found.
//
// cacheImage is whether to retain the submitted image for future use; defaults to false if omitted.
func (client ImageModerationClient) FindFaces(ctx context.Context, cacheImage *bool) (result FoundFaces, err error) {
req, err := client.FindFacesPreparer(ctx, cacheImage)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "FindFaces", nil, "Failure preparing request")
return
}
resp, err := client.FindFacesSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "FindFaces", resp, "Failure sending request")
return
}
result, err = client.FindFacesResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "FindFaces", resp, "Failure responding to request")
}
return
}
// FindFacesPreparer prepares the FindFaces request.
func (client ImageModerationClient) FindFacesPreparer(ctx context.Context, cacheImage *bool) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
queryParameters := map[string]interface{}{}
if cacheImage != nil {
queryParameters["CacheImage"] = autorest.Encode("query", *cacheImage)
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/moderate/v1.0/ProcessImage/FindFaces"),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// FindFacesSender sends the FindFaces request. The method will close the
// http.Response Body if it receives an error.
func (client ImageModerationClient) FindFacesSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// FindFacesResponder handles the response to the FindFaces request. The method always
// closes the http.Response Body.
func (client ImageModerationClient) FindFacesResponder(resp *http.Response) (result FoundFaces, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// FindFacesFileInput returns the list of faces found.
//
// imageStream is the image file. imageStream will be closed upon successful return. Callers should ensure closure when
// receiving an error.cacheImage is whether to retain the submitted image for future use; defaults to false if omitted.
func (client ImageModerationClient) FindFacesFileInput(ctx context.Context, imageStream io.ReadCloser, cacheImage *bool) (result FoundFaces, err error) {
req, err := client.FindFacesFileInputPreparer(ctx, imageStream, cacheImage)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "FindFacesFileInput", nil, "Failure preparing request")
return
}
resp, err := client.FindFacesFileInputSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "FindFacesFileInput", resp, "Failure sending request")
return
}
result, err = client.FindFacesFileInputResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "FindFacesFileInput", resp, "Failure responding to request")
}
return
}
// FindFacesFileInputPreparer prepares the FindFacesFileInput request.
func (client ImageModerationClient) FindFacesFileInputPreparer(ctx context.Context, imageStream io.ReadCloser, cacheImage *bool) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
queryParameters := map[string]interface{}{}
if cacheImage != nil {
queryParameters["CacheImage"] = autorest.Encode("query", *cacheImage)
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/moderate/v1.0/ProcessImage/FindFaces"),
autorest.WithFile(imageStream),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// FindFacesFileInputSender sends the FindFacesFileInput request. The method will close the
// http.Response Body if it receives an error.
func (client ImageModerationClient) FindFacesFileInputSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// FindFacesFileInputResponder handles the response to the FindFacesFileInput request. The method always
// closes the http.Response Body.
func (client ImageModerationClient) FindFacesFileInputResponder(resp *http.Response) (result FoundFaces, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// FindFacesURLInput returns the list of faces found.
//
// contentType is the content type. imageURL is the image url. cacheImage is whether to retain the submitted image for
// future use; defaults to false if omitted.
func (client ImageModerationClient) FindFacesURLInput(ctx context.Context, contentType string, imageURL BodyModel, cacheImage *bool) (result FoundFaces, err error) {
req, err := client.FindFacesURLInputPreparer(ctx, contentType, imageURL, cacheImage)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "FindFacesURLInput", nil, "Failure preparing request")
return
}
resp, err := client.FindFacesURLInputSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "FindFacesURLInput", resp, "Failure sending request")
return
}
result, err = client.FindFacesURLInputResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "FindFacesURLInput", resp, "Failure responding to request")
}
return
}
// FindFacesURLInputPreparer prepares the FindFacesURLInput request.
func (client ImageModerationClient) FindFacesURLInputPreparer(ctx context.Context, contentType string, imageURL BodyModel, cacheImage *bool) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
queryParameters := map[string]interface{}{}
if cacheImage != nil {
queryParameters["CacheImage"] = autorest.Encode("query", *cacheImage)
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/moderate/v1.0/ProcessImage/FindFaces"),
autorest.WithJSON(imageURL),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("Content-Type", autorest.String(contentType)))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// FindFacesURLInputSender sends the FindFacesURLInput request. The method will close the
// http.Response Body if it receives an error.
func (client ImageModerationClient) FindFacesURLInputSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// FindFacesURLInputResponder handles the response to the FindFacesURLInput request. The method always
// closes the http.Response Body.
func (client ImageModerationClient) FindFacesURLInputResponder(resp *http.Response) (result FoundFaces, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// MatchFileInput fuzzily match an image against one of your custom Image Lists. You can create and manage your custom
// image lists using <a href="/docs/services/578ff44d2703741568569ab9/operations/578ff7b12703741568569abe">this</a>
// API.
//
// Returns ID and tags of matching image.<br/>
// <br/>
// Note: Refresh Index must be run on the corresponding Image List before additions and removals are reflected in the
// response.
//
// imageStream is the image file. imageStream will be closed upon successful return. Callers should ensure closure when
// receiving an error.listID is the list Id. cacheImage is whether to retain the submitted image for future use;
// defaults to false if omitted.
func (client ImageModerationClient) MatchFileInput(ctx context.Context, imageStream io.ReadCloser, listID string, cacheImage *bool) (result MatchResponse, err error) {
req, err := client.MatchFileInputPreparer(ctx, imageStream, listID, cacheImage)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "MatchFileInput", nil, "Failure preparing request")
return
}
resp, err := client.MatchFileInputSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "MatchFileInput", resp, "Failure sending request")
return
}
result, err = client.MatchFileInputResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "MatchFileInput", resp, "Failure responding to request")
}
return
}
// MatchFileInputPreparer prepares the MatchFileInput request.
func (client ImageModerationClient) MatchFileInputPreparer(ctx context.Context, imageStream io.ReadCloser, listID string, cacheImage *bool) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
queryParameters := map[string]interface{}{}
if len(listID) > 0 {
queryParameters["listId"] = autorest.Encode("query", listID)
}
if cacheImage != nil {
queryParameters["CacheImage"] = autorest.Encode("query", *cacheImage)
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/moderate/v1.0/ProcessImage/Match"),
autorest.WithFile(imageStream),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// MatchFileInputSender sends the MatchFileInput request. The method will close the
// http.Response Body if it receives an error.
func (client ImageModerationClient) MatchFileInputSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// MatchFileInputResponder handles the response to the MatchFileInput request. The method always
// closes the http.Response Body.
func (client ImageModerationClient) MatchFileInputResponder(resp *http.Response) (result MatchResponse, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// MatchMethod fuzzily match an image against one of your custom Image Lists. You can create and manage your custom
// image lists using <a href="/docs/services/578ff44d2703741568569ab9/operations/578ff7b12703741568569abe">this</a>
// API.
//
// Returns ID and tags of matching image.<br/>
// <br/>
// Note: Refresh Index must be run on the corresponding Image List before additions and removals are reflected in the
// response.
//
// listID is the list Id. cacheImage is whether to retain the submitted image for future use; defaults to false if
// omitted.
func (client ImageModerationClient) MatchMethod(ctx context.Context, listID string, cacheImage *bool) (result MatchResponse, err error) {
req, err := client.MatchMethodPreparer(ctx, listID, cacheImage)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "MatchMethod", nil, "Failure preparing request")
return
}
resp, err := client.MatchMethodSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "MatchMethod", resp, "Failure sending request")
return
}
result, err = client.MatchMethodResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "MatchMethod", resp, "Failure responding to request")
}
return
}
// MatchMethodPreparer prepares the MatchMethod request.
func (client ImageModerationClient) MatchMethodPreparer(ctx context.Context, listID string, cacheImage *bool) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
queryParameters := map[string]interface{}{}
if len(listID) > 0 {
queryParameters["listId"] = autorest.Encode("query", listID)
}
if cacheImage != nil {
queryParameters["CacheImage"] = autorest.Encode("query", *cacheImage)
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/moderate/v1.0/ProcessImage/Match"),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// MatchMethodSender sends the MatchMethod request. The method will close the
// http.Response Body if it receives an error.
func (client ImageModerationClient) MatchMethodSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// MatchMethodResponder handles the response to the MatchMethod request. The method always
// closes the http.Response Body.
func (client ImageModerationClient) MatchMethodResponder(resp *http.Response) (result MatchResponse, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// MatchURLInput fuzzily match an image against one of your custom Image Lists. You can create and manage your custom
// image lists using <a href="/docs/services/578ff44d2703741568569ab9/operations/578ff7b12703741568569abe">this</a>
// API.
//
// Returns ID and tags of matching image.<br/>
// <br/>
// Note: Refresh Index must be run on the corresponding Image List before additions and removals are reflected in the
// response.
//
// contentType is the content type. imageURL is the image url. listID is the list Id. cacheImage is whether to retain
// the submitted image for future use; defaults to false if omitted.
func (client ImageModerationClient) MatchURLInput(ctx context.Context, contentType string, imageURL BodyModel, listID string, cacheImage *bool) (result MatchResponse, err error) {
req, err := client.MatchURLInputPreparer(ctx, contentType, imageURL, listID, cacheImage)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "MatchURLInput", nil, "Failure preparing request")
return
}
resp, err := client.MatchURLInputSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "MatchURLInput", resp, "Failure sending request")
return
}
result, err = client.MatchURLInputResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "MatchURLInput", resp, "Failure responding to request")
}
return
}
// MatchURLInputPreparer prepares the MatchURLInput request.
func (client ImageModerationClient) MatchURLInputPreparer(ctx context.Context, contentType string, imageURL BodyModel, listID string, cacheImage *bool) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
queryParameters := map[string]interface{}{}
if len(listID) > 0 {
queryParameters["listId"] = autorest.Encode("query", listID)
}
if cacheImage != nil {
queryParameters["CacheImage"] = autorest.Encode("query", *cacheImage)
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/moderate/v1.0/ProcessImage/Match"),
autorest.WithJSON(imageURL),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("Content-Type", autorest.String(contentType)))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// MatchURLInputSender sends the MatchURLInput request. The method will close the
// http.Response Body if it receives an error.
func (client ImageModerationClient) MatchURLInputSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// MatchURLInputResponder handles the response to the MatchURLInput request. The method always
// closes the http.Response Body.
func (client ImageModerationClient) MatchURLInputResponder(resp *http.Response) (result MatchResponse, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// OCRFileInput returns any text found in the image for the language specified. If no language is specified in input
// then the detection defaults to English.
//
// language is language of the terms. imageStream is the image file. imageStream will be closed upon successful return.
// Callers should ensure closure when receiving an error.cacheImage is whether to retain the submitted image for future
// use; defaults to false if omitted. enhanced is when set to True, the image goes through additional processing to
// come with additional candidates.
//
// image/tiff is not supported when enhanced is set to true
//
// Note: This impacts the response time.
func (client ImageModerationClient) OCRFileInput(ctx context.Context, language string, imageStream io.ReadCloser, cacheImage *bool, enhanced *bool) (result OCR, err error) {
req, err := client.OCRFileInputPreparer(ctx, language, imageStream, cacheImage, enhanced)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "OCRFileInput", nil, "Failure preparing request")
return
}
resp, err := client.OCRFileInputSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "OCRFileInput", resp, "Failure sending request")
return
}
result, err = client.OCRFileInputResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "OCRFileInput", resp, "Failure responding to request")
}
return
}
// OCRFileInputPreparer prepares the OCRFileInput request.
func (client ImageModerationClient) OCRFileInputPreparer(ctx context.Context, language string, imageStream io.ReadCloser, cacheImage *bool, enhanced *bool) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
queryParameters := map[string]interface{}{
"language": autorest.Encode("query", language),
}
if cacheImage != nil {
queryParameters["CacheImage"] = autorest.Encode("query", *cacheImage)
}
if enhanced != nil {
queryParameters["enhanced"] = autorest.Encode("query", *enhanced)
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/moderate/v1.0/ProcessImage/OCR"),
autorest.WithFile(imageStream),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// OCRFileInputSender sends the OCRFileInput request. The method will close the
// http.Response Body if it receives an error.
func (client ImageModerationClient) OCRFileInputSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// OCRFileInputResponder handles the response to the OCRFileInput request. The method always
// closes the http.Response Body.
func (client ImageModerationClient) OCRFileInputResponder(resp *http.Response) (result OCR, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// OCRMethod returns any text found in the image for the language specified. If no language is specified in input then
// the detection defaults to English.
//
// language is language of the terms. cacheImage is whether to retain the submitted image for future use; defaults to
// false if omitted. enhanced is when set to True, the image goes through additional processing to come with additional
// candidates.
//
// image/tiff is not supported when enhanced is set to true
//
// Note: This impacts the response time.
func (client ImageModerationClient) OCRMethod(ctx context.Context, language string, cacheImage *bool, enhanced *bool) (result OCR, err error) {
req, err := client.OCRMethodPreparer(ctx, language, cacheImage, enhanced)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "OCRMethod", nil, "Failure preparing request")
return
}
resp, err := client.OCRMethodSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "OCRMethod", resp, "Failure sending request")
return
}
result, err = client.OCRMethodResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "OCRMethod", resp, "Failure responding to request")
}
return
}
// OCRMethodPreparer prepares the OCRMethod request.
func (client ImageModerationClient) OCRMethodPreparer(ctx context.Context, language string, cacheImage *bool, enhanced *bool) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
queryParameters := map[string]interface{}{
"language": autorest.Encode("query", language),
}
if cacheImage != nil {
queryParameters["CacheImage"] = autorest.Encode("query", *cacheImage)
}
if enhanced != nil {
queryParameters["enhanced"] = autorest.Encode("query", *enhanced)
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/moderate/v1.0/ProcessImage/OCR"),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// OCRMethodSender sends the OCRMethod request. The method will close the
// http.Response Body if it receives an error.
func (client ImageModerationClient) OCRMethodSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// OCRMethodResponder handles the response to the OCRMethod request. The method always
// closes the http.Response Body.
func (client ImageModerationClient) OCRMethodResponder(resp *http.Response) (result OCR, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// OCRURLInput returns any text found in the image for the language specified. If no language is specified in input
// then the detection defaults to English.
//
// language is language of the terms. contentType is the content type. imageURL is the image url. cacheImage is whether
// to retain the submitted image for future use; defaults to false if omitted. enhanced is when set to True, the image
// goes through additional processing to come with additional candidates.
//
// image/tiff is not supported when enhanced is set to true
//
// Note: This impacts the response time.
func (client ImageModerationClient) OCRURLInput(ctx context.Context, language string, contentType string, imageURL BodyModel, cacheImage *bool, enhanced *bool) (result OCR, err error) {
req, err := client.OCRURLInputPreparer(ctx, language, contentType, imageURL, cacheImage, enhanced)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "OCRURLInput", nil, "Failure preparing request")
return
}
resp, err := client.OCRURLInputSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "OCRURLInput", resp, "Failure sending request")
return
}
result, err = client.OCRURLInputResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ImageModerationClient", "OCRURLInput", resp, "Failure responding to request")
}
return
}
// OCRURLInputPreparer prepares the OCRURLInput request.
func (client ImageModerationClient) OCRURLInputPreparer(ctx context.Context, language string, contentType string, imageURL BodyModel, cacheImage *bool, enhanced *bool) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
queryParameters := map[string]interface{}{
"language": autorest.Encode("query", language),
}
if cacheImage != nil {
queryParameters["CacheImage"] = autorest.Encode("query", *cacheImage)
}
if enhanced != nil {
queryParameters["enhanced"] = autorest.Encode("query", *enhanced)
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/moderate/v1.0/ProcessImage/OCR"),
autorest.WithJSON(imageURL),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("Content-Type", autorest.String(contentType)))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// OCRURLInputSender sends the OCRURLInput request. The method will close the
// http.Response Body if it receives an error.
func (client ImageModerationClient) OCRURLInputSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// OCRURLInputResponder handles the response to the OCRURLInput request. The method always
// closes the http.Response Body.
func (client ImageModerationClient) OCRURLInputResponder(resp *http.Response) (result OCR, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,457 @@
package contentmoderator
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"io"
"net/http"
)
// ListManagementImageClient is the you use the API to scan your content as it is generated. Content Moderator then
// processes your content and sends the results along with relevant information either back to your systems or to the
// built-in review tool. You can use this information to take decisions e.g. take it down, send to human judge, etc.
//
// When using the API, images need to have a minimum of 128 pixels and a maximum file size of 4MB.
// Text can be at most 1024 characters long.
// If the content passed to the text API or the image API exceeds the size limits, the API will return an error code
// that informs about the issue.
//
// This API is currently available in:
//
// * West US - westus.api.cognitive.microsoft.com
// * East US 2 - eastus2.api.cognitive.microsoft.com
// * West Central US - westcentralus.api.cognitive.microsoft.com
// * West Europe - westeurope.api.cognitive.microsoft.com
// * Southeast Asia - southeastasia.api.cognitive.microsoft.com .
type ListManagementImageClient struct {
BaseClient
}
// NewListManagementImageClient creates an instance of the ListManagementImageClient client.
func NewListManagementImageClient(baseURL AzureRegionBaseURL) ListManagementImageClient {
return ListManagementImageClient{New(baseURL)}
}
// AddImage add an image to the list with list Id equal to list Id passed.
//
// listID is list Id of the image list. tag is tag for the image. label is the image label.
func (client ListManagementImageClient) AddImage(ctx context.Context, listID string, tag *int32, label string) (result Image, err error) {
req, err := client.AddImagePreparer(ctx, listID, tag, label)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "AddImage", nil, "Failure preparing request")
return
}
resp, err := client.AddImageSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "AddImage", resp, "Failure sending request")
return
}
result, err = client.AddImageResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "AddImage", resp, "Failure responding to request")
}
return
}
// AddImagePreparer prepares the AddImage request.
func (client ListManagementImageClient) AddImagePreparer(ctx context.Context, listID string, tag *int32, label string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
}
queryParameters := map[string]interface{}{}
if tag != nil {
queryParameters["tag"] = autorest.Encode("query", *tag)
}
if len(label) > 0 {
queryParameters["label"] = autorest.Encode("query", label)
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/imagelists/{listId}/images", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// AddImageSender sends the AddImage request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementImageClient) AddImageSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// AddImageResponder handles the response to the AddImage request. The method always
// closes the http.Response Body.
func (client ListManagementImageClient) AddImageResponder(resp *http.Response) (result Image, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// AddImageFileInput add an image to the list with list Id equal to list Id passed.
//
// listID is list Id of the image list. imageStream is the image file. imageStream will be closed upon successful
// return. Callers should ensure closure when receiving an error.tag is tag for the image. label is the image label.
func (client ListManagementImageClient) AddImageFileInput(ctx context.Context, listID string, imageStream io.ReadCloser, tag *int32, label string) (result Image, err error) {
req, err := client.AddImageFileInputPreparer(ctx, listID, imageStream, tag, label)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "AddImageFileInput", nil, "Failure preparing request")
return
}
resp, err := client.AddImageFileInputSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "AddImageFileInput", resp, "Failure sending request")
return
}
result, err = client.AddImageFileInputResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "AddImageFileInput", resp, "Failure responding to request")
}
return
}
// AddImageFileInputPreparer prepares the AddImageFileInput request.
func (client ListManagementImageClient) AddImageFileInputPreparer(ctx context.Context, listID string, imageStream io.ReadCloser, tag *int32, label string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
}
queryParameters := map[string]interface{}{}
if tag != nil {
queryParameters["tag"] = autorest.Encode("query", *tag)
}
if len(label) > 0 {
queryParameters["label"] = autorest.Encode("query", label)
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/imagelists/{listId}/images", pathParameters),
autorest.WithFile(imageStream),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// AddImageFileInputSender sends the AddImageFileInput request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementImageClient) AddImageFileInputSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// AddImageFileInputResponder handles the response to the AddImageFileInput request. The method always
// closes the http.Response Body.
func (client ListManagementImageClient) AddImageFileInputResponder(resp *http.Response) (result Image, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// AddImageURLInput add an image to the list with list Id equal to list Id passed.
//
// listID is list Id of the image list. contentType is the content type. imageURL is the image url. tag is tag for the
// image. label is the image label.
func (client ListManagementImageClient) AddImageURLInput(ctx context.Context, listID string, contentType string, imageURL BodyModel, tag *int32, label string) (result Image, err error) {
req, err := client.AddImageURLInputPreparer(ctx, listID, contentType, imageURL, tag, label)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "AddImageURLInput", nil, "Failure preparing request")
return
}
resp, err := client.AddImageURLInputSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "AddImageURLInput", resp, "Failure sending request")
return
}
result, err = client.AddImageURLInputResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "AddImageURLInput", resp, "Failure responding to request")
}
return
}
// AddImageURLInputPreparer prepares the AddImageURLInput request.
func (client ListManagementImageClient) AddImageURLInputPreparer(ctx context.Context, listID string, contentType string, imageURL BodyModel, tag *int32, label string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
}
queryParameters := map[string]interface{}{}
if tag != nil {
queryParameters["tag"] = autorest.Encode("query", *tag)
}
if len(label) > 0 {
queryParameters["label"] = autorest.Encode("query", label)
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/imagelists/{listId}/images", pathParameters),
autorest.WithJSON(imageURL),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("Content-Type", autorest.String(contentType)))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// AddImageURLInputSender sends the AddImageURLInput request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementImageClient) AddImageURLInputSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// AddImageURLInputResponder handles the response to the AddImageURLInput request. The method always
// closes the http.Response Body.
func (client ListManagementImageClient) AddImageURLInputResponder(resp *http.Response) (result Image, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// DeleteAllImages deletes all images from the list with list Id equal to list Id passed.
//
// listID is list Id of the image list.
func (client ListManagementImageClient) DeleteAllImages(ctx context.Context, listID string) (result String, err error) {
req, err := client.DeleteAllImagesPreparer(ctx, listID)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "DeleteAllImages", nil, "Failure preparing request")
return
}
resp, err := client.DeleteAllImagesSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "DeleteAllImages", resp, "Failure sending request")
return
}
result, err = client.DeleteAllImagesResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "DeleteAllImages", resp, "Failure responding to request")
}
return
}
// DeleteAllImagesPreparer prepares the DeleteAllImages request.
func (client ListManagementImageClient) DeleteAllImagesPreparer(ctx context.Context, listID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/imagelists/{listId}/images", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteAllImagesSender sends the DeleteAllImages request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementImageClient) DeleteAllImagesSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DeleteAllImagesResponder handles the response to the DeleteAllImages request. The method always
// closes the http.Response Body.
func (client ListManagementImageClient) DeleteAllImagesResponder(resp *http.Response) (result String, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// DeleteImage deletes an image from the list with list Id and image Id passed.
//
// listID is list Id of the image list. imageID is id of the image.
func (client ListManagementImageClient) DeleteImage(ctx context.Context, listID string, imageID string) (result String, err error) {
req, err := client.DeleteImagePreparer(ctx, listID, imageID)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "DeleteImage", nil, "Failure preparing request")
return
}
resp, err := client.DeleteImageSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "DeleteImage", resp, "Failure sending request")
return
}
result, err = client.DeleteImageResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "DeleteImage", resp, "Failure responding to request")
}
return
}
// DeleteImagePreparer prepares the DeleteImage request.
func (client ListManagementImageClient) DeleteImagePreparer(ctx context.Context, listID string, imageID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"ImageId": autorest.Encode("path", imageID),
"listId": autorest.Encode("path", listID),
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/imagelists/{listId}/images/{ImageId}", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteImageSender sends the DeleteImage request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementImageClient) DeleteImageSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DeleteImageResponder handles the response to the DeleteImage request. The method always
// closes the http.Response Body.
func (client ListManagementImageClient) DeleteImageResponder(resp *http.Response) (result String, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetAllImageIds gets all image Ids from the list with list Id equal to list Id passed.
//
// listID is list Id of the image list.
func (client ListManagementImageClient) GetAllImageIds(ctx context.Context, listID string) (result ImageIds, err error) {
req, err := client.GetAllImageIdsPreparer(ctx, listID)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "GetAllImageIds", nil, "Failure preparing request")
return
}
resp, err := client.GetAllImageIdsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "GetAllImageIds", resp, "Failure sending request")
return
}
result, err = client.GetAllImageIdsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageClient", "GetAllImageIds", resp, "Failure responding to request")
}
return
}
// GetAllImageIdsPreparer prepares the GetAllImageIds request.
func (client ListManagementImageClient) GetAllImageIdsPreparer(ctx context.Context, listID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/imagelists/{listId}/images", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetAllImageIdsSender sends the GetAllImageIds request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementImageClient) GetAllImageIdsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// GetAllImageIdsResponder handles the response to the GetAllImageIds request. The method always
// closes the http.Response Body.
func (client ListManagementImageClient) GetAllImageIdsResponder(resp *http.Response) (result ImageIds, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,419 @@
package contentmoderator
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// ListManagementImageListsClient is the you use the API to scan your content as it is generated. Content Moderator
// then processes your content and sends the results along with relevant information either back to your systems or to
// the built-in review tool. You can use this information to take decisions e.g. take it down, send to human judge,
// etc.
//
// When using the API, images need to have a minimum of 128 pixels and a maximum file size of 4MB.
// Text can be at most 1024 characters long.
// If the content passed to the text API or the image API exceeds the size limits, the API will return an error code
// that informs about the issue.
//
// This API is currently available in:
//
// * West US - westus.api.cognitive.microsoft.com
// * East US 2 - eastus2.api.cognitive.microsoft.com
// * West Central US - westcentralus.api.cognitive.microsoft.com
// * West Europe - westeurope.api.cognitive.microsoft.com
// * Southeast Asia - southeastasia.api.cognitive.microsoft.com .
type ListManagementImageListsClient struct {
BaseClient
}
// NewListManagementImageListsClient creates an instance of the ListManagementImageListsClient client.
func NewListManagementImageListsClient(baseURL AzureRegionBaseURL) ListManagementImageListsClient {
return ListManagementImageListsClient{New(baseURL)}
}
// Create creates an image list.
//
// contentType is the content type. body is schema of the body.
func (client ListManagementImageListsClient) Create(ctx context.Context, contentType string, body Body) (result ImageList, err error) {
req, err := client.CreatePreparer(ctx, contentType, body)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "Create", nil, "Failure preparing request")
return
}
resp, err := client.CreateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "Create", resp, "Failure sending request")
return
}
result, err = client.CreateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "Create", resp, "Failure responding to request")
}
return
}
// CreatePreparer prepares the Create request.
func (client ListManagementImageListsClient) CreatePreparer(ctx context.Context, contentType string, body Body) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/lists/v1.0/imagelists"),
autorest.WithJSON(body),
autorest.WithHeader("Content-Type", autorest.String(contentType)))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementImageListsClient) CreateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// CreateResponder handles the response to the Create request. The method always
// closes the http.Response Body.
func (client ListManagementImageListsClient) CreateResponder(resp *http.Response) (result ImageList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes image list with the list Id equal to list Id passed.
//
// listID is list Id of the image list.
func (client ListManagementImageListsClient) Delete(ctx context.Context, listID string) (result String, err error) {
req, err := client.DeletePreparer(ctx, listID)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client ListManagementImageListsClient) DeletePreparer(ctx context.Context, listID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/imagelists/{listId}", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementImageListsClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client ListManagementImageListsClient) DeleteResponder(resp *http.Response) (result String, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetAllImageLists gets all the Image Lists.
func (client ListManagementImageListsClient) GetAllImageLists(ctx context.Context) (result ListImageList, err error) {
req, err := client.GetAllImageListsPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "GetAllImageLists", nil, "Failure preparing request")
return
}
resp, err := client.GetAllImageListsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "GetAllImageLists", resp, "Failure sending request")
return
}
result, err = client.GetAllImageListsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "GetAllImageLists", resp, "Failure responding to request")
}
return
}
// GetAllImageListsPreparer prepares the GetAllImageLists request.
func (client ListManagementImageListsClient) GetAllImageListsPreparer(ctx context.Context) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/lists/v1.0/imagelists"))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetAllImageListsSender sends the GetAllImageLists request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementImageListsClient) GetAllImageListsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// GetAllImageListsResponder handles the response to the GetAllImageLists request. The method always
// closes the http.Response Body.
func (client ListManagementImageListsClient) GetAllImageListsResponder(resp *http.Response) (result ListImageList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetDetails returns the details of the image list with list Id equal to list Id passed.
//
// listID is list Id of the image list.
func (client ListManagementImageListsClient) GetDetails(ctx context.Context, listID string) (result ImageList, err error) {
req, err := client.GetDetailsPreparer(ctx, listID)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "GetDetails", nil, "Failure preparing request")
return
}
resp, err := client.GetDetailsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "GetDetails", resp, "Failure sending request")
return
}
result, err = client.GetDetailsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "GetDetails", resp, "Failure responding to request")
}
return
}
// GetDetailsPreparer prepares the GetDetails request.
func (client ListManagementImageListsClient) GetDetailsPreparer(ctx context.Context, listID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/imagelists/{listId}", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetDetailsSender sends the GetDetails request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementImageListsClient) GetDetailsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// GetDetailsResponder handles the response to the GetDetails request. The method always
// closes the http.Response Body.
func (client ListManagementImageListsClient) GetDetailsResponder(resp *http.Response) (result ImageList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// RefreshIndexMethod refreshes the index of the list with list Id equal to list Id passed.
//
// listID is list Id of the image list.
func (client ListManagementImageListsClient) RefreshIndexMethod(ctx context.Context, listID string) (result RefreshIndex, err error) {
req, err := client.RefreshIndexMethodPreparer(ctx, listID)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "RefreshIndexMethod", nil, "Failure preparing request")
return
}
resp, err := client.RefreshIndexMethodSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "RefreshIndexMethod", resp, "Failure sending request")
return
}
result, err = client.RefreshIndexMethodResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "RefreshIndexMethod", resp, "Failure responding to request")
}
return
}
// RefreshIndexMethodPreparer prepares the RefreshIndexMethod request.
func (client ListManagementImageListsClient) RefreshIndexMethodPreparer(ctx context.Context, listID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/imagelists/{listId}/RefreshIndex", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// RefreshIndexMethodSender sends the RefreshIndexMethod request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementImageListsClient) RefreshIndexMethodSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// RefreshIndexMethodResponder handles the response to the RefreshIndexMethod request. The method always
// closes the http.Response Body.
func (client ListManagementImageListsClient) RefreshIndexMethodResponder(resp *http.Response) (result RefreshIndex, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Update updates an image list with list Id equal to list Id passed.
//
// listID is list Id of the image list. contentType is the content type. body is schema of the body.
func (client ListManagementImageListsClient) Update(ctx context.Context, listID string, contentType string, body Body) (result ImageList, err error) {
req, err := client.UpdatePreparer(ctx, listID, contentType, body)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "Update", nil, "Failure preparing request")
return
}
resp, err := client.UpdateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "Update", resp, "Failure sending request")
return
}
result, err = client.UpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementImageListsClient", "Update", resp, "Failure responding to request")
}
return
}
// UpdatePreparer prepares the Update request.
func (client ListManagementImageListsClient) UpdatePreparer(ctx context.Context, listID string, contentType string, body Body) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPut(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/imagelists/{listId}", pathParameters),
autorest.WithJSON(body),
autorest.WithHeader("Content-Type", autorest.String(contentType)))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementImageListsClient) UpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client ListManagementImageListsClient) UpdateResponder(resp *http.Response) (result ImageList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,327 @@
package contentmoderator
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// ListManagementTermClient is the you use the API to scan your content as it is generated. Content Moderator then
// processes your content and sends the results along with relevant information either back to your systems or to the
// built-in review tool. You can use this information to take decisions e.g. take it down, send to human judge, etc.
//
// When using the API, images need to have a minimum of 128 pixels and a maximum file size of 4MB.
// Text can be at most 1024 characters long.
// If the content passed to the text API or the image API exceeds the size limits, the API will return an error code
// that informs about the issue.
//
// This API is currently available in:
//
// * West US - westus.api.cognitive.microsoft.com
// * East US 2 - eastus2.api.cognitive.microsoft.com
// * West Central US - westcentralus.api.cognitive.microsoft.com
// * West Europe - westeurope.api.cognitive.microsoft.com
// * Southeast Asia - southeastasia.api.cognitive.microsoft.com .
type ListManagementTermClient struct {
BaseClient
}
// NewListManagementTermClient creates an instance of the ListManagementTermClient client.
func NewListManagementTermClient(baseURL AzureRegionBaseURL) ListManagementTermClient {
return ListManagementTermClient{New(baseURL)}
}
// AddTerm add a term to the term list with list Id equal to list Id passed.
//
// listID is list Id of the image list. term is term to be deleted language is language of the terms.
func (client ListManagementTermClient) AddTerm(ctx context.Context, listID string, term string, language string) (result SetObject, err error) {
req, err := client.AddTermPreparer(ctx, listID, term, language)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermClient", "AddTerm", nil, "Failure preparing request")
return
}
resp, err := client.AddTermSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermClient", "AddTerm", resp, "Failure sending request")
return
}
result, err = client.AddTermResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermClient", "AddTerm", resp, "Failure responding to request")
}
return
}
// AddTermPreparer prepares the AddTerm request.
func (client ListManagementTermClient) AddTermPreparer(ctx context.Context, listID string, term string, language string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
"term": autorest.Encode("path", term),
}
queryParameters := map[string]interface{}{
"language": autorest.Encode("query", language),
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/termlists/{listId}/terms/{term}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// AddTermSender sends the AddTerm request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementTermClient) AddTermSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// AddTermResponder handles the response to the AddTerm request. The method always
// closes the http.Response Body.
func (client ListManagementTermClient) AddTermResponder(resp *http.Response) (result SetObject, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// DeleteAllTerms deletes all terms from the list with list Id equal to the list Id passed.
//
// listID is list Id of the image list. language is language of the terms.
func (client ListManagementTermClient) DeleteAllTerms(ctx context.Context, listID string, language string) (result String, err error) {
req, err := client.DeleteAllTermsPreparer(ctx, listID, language)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermClient", "DeleteAllTerms", nil, "Failure preparing request")
return
}
resp, err := client.DeleteAllTermsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermClient", "DeleteAllTerms", resp, "Failure sending request")
return
}
result, err = client.DeleteAllTermsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermClient", "DeleteAllTerms", resp, "Failure responding to request")
}
return
}
// DeleteAllTermsPreparer prepares the DeleteAllTerms request.
func (client ListManagementTermClient) DeleteAllTermsPreparer(ctx context.Context, listID string, language string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
}
queryParameters := map[string]interface{}{
"language": autorest.Encode("query", language),
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/termlists/{listId}/terms", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteAllTermsSender sends the DeleteAllTerms request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementTermClient) DeleteAllTermsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DeleteAllTermsResponder handles the response to the DeleteAllTerms request. The method always
// closes the http.Response Body.
func (client ListManagementTermClient) DeleteAllTermsResponder(resp *http.Response) (result String, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// DeleteTerm deletes a term from the list with list Id equal to the list Id passed.
//
// listID is list Id of the image list. term is term to be deleted language is language of the terms.
func (client ListManagementTermClient) DeleteTerm(ctx context.Context, listID string, term string, language string) (result String, err error) {
req, err := client.DeleteTermPreparer(ctx, listID, term, language)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermClient", "DeleteTerm", nil, "Failure preparing request")
return
}
resp, err := client.DeleteTermSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermClient", "DeleteTerm", resp, "Failure sending request")
return
}
result, err = client.DeleteTermResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermClient", "DeleteTerm", resp, "Failure responding to request")
}
return
}
// DeleteTermPreparer prepares the DeleteTerm request.
func (client ListManagementTermClient) DeleteTermPreparer(ctx context.Context, listID string, term string, language string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
"term": autorest.Encode("path", term),
}
queryParameters := map[string]interface{}{
"language": autorest.Encode("query", language),
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/termlists/{listId}/terms/{term}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteTermSender sends the DeleteTerm request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementTermClient) DeleteTermSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DeleteTermResponder handles the response to the DeleteTerm request. The method always
// closes the http.Response Body.
func (client ListManagementTermClient) DeleteTermResponder(resp *http.Response) (result String, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetAllTerms gets all terms from the list with list Id equal to the list Id passed.
//
// listID is list Id of the image list. language is language of the terms. offset is the pagination start index. limit
// is the max limit.
func (client ListManagementTermClient) GetAllTerms(ctx context.Context, listID string, language string, offset *int32, limit *int32) (result Terms, err error) {
req, err := client.GetAllTermsPreparer(ctx, listID, language, offset, limit)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermClient", "GetAllTerms", nil, "Failure preparing request")
return
}
resp, err := client.GetAllTermsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermClient", "GetAllTerms", resp, "Failure sending request")
return
}
result, err = client.GetAllTermsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermClient", "GetAllTerms", resp, "Failure responding to request")
}
return
}
// GetAllTermsPreparer prepares the GetAllTerms request.
func (client ListManagementTermClient) GetAllTermsPreparer(ctx context.Context, listID string, language string, offset *int32, limit *int32) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
}
queryParameters := map[string]interface{}{
"language": autorest.Encode("query", language),
}
if offset != nil {
queryParameters["offset"] = autorest.Encode("query", *offset)
}
if limit != nil {
queryParameters["limit"] = autorest.Encode("query", *limit)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/termlists/{listId}/terms", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetAllTermsSender sends the GetAllTerms request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementTermClient) GetAllTermsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// GetAllTermsResponder handles the response to the GetAllTerms request. The method always
// closes the http.Response Body.
func (client ListManagementTermClient) GetAllTermsResponder(resp *http.Response) (result Terms, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,423 @@
package contentmoderator
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// ListManagementTermListsClient is the you use the API to scan your content as it is generated. Content Moderator then
// processes your content and sends the results along with relevant information either back to your systems or to the
// built-in review tool. You can use this information to take decisions e.g. take it down, send to human judge, etc.
//
// When using the API, images need to have a minimum of 128 pixels and a maximum file size of 4MB.
// Text can be at most 1024 characters long.
// If the content passed to the text API or the image API exceeds the size limits, the API will return an error code
// that informs about the issue.
//
// This API is currently available in:
//
// * West US - westus.api.cognitive.microsoft.com
// * East US 2 - eastus2.api.cognitive.microsoft.com
// * West Central US - westcentralus.api.cognitive.microsoft.com
// * West Europe - westeurope.api.cognitive.microsoft.com
// * Southeast Asia - southeastasia.api.cognitive.microsoft.com .
type ListManagementTermListsClient struct {
BaseClient
}
// NewListManagementTermListsClient creates an instance of the ListManagementTermListsClient client.
func NewListManagementTermListsClient(baseURL AzureRegionBaseURL) ListManagementTermListsClient {
return ListManagementTermListsClient{New(baseURL)}
}
// Create creates a Term List
//
// contentType is the content type. body is schema of the body.
func (client ListManagementTermListsClient) Create(ctx context.Context, contentType string, body Body) (result TermList, err error) {
req, err := client.CreatePreparer(ctx, contentType, body)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "Create", nil, "Failure preparing request")
return
}
resp, err := client.CreateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "Create", resp, "Failure sending request")
return
}
result, err = client.CreateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "Create", resp, "Failure responding to request")
}
return
}
// CreatePreparer prepares the Create request.
func (client ListManagementTermListsClient) CreatePreparer(ctx context.Context, contentType string, body Body) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/lists/v1.0/termlists"),
autorest.WithJSON(body),
autorest.WithHeader("Content-Type", autorest.String(contentType)))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementTermListsClient) CreateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// CreateResponder handles the response to the Create request. The method always
// closes the http.Response Body.
func (client ListManagementTermListsClient) CreateResponder(resp *http.Response) (result TermList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes term list with the list Id equal to list Id passed.
//
// listID is list Id of the image list.
func (client ListManagementTermListsClient) Delete(ctx context.Context, listID string) (result String, err error) {
req, err := client.DeletePreparer(ctx, listID)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client ListManagementTermListsClient) DeletePreparer(ctx context.Context, listID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/termlists/{listId}", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementTermListsClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client ListManagementTermListsClient) DeleteResponder(resp *http.Response) (result String, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetAllTermLists gets all the Term Lists
func (client ListManagementTermListsClient) GetAllTermLists(ctx context.Context) (result ListTermList, err error) {
req, err := client.GetAllTermListsPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "GetAllTermLists", nil, "Failure preparing request")
return
}
resp, err := client.GetAllTermListsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "GetAllTermLists", resp, "Failure sending request")
return
}
result, err = client.GetAllTermListsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "GetAllTermLists", resp, "Failure responding to request")
}
return
}
// GetAllTermListsPreparer prepares the GetAllTermLists request.
func (client ListManagementTermListsClient) GetAllTermListsPreparer(ctx context.Context) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/lists/v1.0/termlists"))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetAllTermListsSender sends the GetAllTermLists request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementTermListsClient) GetAllTermListsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// GetAllTermListsResponder handles the response to the GetAllTermLists request. The method always
// closes the http.Response Body.
func (client ListManagementTermListsClient) GetAllTermListsResponder(resp *http.Response) (result ListTermList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetDetails returns list Id details of the term list with list Id equal to list Id passed.
//
// listID is list Id of the image list.
func (client ListManagementTermListsClient) GetDetails(ctx context.Context, listID string) (result TermList, err error) {
req, err := client.GetDetailsPreparer(ctx, listID)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "GetDetails", nil, "Failure preparing request")
return
}
resp, err := client.GetDetailsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "GetDetails", resp, "Failure sending request")
return
}
result, err = client.GetDetailsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "GetDetails", resp, "Failure responding to request")
}
return
}
// GetDetailsPreparer prepares the GetDetails request.
func (client ListManagementTermListsClient) GetDetailsPreparer(ctx context.Context, listID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/termlists/{listId}", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetDetailsSender sends the GetDetails request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementTermListsClient) GetDetailsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// GetDetailsResponder handles the response to the GetDetails request. The method always
// closes the http.Response Body.
func (client ListManagementTermListsClient) GetDetailsResponder(resp *http.Response) (result TermList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// RefreshIndexMethod refreshes the index of the list with list Id equal to list ID passed.
//
// listID is list Id of the image list. language is language of the terms.
func (client ListManagementTermListsClient) RefreshIndexMethod(ctx context.Context, listID string, language string) (result RefreshIndex, err error) {
req, err := client.RefreshIndexMethodPreparer(ctx, listID, language)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "RefreshIndexMethod", nil, "Failure preparing request")
return
}
resp, err := client.RefreshIndexMethodSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "RefreshIndexMethod", resp, "Failure sending request")
return
}
result, err = client.RefreshIndexMethodResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "RefreshIndexMethod", resp, "Failure responding to request")
}
return
}
// RefreshIndexMethodPreparer prepares the RefreshIndexMethod request.
func (client ListManagementTermListsClient) RefreshIndexMethodPreparer(ctx context.Context, listID string, language string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
}
queryParameters := map[string]interface{}{
"language": autorest.Encode("query", language),
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/termlists/{listId}/RefreshIndex", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// RefreshIndexMethodSender sends the RefreshIndexMethod request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementTermListsClient) RefreshIndexMethodSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// RefreshIndexMethodResponder handles the response to the RefreshIndexMethod request. The method always
// closes the http.Response Body.
func (client ListManagementTermListsClient) RefreshIndexMethodResponder(resp *http.Response) (result RefreshIndex, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Update updates an Term List.
//
// listID is list Id of the image list. contentType is the content type. body is schema of the body.
func (client ListManagementTermListsClient) Update(ctx context.Context, listID string, contentType string, body Body) (result TermList, err error) {
req, err := client.UpdatePreparer(ctx, listID, contentType, body)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "Update", nil, "Failure preparing request")
return
}
resp, err := client.UpdateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "Update", resp, "Failure sending request")
return
}
result, err = client.UpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.ListManagementTermListsClient", "Update", resp, "Failure responding to request")
}
return
}
// UpdatePreparer prepares the Update request.
func (client ListManagementTermListsClient) UpdatePreparer(ctx context.Context, listID string, contentType string, body Body) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
pathParameters := map[string]interface{}{
"listId": autorest.Encode("path", listID),
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPut(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPathParameters("/contentmoderator/lists/v1.0/termlists/{listId}", pathParameters),
autorest.WithJSON(body),
autorest.WithHeader("Content-Type", autorest.String(contentType)))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client ListManagementTermListsClient) UpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client ListManagementTermListsClient) UpdateResponder(resp *http.Response) (result TermList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,739 @@
package contentmoderator
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
// AzureRegionBaseURL enumerates the values for azure region base url.
type AzureRegionBaseURL string
const (
// Australiaeastapicognitivemicrosoftcom ...
Australiaeastapicognitivemicrosoftcom AzureRegionBaseURL = "australiaeast.api.cognitive.microsoft.com"
// Brazilsouthapicognitivemicrosoftcom ...
Brazilsouthapicognitivemicrosoftcom AzureRegionBaseURL = "brazilsouth.api.cognitive.microsoft.com"
// ContentmoderatortestazureApinet ...
ContentmoderatortestazureApinet AzureRegionBaseURL = "contentmoderatortest.azure-api.net"
// Eastasiaapicognitivemicrosoftcom ...
Eastasiaapicognitivemicrosoftcom AzureRegionBaseURL = "eastasia.api.cognitive.microsoft.com"
// Eastus2apicognitivemicrosoftcom ...
Eastus2apicognitivemicrosoftcom AzureRegionBaseURL = "eastus2.api.cognitive.microsoft.com"
// Eastusapicognitivemicrosoftcom ...
Eastusapicognitivemicrosoftcom AzureRegionBaseURL = "eastus.api.cognitive.microsoft.com"
// Northeuropeapicognitivemicrosoftcom ...
Northeuropeapicognitivemicrosoftcom AzureRegionBaseURL = "northeurope.api.cognitive.microsoft.com"
// Southcentralusapicognitivemicrosoftcom ...
Southcentralusapicognitivemicrosoftcom AzureRegionBaseURL = "southcentralus.api.cognitive.microsoft.com"
// Southeastasiaapicognitivemicrosoftcom ...
Southeastasiaapicognitivemicrosoftcom AzureRegionBaseURL = "southeastasia.api.cognitive.microsoft.com"
// Westcentralusapicognitivemicrosoftcom ...
Westcentralusapicognitivemicrosoftcom AzureRegionBaseURL = "westcentralus.api.cognitive.microsoft.com"
// Westeuropeapicognitivemicrosoftcom ...
Westeuropeapicognitivemicrosoftcom AzureRegionBaseURL = "westeurope.api.cognitive.microsoft.com"
// Westus2apicognitivemicrosoftcom ...
Westus2apicognitivemicrosoftcom AzureRegionBaseURL = "westus2.api.cognitive.microsoft.com"
// Westusapicognitivemicrosoftcom ...
Westusapicognitivemicrosoftcom AzureRegionBaseURL = "westus.api.cognitive.microsoft.com"
)
// StatusEnum enumerates the values for status enum.
type StatusEnum string
const (
// Complete ...
Complete StatusEnum = "Complete"
// Pending ...
Pending StatusEnum = "Pending"
// Unpublished ...
Unpublished StatusEnum = "Unpublished"
)
// Type enumerates the values for type.
type Type string
const (
// TypeImage ...
TypeImage Type = "Image"
// TypeText ...
TypeText Type = "Text"
)
// Address address details.
type Address struct {
// Text - Detected Address.
Text *string `json:"Text,omitempty"`
// Index - Index(Location) of the Address in the input text content.
Index *int32 `json:"Index,omitempty"`
}
// APIError error information returned by the API
type APIError struct {
Error *Error `json:"Error,omitempty"`
}
// Body ...
type Body struct {
// Name - Name of the list.
Name *string `json:"Name,omitempty"`
// Description - Description of the list.
Description *string `json:"Description,omitempty"`
// Metadata - Metadata of the list.
Metadata *BodyMetadata `json:"Metadata,omitempty"`
}
// BodyMetadata metadata of the list.
type BodyMetadata struct {
// KeyOne - Optional key value pair to describe your list.
KeyOne *string `json:"Key One,omitempty"`
// KeyTwo - Optional key value pair to describe your list.
KeyTwo *string `json:"Key Two,omitempty"`
}
// BodyModel ...
type BodyModel struct {
DataRepresentation *string `json:"DataRepresentation,omitempty"`
Value *string `json:"Value,omitempty"`
}
// Candidate OCR candidate text.
type Candidate struct {
// Text - The text found.
Text *string `json:"Text,omitempty"`
// Confidence - The confidence level.
Confidence *float64 `json:"Confidence,omitempty"`
}
// Classification the classification details of the text.
type Classification struct {
// AdultScore - The adult score.
AdultScore *float64 `json:"AdultScore,omitempty"`
// RacyScore - The racy score.
RacyScore *float64 `json:"RacyScore,omitempty"`
// OffensiveScore - The offensive score.
OffensiveScore *float64 `json:"OffensiveScore,omitempty"`
// ReviewRecommended - The review recommended flag.
ReviewRecommended *bool `json:"ReviewRecommended,omitempty"`
}
// Content ...
type Content struct {
// ContentValue - Content to evaluate for a job.
ContentValue *string `json:"ContentValue,omitempty"`
}
// CreateReviewBodyItem schema items of the body.
type CreateReviewBodyItem struct {
// Type - Type of the content. Possible values include: 'TypeImage', 'TypeText'
Type Type `json:"Type,omitempty"`
// Content - Content to review.
Content *string `json:"Content,omitempty"`
// ContentID - Content Identifier.
ContentID *string `json:"ContentId,omitempty"`
// CallbackEndpoint - Optional CallbackEndpoint.
CallbackEndpoint *string `json:"CallbackEndpoint,omitempty"`
// Metadata - Optional metadata details.
Metadata *[]CreateReviewBodyItemMetadataItem `json:"Metadata,omitempty"`
}
// CreateReviewBodyItemMetadataItem ...
type CreateReviewBodyItemMetadataItem struct {
// Key - Your key parameter.
Key *string `json:"Key,omitempty"`
// Value - Your value parameter.
Value *string `json:"Value,omitempty"`
}
// CreateVideoReviewsBodyItem schema items of the body.
type CreateVideoReviewsBodyItem struct {
// VideoFrames - Optional metadata details.
VideoFrames *[]CreateVideoReviewsBodyItemVideoFramesItem `json:"VideoFrames,omitempty"`
// Metadata - Optional metadata details.
Metadata *[]CreateVideoReviewsBodyItemMetadataItem `json:"Metadata,omitempty"`
// Type - Type of the content.
Type *string `json:"Type,omitempty"`
// Content - Video content url to review.
Content *string `json:"Content,omitempty"`
// ContentID - Content Identifier.
ContentID *string `json:"ContentId,omitempty"`
// Status - Status of the video(Complete,Unpublished,Pending). Possible values include: 'Complete', 'Unpublished', 'Pending'
Status Status `json:"Status,omitempty"`
// Timescale - Timescale of the video.
Timescale *int32 `json:"Timescale,omitempty"`
// CallbackEndpoint - Optional CallbackEndpoint.
CallbackEndpoint *string `json:"CallbackEndpoint,omitempty"`
}
// CreateVideoReviewsBodyItemMetadataItem ...
type CreateVideoReviewsBodyItemMetadataItem struct {
// Key - Your key parameter.
Key *string `json:"Key,omitempty"`
// Value - Your value parameter.
Value *string `json:"Value,omitempty"`
}
// CreateVideoReviewsBodyItemVideoFramesItem ...
type CreateVideoReviewsBodyItemVideoFramesItem struct {
// ID - Id of the frame.
ID *string `json:"Id,omitempty"`
// Timestamp - Timestamp of the frame.
Timestamp *int32 `json:"Timestamp,omitempty"`
// FrameImage - Frame image Url.
FrameImage *string `json:"FrameImage,omitempty"`
ReviewerResultTags *[]CreateVideoReviewsBodyItemVideoFramesItemReviewerResultTagsItem `json:"ReviewerResultTags,omitempty"`
// Metadata - Optional metadata details.
Metadata *[]CreateVideoReviewsBodyItemVideoFramesItemMetadataItem `json:"Metadata,omitempty"`
}
// CreateVideoReviewsBodyItemVideoFramesItemMetadataItem ...
type CreateVideoReviewsBodyItemVideoFramesItemMetadataItem struct {
// Key - Your key parameter.
Key *string `json:"Key,omitempty"`
// Value - Your value parameter.
Value *string `json:"Value,omitempty"`
}
// CreateVideoReviewsBodyItemVideoFramesItemReviewerResultTagsItem ...
type CreateVideoReviewsBodyItemVideoFramesItemReviewerResultTagsItem struct {
// Key - Your key parameter.
Key *string `json:"Key,omitempty"`
// Value - Your value parameter.
Value *string `json:"Value,omitempty"`
}
// DetectedLanguage detect language result.
type DetectedLanguage struct {
autorest.Response `json:"-"`
// DetectedLanguage - The detected language.
DetectedLanguage *string `json:"DetectedLanguage,omitempty"`
// Status - The detect language status
Status *Status `json:"Status,omitempty"`
// TrackingID - The tracking id.
TrackingID *string `json:"TrackingId,omitempty"`
}
// DetectedTerms detected Terms details.
type DetectedTerms struct {
// Index - Index(Location) of the detected profanity term in the input text content.
Index *int32 `json:"Index,omitempty"`
// OriginalIndex - Original Index(Location) of the detected profanity term in the input text content.
OriginalIndex *int32 `json:"OriginalIndex,omitempty"`
// ListID - Matched Terms list Id.
ListID *int32 `json:"ListId,omitempty"`
// Term - Detected profanity term.
Term *string `json:"Term,omitempty"`
}
// Email email Address details.
type Email struct {
// Detected - Detected Email Address from the input text content.
Detected *string `json:"Detected,omitempty"`
// SubType - Subtype of the detected Email Address.
SubType *string `json:"SubType,omitempty"`
// Text - Email Address in the input text content.
Text *string `json:"Text,omitempty"`
// Index - Index(Location) of the Email address in the input text content.
Index *int32 `json:"Index,omitempty"`
}
// Error error body.
type Error struct {
Code *string `json:"Code,omitempty"`
Message *string `json:"Message,omitempty"`
}
// Evaluate evaluate response object.
type Evaluate struct {
autorest.Response `json:"-"`
// CacheID - The cache id.
CacheID *string `json:"CacheID,omitempty"`
// Result - Evaluate result.
Result *bool `json:"Result,omitempty"`
// TrackingID - The tracking id.
TrackingID *string `json:"TrackingId,omitempty"`
// AdultClassificationScore - The adult classification score.
AdultClassificationScore *float64 `json:"AdultClassificationScore,omitempty"`
// IsImageAdultClassified - Indicates if an image is classified as adult.
IsImageAdultClassified *bool `json:"IsImageAdultClassified,omitempty"`
// RacyClassificationScore - The racy classication score.
RacyClassificationScore *float64 `json:"RacyClassificationScore,omitempty"`
// IsImageRacyClassified - Indicates if the image is classified as racy.
IsImageRacyClassified *bool `json:"IsImageRacyClassified,omitempty"`
// AdvancedInfo - The advanced info.
AdvancedInfo *[]KeyValuePair `json:"AdvancedInfo,omitempty"`
// Status - The evaluate status
Status *Status `json:"Status,omitempty"`
}
// Face coordinates to the found face.
type Face struct {
// Bottom - The bottom coordinate.
Bottom *int32 `json:"Bottom,omitempty"`
// Left - The left coordinate.
Left *int32 `json:"Left,omitempty"`
// Right - The right coordinate.
Right *int32 `json:"Right,omitempty"`
// Top - The top coordinate.
Top *int32 `json:"Top,omitempty"`
}
// FoundFaces request object the contains found faces.
type FoundFaces struct {
autorest.Response `json:"-"`
// Status - The evaluate status
Status *Status `json:"Status,omitempty"`
// TrackingID - The tracking id.
TrackingID *string `json:"TrackingId,omitempty"`
// CacheID - The cache id.
CacheID *string `json:"CacheId,omitempty"`
// Result - True if result was found.
Result *bool `json:"Result,omitempty"`
// Count - Number of faces found.
Count *int32 `json:"Count,omitempty"`
// AdvancedInfo - The advanced info.
AdvancedInfo *[]KeyValuePair `json:"AdvancedInfo,omitempty"`
// Faces - The list of faces.
Faces *[]Face `json:"Faces,omitempty"`
}
// Frame video frame property details.
type Frame struct {
// Timestamp - Timestamp of the frame.
Timestamp *string `json:"Timestamp,omitempty"`
// FrameImage - Frame image.
FrameImage *string `json:"FrameImage,omitempty"`
// Metadata - Array of KeyValue.
Metadata *[]KeyValuePair `json:"Metadata,omitempty"`
// ReviewerResultTags - Reviewer result tags.
ReviewerResultTags *[]Tag `json:"ReviewerResultTags,omitempty"`
}
// Frames the response for a Get Frames request.
type Frames struct {
autorest.Response `json:"-"`
// ReviewID - Id of the review.
ReviewID *string `json:"ReviewId,omitempty"`
VideoFrames *[]Frame `json:"VideoFrames,omitempty"`
}
// Image image Properties.
type Image struct {
autorest.Response `json:"-"`
// ContentID - Content Id.
ContentID *string `json:"ContentId,omitempty"`
// AdditionalInfo - Advanced info list.
AdditionalInfo *[]ImageAdditionalInfoItem `json:"AdditionalInfo,omitempty"`
// Status - Status details.
Status *Status `json:"Status,omitempty"`
// TrackingID - Tracking Id.
TrackingID *string `json:"TrackingId,omitempty"`
}
// ImageAdditionalInfoItem ...
type ImageAdditionalInfoItem struct {
// Key - Key parameter.
Key *string `json:"Key,omitempty"`
// Value - Value parameter.
Value *string `json:"Value,omitempty"`
}
// ImageIds image Id properties.
type ImageIds struct {
autorest.Response `json:"-"`
// ContentSource - Source of the content.
ContentSource *string `json:"ContentSource,omitempty"`
// ContentIds - Id of the contents.
ContentIds *[]int32 `json:"ContentIds,omitempty"`
// Status - Get Image status.
Status *Status `json:"Status,omitempty"`
// TrackingID - Tracking Id.
TrackingID *string `json:"TrackingId,omitempty"`
}
// ImageList image List Properties.
type ImageList struct {
autorest.Response `json:"-"`
// ID - Image List Id.
ID *int32 `json:"Id,omitempty"`
// Name - Image List Name.
Name *string `json:"Name,omitempty"`
// Description - Description for image list.
Description *string `json:"Description,omitempty"`
// Metadata - Image List Metadata.
Metadata *ImageListMetadata `json:"Metadata,omitempty"`
}
// ImageListMetadata image List Metadata.
type ImageListMetadata struct {
// KeyOne - Optional Key value pair to describe your list.
KeyOne *string `json:"Key One,omitempty"`
// KeyTwo - Optional Key value pair to describe your list.
KeyTwo *string `json:"Key Two,omitempty"`
}
// IPA IP Address details.
type IPA struct {
// SubType - Subtype of the detected IP Address.
SubType *string `json:"SubType,omitempty"`
// Text - Detected IP Address.
Text *string `json:"Text,omitempty"`
// Index - Index(Location) of the IP Address in the input text content.
Index *int32 `json:"Index,omitempty"`
}
// Job the Job object.
type Job struct {
autorest.Response `json:"-"`
// ID - The job id.
ID *string `json:"Id,omitempty"`
// TeamName - The team name associated with the job.
TeamName *string `json:"TeamName,omitempty"`
// Status - The status string (<Pending, Failed, Completed>).
Status *string `json:"Status,omitempty"`
// WorkflowID - The Id of the workflow.
WorkflowID *string `json:"WorkflowId,omitempty"`
// Type - Type of the content.
Type *string `json:"Type,omitempty"`
// CallBackEndpoint - The callback endpoint.
CallBackEndpoint *string `json:"CallBackEndpoint,omitempty"`
// ReviewID - Review Id if one is created.
ReviewID *string `json:"ReviewId,omitempty"`
// ResultMetaData - Array of KeyValue pairs.
ResultMetaData *[]KeyValuePair `json:"ResultMetaData,omitempty"`
// JobExecutionReport - Job execution report- Array of KeyValue pairs object.
JobExecutionReport *[]JobExecutionReportDetails `json:"JobExecutionReport,omitempty"`
}
// JobExecutionReportDetails job Execution Report Values.
type JobExecutionReportDetails struct {
// Ts - Time details.
Ts *string `json:"Ts,omitempty"`
// Msg - Message details.
Msg *string `json:"Msg,omitempty"`
}
// JobID ...
type JobID struct {
autorest.Response `json:"-"`
// JobID - Id of the created job.
JobID *string `json:"JobId,omitempty"`
}
// JobListResult the list of job ids.
type JobListResult struct {
// Value - The job id.
Value *[]string `json:"Value,omitempty"`
}
// KeyValuePair the key value pair object properties.
type KeyValuePair struct {
// Key - The key parameter.
Key *string `json:"Key,omitempty"`
// Value - The value parameter.
Value *string `json:"Value,omitempty"`
}
// ListImageList ...
type ListImageList struct {
autorest.Response `json:"-"`
Value *[]ImageList `json:"value,omitempty"`
}
// ListString ...
type ListString struct {
autorest.Response `json:"-"`
Value *[]string `json:"value,omitempty"`
}
// ListTermList ...
type ListTermList struct {
autorest.Response `json:"-"`
Value *[]TermList `json:"value,omitempty"`
}
// Match the match details.
type Match struct {
// Score - Confidence score of the image match.
Score *float64 `json:"Score,omitempty"`
// MatchID - The match id.
MatchID *int32 `json:"MatchId,omitempty"`
// Source - The source.
Source *string `json:"Source,omitempty"`
// Tags - The tags for match details.
Tags *[]int32 `json:"Tags,omitempty"`
// Label - The label.
Label *string `json:"Label,omitempty"`
}
// MatchResponse the response for a Match request.
type MatchResponse struct {
autorest.Response `json:"-"`
// TrackingID - The tracking id.
TrackingID *string `json:"TrackingId,omitempty"`
// CacheID - The cache id.
CacheID *string `json:"CacheID,omitempty"`
// IsMatch - Indicates if there is a match.
IsMatch *bool `json:"IsMatch,omitempty"`
// Matches - The match details.
Matches *[]Match `json:"Matches,omitempty"`
// Status - The evaluate status
Status *Status `json:"Status,omitempty"`
}
// OCR contains the text found in image for the language specified.
type OCR struct {
autorest.Response `json:"-"`
// Status - The evaluate status
Status *Status `json:"Status,omitempty"`
// Metadata - Array of KeyValue.
Metadata *[]KeyValuePair `json:"Metadata,omitempty"`
// TrackingID - The tracking id.
TrackingID *string `json:"TrackingId,omitempty"`
// CacheID - The cache id.
CacheID *string `json:"CacheId,omitempty"`
// Language - The ISO 639-3 code.
Language *string `json:"Language,omitempty"`
// Text - The found text.
Text *string `json:"Text,omitempty"`
// Candidates - The list of candidate text.
Candidates *[]Candidate `json:"Candidates,omitempty"`
}
// Phone phone Property details.
type Phone struct {
// CountryCode - CountryCode of the detected Phone number.
CountryCode *string `json:"CountryCode,omitempty"`
// Text - Detected Phone number.
Text *string `json:"Text,omitempty"`
// Index - Index(Location) of the Phone number in the input text content.
Index *int32 `json:"Index,omitempty"`
}
// PII personal Identifier Information details.
type PII struct {
Email *[]Email `json:"Email,omitempty"`
IPA *[]IPA `json:"IPA,omitempty"`
Phone *[]Phone `json:"Phone,omitempty"`
Address *[]Address `json:"Address,omitempty"`
}
// RefreshIndex refresh Index Response.
type RefreshIndex struct {
autorest.Response `json:"-"`
// ContentSourceID - Content source Id.
ContentSourceID *string `json:"ContentSourceId,omitempty"`
// IsUpdateSuccess - Update success status.
IsUpdateSuccess *bool `json:"IsUpdateSuccess,omitempty"`
// AdvancedInfo - Advanced info list.
AdvancedInfo *[]RefreshIndexAdvancedInfoItem `json:"AdvancedInfo,omitempty"`
// Status - Refresh index status.
Status *Status `json:"Status,omitempty"`
// TrackingID - Tracking Id.
TrackingID *string `json:"TrackingId,omitempty"`
}
// RefreshIndexAdvancedInfoItem ...
type RefreshIndexAdvancedInfoItem struct {
// KeyOne - Key parameter to describe advanced info.
KeyOne *string `json:"Key One,omitempty"`
// KeyTwo - Key parameter to describe advanced info.
KeyTwo *string `json:"Key Two,omitempty"`
}
// Review the Review object.
type Review struct {
autorest.Response `json:"-"`
// ReviewID - Id of the review.
ReviewID *string `json:"ReviewId,omitempty"`
// SubTeam - Name of the subteam.
SubTeam *string `json:"SubTeam,omitempty"`
// Status - The status string (<Pending, Complete>).
Status *string `json:"Status,omitempty"`
// ReviewerResultTags - Array of KeyValue with Reviewer set Tags.
ReviewerResultTags *[]KeyValuePair `json:"ReviewerResultTags,omitempty"`
// CreatedBy - The reviewer name.
CreatedBy *string `json:"CreatedBy,omitempty"`
// Metadata - Array of KeyValue.
Metadata *[]KeyValuePair `json:"Metadata,omitempty"`
// Type - The type of content.
Type *string `json:"Type,omitempty"`
// Content - The content value.
Content *string `json:"Content,omitempty"`
// ContentID - Id of the content.
ContentID *string `json:"ContentId,omitempty"`
// CallbackEndpoint - The callback endpoint.
CallbackEndpoint *string `json:"CallbackEndpoint,omitempty"`
}
// Screen the response for a Screen text request.
type Screen struct {
autorest.Response `json:"-"`
// OriginalText - The original text.
OriginalText *string `json:"OriginalText,omitempty"`
// NormalizedText - The normalized text.
NormalizedText *string `json:"NormalizedText,omitempty"`
// AutoCorrectedText - The autocorrected text
AutoCorrectedText *string `json:"AutoCorrectedText,omitempty"`
// Misrepresentation - The misrepresentation text.
Misrepresentation *[]string `json:"Misrepresentation,omitempty"`
// Classification - The classification details of the text.
Classification *Classification `json:"Classification,omitempty"`
// Status - The evaluate status.
Status *Status `json:"Status,omitempty"`
// PII - Personal Identifier Information details.
PII *PII `json:"PII,omitempty"`
// Language - Language of the input text content.
Language *string `json:"Language,omitempty"`
Terms *[]DetectedTerms `json:"Terms,omitempty"`
// TrackingID - Unique Content Moderator transaction Id.
TrackingID *string `json:"TrackingId,omitempty"`
}
// SetObject ...
type SetObject struct {
autorest.Response `json:"-"`
Value *map[string]interface{} `json:"value,omitempty"`
}
// Status status properties.
type Status struct {
// Code - Status code.
Code *int32 `json:"Code,omitempty"`
// Description - Status description.
Description *string `json:"Description,omitempty"`
// Exception - Exception status.
Exception *string `json:"Exception,omitempty"`
}
// String ...
type String struct {
autorest.Response `json:"-"`
Value *string `json:"value,omitempty"`
}
// Tag tag details.
type Tag struct {
// Key - The key parameter.
Key *string `json:"Key,omitempty"`
// Value - The value parameter.
Value *string `json:"Value,omitempty"`
}
// TermList term List Properties.
type TermList struct {
autorest.Response `json:"-"`
// ID - Term list Id.
ID *int32 `json:"Id,omitempty"`
// Name - Term list name.
Name *string `json:"Name,omitempty"`
// Description - Description for term list.
Description *string `json:"Description,omitempty"`
// Metadata - Term list metadata.
Metadata *TermListMetadata `json:"Metadata,omitempty"`
}
// TermListMetadata term list metadata.
type TermListMetadata struct {
// KeyOne - Optional Key value pair to describe your list.
KeyOne *string `json:"Key One,omitempty"`
// KeyTwo - Optional Key value pair to describe your list.
KeyTwo *string `json:"Key Two,omitempty"`
}
// Terms terms properties.
type Terms struct {
autorest.Response `json:"-"`
// Data - Term data details.
Data *TermsData `json:"Data,omitempty"`
// Paging - Paging details.
Paging *TermsPaging `json:"Paging,omitempty"`
}
// TermsData all term Id response properties.
type TermsData struct {
// Language - Language of the terms.
Language *string `json:"Language,omitempty"`
// Terms - List of terms.
Terms *[]TermsInList `json:"Terms,omitempty"`
// Status - Term Status.
Status *Status `json:"Status,omitempty"`
// TrackingID - Tracking Id.
TrackingID *string `json:"TrackingId,omitempty"`
}
// TermsInList terms in list Id passed.
type TermsInList struct {
// Term - Added term details.
Term *string `json:"Term,omitempty"`
}
// TermsPaging paging details.
type TermsPaging struct {
// Total - Total details.
Total *int32 `json:"Total,omitempty"`
// Limit - Limit details.
Limit *int32 `json:"Limit,omitempty"`
// Offset - Offset details.
Offset *int32 `json:"Offset,omitempty"`
// Returned - Returned text details.
Returned *int32 `json:"Returned,omitempty"`
}
// TranscriptModerationBodyItem schema items of the body.
type TranscriptModerationBodyItem struct {
// Timestamp - Timestamp of the image.
Timestamp *string `json:"Timestamp,omitempty"`
// Terms - Optional metadata details.
Terms *[]TranscriptModerationBodyItemTermsItem `json:"Terms,omitempty"`
}
// TranscriptModerationBodyItemTermsItem ...
type TranscriptModerationBodyItemTermsItem struct {
// Index - Index of the word
Index *int32 `json:"Index,omitempty"`
// Term - Detected word.
Term *string `json:"Term,omitempty"`
}
// VideoFrameBodyItem schema items of the body.
type VideoFrameBodyItem struct {
// Timestamp - Timestamp of the frame.
Timestamp *string `json:"Timestamp,omitempty"`
// FrameImage - Content to review.
FrameImage *string `json:"FrameImage,omitempty"`
ReviewerResultTags *[]VideoFrameBodyItemReviewerResultTagsItem `json:"ReviewerResultTags,omitempty"`
// Metadata - Optional metadata details.
Metadata *[]VideoFrameBodyItemMetadataItem `json:"Metadata,omitempty"`
}
// VideoFrameBodyItemMetadataItem ...
type VideoFrameBodyItemMetadataItem struct {
// Key - Your key parameter.
Key *string `json:"Key,omitempty"`
// Value - Your value parameter.
Value *string `json:"Value,omitempty"`
}
// VideoFrameBodyItemReviewerResultTagsItem ...
type VideoFrameBodyItemReviewerResultTagsItem struct {
// Key - Your key parameter.
Key *string `json:"Key,omitempty"`
// Value - Your value parameter.
Value *string `json:"Value,omitempty"`
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,193 @@
package contentmoderator
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// TextModerationClient is the you use the API to scan your content as it is generated. Content Moderator then
// processes your content and sends the results along with relevant information either back to your systems or to the
// built-in review tool. You can use this information to take decisions e.g. take it down, send to human judge, etc.
//
// When using the API, images need to have a minimum of 128 pixels and a maximum file size of 4MB.
// Text can be at most 1024 characters long.
// If the content passed to the text API or the image API exceeds the size limits, the API will return an error code
// that informs about the issue.
//
// This API is currently available in:
//
// * West US - westus.api.cognitive.microsoft.com
// * East US 2 - eastus2.api.cognitive.microsoft.com
// * West Central US - westcentralus.api.cognitive.microsoft.com
// * West Europe - westeurope.api.cognitive.microsoft.com
// * Southeast Asia - southeastasia.api.cognitive.microsoft.com .
type TextModerationClient struct {
BaseClient
}
// NewTextModerationClient creates an instance of the TextModerationClient client.
func NewTextModerationClient(baseURL AzureRegionBaseURL) TextModerationClient {
return TextModerationClient{New(baseURL)}
}
// DetectLanguage this operation will detect the language of given input content. Returns the <a
// href="http://www-01.sil.org/iso639-3/codes.asp">ISO 639-3 code</a> for the predominant language comprising the
// submitted text. Over 110 languages supported.
//
// textContentType is the content type. textContent is content to screen.
func (client TextModerationClient) DetectLanguage(ctx context.Context, textContentType string, textContent string) (result DetectedLanguage, err error) {
req, err := client.DetectLanguagePreparer(ctx, textContentType, textContent)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.TextModerationClient", "DetectLanguage", nil, "Failure preparing request")
return
}
resp, err := client.DetectLanguageSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.TextModerationClient", "DetectLanguage", resp, "Failure sending request")
return
}
result, err = client.DetectLanguageResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.TextModerationClient", "DetectLanguage", resp, "Failure responding to request")
}
return
}
// DetectLanguagePreparer prepares the DetectLanguage request.
func (client TextModerationClient) DetectLanguagePreparer(ctx context.Context, textContentType string, textContent string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/moderate/v1.0/ProcessText/DetectLanguage"),
autorest.WithJSON(textContent),
autorest.WithHeader("Content-Type", autorest.String(textContentType)))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DetectLanguageSender sends the DetectLanguage request. The method will close the
// http.Response Body if it receives an error.
func (client TextModerationClient) DetectLanguageSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DetectLanguageResponder handles the response to the DetectLanguage request. The method always
// closes the http.Response Body.
func (client TextModerationClient) DetectLanguageResponder(resp *http.Response) (result DetectedLanguage, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ScreenText detects profanity in more than 100 languages and match against custom and shared blacklists.
//
// language is language of the terms. textContentType is the content type. textContent is content to screen.
// autocorrect is autocorrect text. pii is detect personal identifiable information. listID is the list Id. classify is
// classify input.
func (client TextModerationClient) ScreenText(ctx context.Context, language string, textContentType string, textContent string, autocorrect *bool, pii *bool, listID string, classify *bool) (result Screen, err error) {
req, err := client.ScreenTextPreparer(ctx, language, textContentType, textContent, autocorrect, pii, listID, classify)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.TextModerationClient", "ScreenText", nil, "Failure preparing request")
return
}
resp, err := client.ScreenTextSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "contentmoderator.TextModerationClient", "ScreenText", resp, "Failure sending request")
return
}
result, err = client.ScreenTextResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "contentmoderator.TextModerationClient", "ScreenText", resp, "Failure responding to request")
}
return
}
// ScreenTextPreparer prepares the ScreenText request.
func (client TextModerationClient) ScreenTextPreparer(ctx context.Context, language string, textContentType string, textContent string, autocorrect *bool, pii *bool, listID string, classify *bool) (*http.Request, error) {
urlParameters := map[string]interface{}{
"baseUrl": client.BaseURL,
}
queryParameters := map[string]interface{}{
"language": autorest.Encode("query", language),
}
if autocorrect != nil {
queryParameters["autocorrect"] = autorest.Encode("query", *autocorrect)
}
if pii != nil {
queryParameters["PII"] = autorest.Encode("query", *pii)
}
if len(listID) > 0 {
queryParameters["listId"] = autorest.Encode("query", listID)
}
if classify != nil {
queryParameters["classify"] = autorest.Encode("query", *classify)
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{baseUrl}", urlParameters),
autorest.WithPath("/contentmoderator/moderate/v1.0/ProcessText/Screen/"),
autorest.WithJSON(textContent),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("Content-Type", autorest.String(textContentType)))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ScreenTextSender sends the ScreenText request. The method will close the
// http.Response Body if it receives an error.
func (client TextModerationClient) ScreenTextSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// ScreenTextResponder handles the response to the ScreenText request. The method always
// closes the http.Response Body.
func (client TextModerationClient) ScreenTextResponder(resp *http.Response) (result Screen, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,28 @@
package contentmoderator
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/v12.2.0-beta services"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v12.2.0-beta"
}
@@ -0,0 +1,50 @@
// Package customsearch implements the Azure ARM Customsearch service API version 1.0.
//
// The Bing Custom Search API lets you send a search query to Bing and get back search results customized to meet your
// custom search definition.
package customsearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
const (
// DefaultBaseURI is the default URI used for the service Customsearch
DefaultBaseURI = "https://api.cognitive.microsoft.com/bingcustomsearch/v7.0"
)
// BaseClient is the base client for Customsearch.
type BaseClient struct {
autorest.Client
BaseURI string
}
// New creates an instance of the BaseClient client.
func New() BaseClient {
return NewWithBaseURI(DefaultBaseURI)
}
// NewWithBaseURI creates an instance of the BaseClient client.
func NewWithBaseURI(baseURI string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
}
}
@@ -0,0 +1,256 @@
package customsearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// CustomInstanceClient is the the Bing Custom Search API lets you send a search query to Bing and get back search
// results customized to meet your custom search definition.
type CustomInstanceClient struct {
BaseClient
}
// NewCustomInstanceClient creates an instance of the CustomInstanceClient client.
func NewCustomInstanceClient() CustomInstanceClient {
return NewCustomInstanceClientWithBaseURI(DefaultBaseURI)
}
// NewCustomInstanceClientWithBaseURI creates an instance of the CustomInstanceClient client.
func NewCustomInstanceClientWithBaseURI(baseURI string) CustomInstanceClient {
return CustomInstanceClient{NewWithBaseURI(baseURI)}
}
// Search sends the search request.
//
// xBingApisSDK is activate swagger compliance query is the user's search query term. The term may not be empty. The
// term may contain Bing Advanced Operators. For example, to limit results to a specific domain, use the site:
// operator. acceptLanguage is a comma-delimited list of one or more languages to use for user interface strings. The
// list is in decreasing order of preference. For additional information, including expected format, see
// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the setLang query parameter are
// mutually exclusive; do not specify both. If you set this header, you must also specify the cc query parameter. Bing
// will use the first supported language it finds from the list, and combine that language with the cc parameter value
// to determine the market to return results for. If the list does not include a supported language, Bing will find the
// closest language and market that supports the request, and may use an aggregated or default market for the results
// instead of a specified one. You should use this header and the cc query parameter only if you specify multiple
// languages; otherwise, you should use the mkt and setLang query parameters. A user interface string is a string
// that's used as a label in a user interface. There are very few user interface strings in the JSON response objects.
// Any links in the response objects to Bing.com properties will apply the specified language. userAgent is the user
// agent originating the request. Bing uses the user agent to provide mobile users with an optimized experience.
// Although optional, you are strongly encouraged to always specify this header. The user-agent should be the same
// string that any commonly used browser would send. For information about user agents, see [RFC
// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). clientID is bing uses this header to provide users
// with consistent behavior across Bing API calls. Bing often flights new features and improvements, and it uses the
// client ID as a key for assigning traffic on different flights. If you do not use the same client ID for a user
// across multiple requests, then Bing may assign the user to multiple conflicting flights. Being assigned to multiple
// conflicting flights can lead to an inconsistent user experience. For example, if the second request has a different
// flight assignment than the first, the experience may be unexpected. Also, Bing can use the client ID to tailor web
// results to that client ID’s search history, providing a richer experience for the user. Bing also uses this header
// to help improve result rankings by analyzing the activity generated by a client ID. The relevance improvements help
// with better quality of results delivered by Bing APIs and in turn enables higher click-through rates for the API
// consumer. IMPORTANT: Although optional, you should consider this header required. Persisting the client ID across
// multiple requests for the same end user and device combination enables 1) the API consumer to receive a consistent
// user experience, and 2) higher click-through rates via better quality of results from the Bing APIs. Each user that
// uses your application on the device must have a unique, Bing generated client ID. If you do not include this header
// in the request, Bing generates an ID and returns it in the X-MSEdge-ClientID response header. The only time that you
// should NOT include this header in a request is the first time the user uses your app on that device. Use the client
// ID for each Bing API request that your app makes for this user on the device. Persist the client ID. To persist the
// ID in a browser app, use a persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session
// cookie. For other apps such as mobile apps, use the device's persistent storage to persist the ID. The next time the
// user uses your app on that device, get the client ID that you persisted. Bing responses may or may not include this
// header. If the response includes this header, capture the client ID and use it for all subsequent Bing requests for
// the user on that device. If you include the X-MSEdge-ClientID, you must not include cookies in the request. clientIP
// is the IPv4 or IPv6 address of the client device. The IP address is used to discover the user's location. Bing uses
// the location information to determine safe search behavior. Although optional, you are encouraged to always specify
// this header and the X-Search-Location header. Do not obfuscate the address (for example, by changing the last octet
// to 0). Obfuscating the address results in the location not being anywhere near the device's actual location, which
// may result in Bing serving erroneous results. location is a semicolon-delimited list of key/value pairs that
// describe the client's geographical location. Bing uses the location information to determine safe search behavior
// and to return relevant local content. Specify the key/value pair as <key>:<value>. The following are the keys that
// you use to specify the user's location. lat (required): The latitude of the client's location, in degrees. The
// latitude must be greater than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern
// latitudes and positive values indicate northern latitudes. long (required): The longitude of the client's location,
// in degrees. The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative values
// indicate western longitudes and positive values indicate eastern longitudes. re (required): The radius, in meters,
// which specifies the horizontal accuracy of the coordinates. Pass the value returned by the device's location
// service. Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP
// lookup. ts (optional): The UTC UNIX timestamp of when the client was at the location. (The UNIX timestamp is the
// number of seconds since January 1, 1970.) head (optional): The client's relative heading or direction of travel.
// Specify the direction of travel as degrees from 0 through 360, counting clockwise relative to true north. Specify
// this key only if the sp key is nonzero. sp (optional): The horizontal velocity (speed), in meters per second, that
// the client device is traveling. alt (optional): The altitude of the client device, in meters. are (optional): The
// radius, in meters, that specifies the vertical accuracy of the coordinates. Specify this key only if you specify the
// alt key. Although many of the keys are optional, the more information that you provide, the more accurate the
// location results are. Although optional, you are encouraged to always specify the user's geographical location.
// Providing the location is especially important if the client's IP address does not accurately reflect the user's
// physical location (for example, if the client uses VPN). For optimal results, you should include this header and the
// X-MSEdge-ClientIP header, but at a minimum, you should include this header. customConfig is the identifier for the
// custom search configuration countryCode is a 2-character country code of the country where the results come from.
// This API supports only the United States market. If you specify this query parameter, it must be set to us. If you
// set this parameter, you must also specify the Accept-Language header. Bing uses the first supported language it
// finds from the languages list, and combine that language with the country code that you specify to determine the
// market to return results for. If the languages list does not include a supported language, Bing finds the closest
// language and market that supports the request, or it may use an aggregated or default market for the results instead
// of a specified one. You should use this query parameter and the Accept-Language query parameter only if you specify
// multiple languages; otherwise, you should use the mkt and setLang query parameters. This parameter and the mkt query
// parameter are mutually exclusive—do not specify both. count is the number of search results to return in the
// response. The default is 10 and the maximum value is 50. The actual number delivered may be less than requested.Use
// this parameter along with the offset parameter to page results.For example, if your user interface displays 10
// search results per page, set count to 10 and offset to 0 to get the first page of results. For each subsequent page,
// increment offset by 10 (for example, 0, 10, 20). It is possible for multiple pages to include some overlap in
// results. market is the market where the results come from. Typically, mkt is the country where the user is making
// the request from. However, it could be a different country if the user is not located in a country where Bing
// delivers results. The market must be in the form <language code>-<country code>. For example, en-US. The string is
// case insensitive. If known, you are encouraged to always specify the market. Specifying the market helps Bing route
// the request and return an appropriate and optimal response. If you specify a market that is not listed in Market
// Codes, Bing uses a best fit market code based on an internal mapping that is subject to change. This parameter and
// the cc query parameter are mutually exclusive—do not specify both. offset is the zero-based offset that indicates
// the number of search results to skip before returning results. The default is 0. The offset should be less than
// (totalEstimatedMatches - count). Use this parameter along with the count parameter to page results. For example, if
// your user interface displays 10 search results per page, set count to 10 and offset to 0 to get the first page of
// results. For each subsequent page, increment offset by 10 (for example, 0, 10, 20). it is possible for multiple
// pages to include some overlap in results. safeSearch is a filter used to filter adult content. Off: Return webpages
// with adult text, images, or videos. Moderate: Return webpages with adult text, but not adult images or videos.
// Strict: Do not return webpages with adult text, images, or videos. The default is Moderate. If the request comes
// from a market that Bing's adult policy requires that safeSearch is set to Strict, Bing ignores the safeSearch value
// and uses Strict. If you use the site: query operator, there is the chance that the response may contain adult
// content regardless of what the safeSearch query parameter is set to. Use site: only if you are aware of the content
// on the site and your scenario supports the possibility of adult content. setLang is the language to use for user
// interface strings. Specify the language using the ISO 639-1 2-letter language code. For example, the language code
// for English is EN. The default is EN (English). Although optional, you should always specify the language.
// Typically, you set setLang to the same language specified by mkt unless the user wants the user interface strings
// displayed in a different language. This parameter and the Accept-Language header are mutually exclusive; do not
// specify both. A user interface string is a string that's used as a label in a user interface. There are few user
// interface strings in the JSON response objects. Also, any links to Bing.com properties in the response objects apply
// the specified language. textDecorations is a Boolean value that determines whether display strings should contain
// decoration markers such as hit highlighting characters. If true, the strings may include markers. The default is
// false. To specify whether to use Unicode characters or HTML tags as the markers, see the textFormat query parameter.
// textFormat is the type of markers to use for text decorations (see the textDecorations query parameter). Possible
// values are Raw—Use Unicode characters to mark content that needs special formatting. The Unicode characters are in
// the range E000 through E019. For example, Bing uses E000 and E001 to mark the beginning and end of query terms for
// hit highlighting. HTML—Use HTML tags to mark content that needs special formatting. For example, use <b> tags to
// highlight query terms in display strings. The default is Raw. For display strings that contain escapable HTML
// characters such as <, >, and &, if textFormat is set to HTML, Bing escapes the characters as appropriate (for
// example, < is escaped to &lt;).
func (client CustomInstanceClient) Search(ctx context.Context, xBingApisSDK string, query string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, customConfig *int32, countryCode string, count *int32, market string, offset *int32, safeSearch SafeSearch, setLang string, textDecorations *bool, textFormat TextFormat) (result SearchResponse, err error) {
req, err := client.SearchPreparer(ctx, xBingApisSDK, query, acceptLanguage, userAgent, clientID, clientIP, location, customConfig, countryCode, count, market, offset, safeSearch, setLang, textDecorations, textFormat)
if err != nil {
err = autorest.NewErrorWithError(err, "customsearch.CustomInstanceClient", "Search", nil, "Failure preparing request")
return
}
resp, err := client.SearchSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "customsearch.CustomInstanceClient", "Search", resp, "Failure sending request")
return
}
result, err = client.SearchResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "customsearch.CustomInstanceClient", "Search", resp, "Failure responding to request")
}
return
}
// SearchPreparer prepares the Search request.
func (client CustomInstanceClient) SearchPreparer(ctx context.Context, xBingApisSDK string, query string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, customConfig *int32, countryCode string, count *int32, market string, offset *int32, safeSearch SafeSearch, setLang string, textDecorations *bool, textFormat TextFormat) (*http.Request, error) {
queryParameters := map[string]interface{}{
"q": autorest.Encode("query", query),
}
if customConfig != nil {
queryParameters["customConfig"] = autorest.Encode("query", *customConfig)
}
if len(countryCode) > 0 {
queryParameters["cc"] = autorest.Encode("query", countryCode)
}
if count != nil {
queryParameters["count"] = autorest.Encode("query", *count)
}
if len(market) > 0 {
queryParameters["mkt"] = autorest.Encode("query", market)
}
if offset != nil {
queryParameters["offset"] = autorest.Encode("query", *offset)
}
if len(string(safeSearch)) > 0 {
queryParameters["safeSearch"] = autorest.Encode("query", safeSearch)
}
if len(setLang) > 0 {
queryParameters["setLang"] = autorest.Encode("query", setLang)
}
if textDecorations != nil {
queryParameters["textDecorations"] = autorest.Encode("query", *textDecorations)
}
if len(string(textFormat)) > 0 {
queryParameters["textFormat"] = autorest.Encode("query", textFormat)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/search"),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("X-BingApis-SDK", autorest.String(xBingApisSDK)))
if len(acceptLanguage) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
}
if len(userAgent) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("User-Agent", autorest.String(userAgent)))
}
if len(clientID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
}
if len(clientIP) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
}
if len(location) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-Search-Location", autorest.String(location)))
}
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// SearchSender sends the Search request. The method will close the
// http.Response Body if it receives an error.
func (client CustomInstanceClient) SearchSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// SearchResponder handles the response to the Search request. The method always
// closes the http.Response Body.
func (client CustomInstanceClient) SearchResponder(resp *http.Response) (result SearchResponse, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,28 @@
package customsearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/v12.2.0-beta services"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v12.2.0-beta"
}
@@ -0,0 +1,52 @@
// Package entitysearch implements the Azure ARM Entitysearch service API version 1.0.
//
// The Entity Search API lets you send a search query to Bing and get back search results that include entities and
// places. Place results include restaurants, hotel, or other local businesses. For places, the query can specify the
// name of the local business or it can ask for a list (for example, restaurants near me). Entity results include
// persons, places, or things. Place in this context is tourist attractions, states, countries, etc.
package entitysearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
const (
// DefaultBaseURI is the default URI used for the service Entitysearch
DefaultBaseURI = "https://api.cognitive.microsoft.com/bing/v7.0"
)
// BaseClient is the base client for Entitysearch.
type BaseClient struct {
autorest.Client
BaseURI string
}
// New creates an instance of the BaseClient client.
func New() BaseClient {
return NewWithBaseURI(DefaultBaseURI)
}
// NewWithBaseURI creates an instance of the BaseClient client.
func NewWithBaseURI(baseURI string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
}
}
@@ -0,0 +1,234 @@
package entitysearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// EntitiesClient is the the Entity Search API lets you send a search query to Bing and get back search results that
// include entities and places. Place results include restaurants, hotel, or other local businesses. For places, the
// query can specify the name of the local business or it can ask for a list (for example, restaurants near me). Entity
// results include persons, places, or things. Place in this context is tourist attractions, states, countries, etc.
type EntitiesClient struct {
BaseClient
}
// NewEntitiesClient creates an instance of the EntitiesClient client.
func NewEntitiesClient() EntitiesClient {
return NewEntitiesClientWithBaseURI(DefaultBaseURI)
}
// NewEntitiesClientWithBaseURI creates an instance of the EntitiesClient client.
func NewEntitiesClientWithBaseURI(baseURI string) EntitiesClient {
return EntitiesClient{NewWithBaseURI(baseURI)}
}
// Search sends the search request.
//
// xBingApisSDK is activate swagger compliance query is the user's search term. acceptLanguage is a comma-delimited
// list of one or more languages to use for user interface strings. The list is in decreasing order of preference. For
// additional information, including expected format, see
// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the setLang query parameter are
// mutually exclusive; do not specify both. If you set this header, you must also specify the cc query parameter. Bing
// will use the first supported language it finds from the list, and combine that language with the cc parameter value
// to determine the market to return results for. If the list does not include a supported language, Bing will find the
// closest language and market that supports the request, and may use an aggregated or default market for the results
// instead of a specified one. You should use this header and the cc query parameter only if you specify multiple
// languages; otherwise, you should use the mkt and setLang query parameters. A user interface string is a string
// that's used as a label in a user interface. There are very few user interface strings in the JSON response objects.
// Any links in the response objects to Bing.com properties will apply the specified language. pragma is by default,
// Bing returns cached content, if available. To prevent Bing from returning cached content, set the Pragma header to
// no-cache (for example, Pragma: no-cache). userAgent is the user agent originating the request. Bing uses the user
// agent to provide mobile users with an optimized experience. Although optional, you are strongly encouraged to always
// specify this header. The user-agent should be the same string that any commonly used browser would send. For
// information about user agents, see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). clientID is
// bing uses this header to provide users with consistent behavior across Bing API calls. Bing often flights new
// features and improvements, and it uses the client ID as a key for assigning traffic on different flights. If you do
// not use the same client ID for a user across multiple requests, then Bing may assign the user to multiple
// conflicting flights. Being assigned to multiple conflicting flights can lead to an inconsistent user experience. For
// example, if the second request has a different flight assignment than the first, the experience may be unexpected.
// Also, Bing can use the client ID to tailor web results to that client ID’s search history, providing a richer
// experience for the user. Bing also uses this header to help improve result rankings by analyzing the activity
// generated by a client ID. The relevance improvements help with better quality of results delivered by Bing APIs and
// in turn enables higher click-through rates for the API consumer. IMPORTANT: Although optional, you should consider
// this header required. Persisting the client ID across multiple requests for the same end user and device combination
// enables 1) the API consumer to receive a consistent user experience, and 2) higher click-through rates via better
// quality of results from the Bing APIs. Each user that uses your application on the device must have a unique, Bing
// generated client ID. If you do not include this header in the request, Bing generates an ID and returns it in the
// X-MSEdge-ClientID response header. The only time that you should NOT include this header in a request is the first
// time the user uses your app on that device. Use the client ID for each Bing API request that your app makes for this
// user on the device. Persist the client ID. To persist the ID in a browser app, use a persistent HTTP cookie to
// ensure the ID is used across all sessions. Do not use a session cookie. For other apps such as mobile apps, use the
// device's persistent storage to persist the ID. The next time the user uses your app on that device, get the client
// ID that you persisted. Bing responses may or may not include this header. If the response includes this header,
// capture the client ID and use it for all subsequent Bing requests for the user on that device. If you include the
// X-MSEdge-ClientID, you must not include cookies in the request. clientIP is the IPv4 or IPv6 address of the client
// device. The IP address is used to discover the user's location. Bing uses the location information to determine safe
// search behavior. Although optional, you are encouraged to always specify this header and the X-Search-Location
// header. Do not obfuscate the address (for example, by changing the last octet to 0). Obfuscating the address results
// in the location not being anywhere near the device's actual location, which may result in Bing serving erroneous
// results. location is a semicolon-delimited list of key/value pairs that describe the client's geographical location.
// Bing uses the location information to determine safe search behavior and to return relevant local content. Specify
// the key/value pair as <key>:<value>. The following are the keys that you use to specify the user's location. lat
// (required): The latitude of the client's location, in degrees. The latitude must be greater than or equal to -90.0
// and less than or equal to +90.0. Negative values indicate southern latitudes and positive values indicate northern
// latitudes. long (required): The longitude of the client's location, in degrees. The longitude must be greater than
// or equal to -180.0 and less than or equal to +180.0. Negative values indicate western longitudes and positive values
// indicate eastern longitudes. re (required): The radius, in meters, which specifies the horizontal accuracy of the
// coordinates. Pass the value returned by the device's location service. Typical values might be 22m for GPS/Wi-Fi,
// 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts (optional): The UTC UNIX timestamp of when
// the client was at the location. (The UNIX timestamp is the number of seconds since January 1, 1970.) head
// (optional): The client's relative heading or direction of travel. Specify the direction of travel as degrees from 0
// through 360, counting clockwise relative to true north. Specify this key only if the sp key is nonzero. sp
// (optional): The horizontal velocity (speed), in meters per second, that the client device is traveling. alt
// (optional): The altitude of the client device, in meters. are (optional): The radius, in meters, that specifies the
// vertical accuracy of the coordinates. Specify this key only if you specify the alt key. Although many of the keys
// are optional, the more information that you provide, the more accurate the location results are. Although optional,
// you are encouraged to always specify the user's geographical location. Providing the location is especially
// important if the client's IP address does not accurately reflect the user's physical location (for example, if the
// client uses VPN). For optimal results, you should include this header and the X-MSEdge-ClientIP header, but at a
// minimum, you should include this header. countryCode is a 2-character country code of the country where the results
// come from. This API supports only the United States market. If you specify this query parameter, it must be set to
// us. If you set this parameter, you must also specify the Accept-Language header. Bing uses the first supported
// language it finds from the languages list, and combine that language with the country code that you specify to
// determine the market to return results for. If the languages list does not include a supported language, Bing finds
// the closest language and market that supports the request, or it may use an aggregated or default market for the
// results instead of a specified one. You should use this query parameter and the Accept-Language query parameter only
// if you specify multiple languages; otherwise, you should use the mkt and setLang query parameters. This parameter
// and the mkt query parameter are mutually exclusive—do not specify both. market is the market where the results come
// from. You are strongly encouraged to always specify the market, if known. Specifying the market helps Bing route the
// request and return an appropriate and optimal response. This parameter and the cc query parameter are mutually
// exclusive—do not specify both. responseFilter is a comma-delimited list of answers to include in the response. If
// you do not specify this parameter, the response includes all search answers for which there's relevant data.
// responseFormat is the media type to use for the response. The following are the possible case-insensitive values:
// JSON, JSONLD. The default is JSON. If you specify JSONLD, the response body includes JSON-LD objects that contain
// the search results. safeSearch is a filter used to filter adult content. Off: Return webpages with adult text,
// images, or videos. Moderate: Return webpages with adult text, but not adult images or videos. Strict: Do not return
// webpages with adult text, images, or videos. The default is Moderate. If the request comes from a market that Bing's
// adult policy requires that safeSearch is set to Strict, Bing ignores the safeSearch value and uses Strict. If you
// use the site: query operator, there is the chance that the response may contain adult content regardless of what the
// safeSearch query parameter is set to. Use site: only if you are aware of the content on the site and your scenario
// supports the possibility of adult content. setLang is the language to use for user interface strings. Specify the
// language using the ISO 639-1 2-letter language code. For example, the language code for English is EN. The default
// is EN (English). Although optional, you should always specify the language. Typically, you set setLang to the same
// language specified by mkt unless the user wants the user interface strings displayed in a different language. This
// parameter and the Accept-Language header are mutually exclusive; do not specify both. A user interface string is a
// string that's used as a label in a user interface. There are few user interface strings in the JSON response
// objects. Also, any links to Bing.com properties in the response objects apply the specified language.
func (client EntitiesClient) Search(ctx context.Context, xBingApisSDK string, 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) {
req, err := client.SearchPreparer(ctx, xBingApisSDK, query, acceptLanguage, pragma, userAgent, clientID, clientIP, location, countryCode, market, responseFilter, responseFormat, safeSearch, setLang)
if err != nil {
err = autorest.NewErrorWithError(err, "entitysearch.EntitiesClient", "Search", nil, "Failure preparing request")
return
}
resp, err := client.SearchSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "entitysearch.EntitiesClient", "Search", resp, "Failure sending request")
return
}
result, err = client.SearchResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "entitysearch.EntitiesClient", "Search", resp, "Failure responding to request")
}
return
}
// SearchPreparer prepares the Search request.
func (client EntitiesClient) SearchPreparer(ctx context.Context, xBingApisSDK string, 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) {
queryParameters := map[string]interface{}{
"q": autorest.Encode("query", query),
}
if len(countryCode) > 0 {
queryParameters["cc"] = autorest.Encode("query", countryCode)
}
if len(market) > 0 {
queryParameters["mkt"] = autorest.Encode("query", market)
}
if responseFilter != nil && len(responseFilter) > 0 {
queryParameters["ResponseFilter"] = autorest.Encode("query", responseFilter, ",")
}
if responseFormat != nil && len(responseFormat) > 0 {
queryParameters["ResponseFormat"] = autorest.Encode("query", responseFormat, ",")
}
if len(string(safeSearch)) > 0 {
queryParameters["SafeSearch"] = autorest.Encode("query", safeSearch)
}
if len(setLang) > 0 {
queryParameters["SetLang"] = autorest.Encode("query", setLang)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/entities"),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("X-BingApis-SDK", autorest.String(xBingApisSDK)))
if len(acceptLanguage) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
}
if len(pragma) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Pragma", autorest.String(pragma)))
}
if len(userAgent) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("User-Agent", autorest.String(userAgent)))
}
if len(clientID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
}
if len(clientIP) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
}
if len(location) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-Search-Location", autorest.String(location)))
}
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// SearchSender sends the Search request. The method will close the
// http.Response Body if it receives an error.
func (client EntitiesClient) SearchSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// SearchResponder handles the response to the Search request. The method always
// closes the http.Response Body.
func (client EntitiesClient) SearchResponder(resp *http.Response) (result SearchResponse, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,28 @@
package entitysearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/v12.2.0-beta services"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v12.2.0-beta"
}
@@ -0,0 +1,44 @@
// Package face implements the Azure ARM Face service API version 1.0.
//
// An API for face detection, verification, and identification.
package face
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
// BaseClient is the base client for Face.
type BaseClient struct {
autorest.Client
AzureRegion AzureRegions
}
// New creates an instance of the BaseClient client.
func New(azureRegion AzureRegions) BaseClient {
return NewWithoutDefaults(azureRegion)
}
// NewWithoutDefaults creates an instance of the BaseClient client.
func NewWithoutDefaults(azureRegion AzureRegions) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
AzureRegion: azureRegion,
}
}
@@ -0,0 +1,559 @@
package face
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"io"
"net/http"
)
// Client is the an API for face detection, verification, and identification.
type Client struct {
BaseClient
}
// NewClient creates an instance of the Client client.
func NewClient(azureRegion AzureRegions) Client {
return Client{New(azureRegion)}
}
// Detect detect human faces in an image and returns face locations, and optionally with faceIds, landmarks, and
// attributes.
//
// imageURL is a JSON document with a URL pointing to the image that is to be analyzed. returnFaceID is a value
// indicating whether the operation should return faceIds of detected faces. returnFaceLandmarks is a value indicating
// whether the operation should return landmarks of the detected faces. returnFaceAttributes is analyze and return the
// one or more specified face attributes in the comma-separated string like "returnFaceAttributes=age,gender".
// Supported face attributes include age, gender, headPose, smile, facialHair, glasses and emotion. Note that each face
// attribute analysis has additional computational and time cost.
func (client Client) Detect(ctx context.Context, imageURL ImageURL, returnFaceID *bool, returnFaceLandmarks *bool, returnFaceAttributes []AttributeTypes) (result ListDetectedFace, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: imageURL,
Constraints: []validation.Constraint{{Target: "imageURL.URL", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.Client", "Detect")
}
req, err := client.DetectPreparer(ctx, imageURL, returnFaceID, returnFaceLandmarks, returnFaceAttributes)
if err != nil {
err = autorest.NewErrorWithError(err, "face.Client", "Detect", nil, "Failure preparing request")
return
}
resp, err := client.DetectSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.Client", "Detect", resp, "Failure sending request")
return
}
result, err = client.DetectResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.Client", "Detect", resp, "Failure responding to request")
}
return
}
// DetectPreparer prepares the Detect request.
func (client Client) DetectPreparer(ctx context.Context, imageURL ImageURL, returnFaceID *bool, returnFaceLandmarks *bool, returnFaceAttributes []AttributeTypes) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
queryParameters := map[string]interface{}{}
if returnFaceID != nil {
queryParameters["returnFaceId"] = autorest.Encode("query", *returnFaceID)
}
if returnFaceLandmarks != nil {
queryParameters["returnFaceLandmarks"] = autorest.Encode("query", *returnFaceLandmarks)
}
if returnFaceAttributes != nil && len(returnFaceAttributes) > 0 {
queryParameters["returnFaceAttributes"] = autorest.Encode("query", returnFaceAttributes, ",")
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPath("/detect"),
autorest.WithJSON(imageURL),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DetectSender sends the Detect request. The method will close the
// http.Response Body if it receives an error.
func (client Client) DetectSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DetectResponder handles the response to the Detect request. The method always
// closes the http.Response Body.
func (client Client) DetectResponder(resp *http.Response) (result ListDetectedFace, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// DetectInStream detect human faces in an image and returns face locations, and optionally with faceIds, landmarks,
// and attributes.
//
// imageParameter is an image stream. imageParameter will be closed upon successful return. Callers should ensure
// closure when receiving an error.returnFaceID is a value indicating whether the operation should return faceIds of
// detected faces. returnFaceLandmarks is a value indicating whether the operation should return landmarks of the
// detected faces. returnFaceAttributes is analyze and return the one or more specified face attributes in the
// comma-separated string like "returnFaceAttributes=age,gender". Supported face attributes include age, gender,
// headPose, smile, facialHair, glasses and emotion. Note that each face attribute analysis has additional
// computational and time cost.
func (client Client) DetectInStream(ctx context.Context, imageParameter io.ReadCloser, returnFaceID *bool, returnFaceLandmarks *bool, returnFaceAttributes []AttributeTypes) (result ListDetectedFace, err error) {
req, err := client.DetectInStreamPreparer(ctx, imageParameter, returnFaceID, returnFaceLandmarks, returnFaceAttributes)
if err != nil {
err = autorest.NewErrorWithError(err, "face.Client", "DetectInStream", nil, "Failure preparing request")
return
}
resp, err := client.DetectInStreamSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.Client", "DetectInStream", resp, "Failure sending request")
return
}
result, err = client.DetectInStreamResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.Client", "DetectInStream", resp, "Failure responding to request")
}
return
}
// DetectInStreamPreparer prepares the DetectInStream request.
func (client Client) DetectInStreamPreparer(ctx context.Context, imageParameter io.ReadCloser, returnFaceID *bool, returnFaceLandmarks *bool, returnFaceAttributes []AttributeTypes) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
queryParameters := map[string]interface{}{}
if returnFaceID != nil {
queryParameters["returnFaceId"] = autorest.Encode("query", *returnFaceID)
}
if returnFaceLandmarks != nil {
queryParameters["returnFaceLandmarks"] = autorest.Encode("query", *returnFaceLandmarks)
}
if returnFaceAttributes != nil && len(returnFaceAttributes) > 0 {
queryParameters["returnFaceAttributes"] = autorest.Encode("query", returnFaceAttributes, ",")
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPath("/detect"),
autorest.WithFile(imageParameter),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DetectInStreamSender sends the DetectInStream request. The method will close the
// http.Response Body if it receives an error.
func (client Client) DetectInStreamSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DetectInStreamResponder handles the response to the DetectInStream request. The method always
// closes the http.Response Body.
func (client Client) DetectInStreamResponder(resp *http.Response) (result ListDetectedFace, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// FindSimilar given query face's faceId, find the similar-looking faces from a faceId array or a faceListId.
//
// body is request body for Find Similar.
func (client Client) FindSimilar(ctx context.Context, body FindSimilarRequest) (result ListSimilarFaceResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: body,
Constraints: []validation.Constraint{{Target: "body.FaceID", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "body.FaceID", Name: validation.MaxLength, Rule: 64, Chain: nil}}},
{Target: "body.FaceListID", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "body.FaceListID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "body.FaceListID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil},
}},
{Target: "body.FaceIds", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "body.FaceIds", Name: validation.MaxItems, Rule: 1000, Chain: nil}}},
{Target: "body.MaxNumOfCandidatesReturned", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "body.MaxNumOfCandidatesReturned", Name: validation.InclusiveMaximum, Rule: 1000, Chain: nil},
{Target: "body.MaxNumOfCandidatesReturned", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil},
}}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.Client", "FindSimilar")
}
req, err := client.FindSimilarPreparer(ctx, body)
if err != nil {
err = autorest.NewErrorWithError(err, "face.Client", "FindSimilar", nil, "Failure preparing request")
return
}
resp, err := client.FindSimilarSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.Client", "FindSimilar", resp, "Failure sending request")
return
}
result, err = client.FindSimilarResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.Client", "FindSimilar", resp, "Failure responding to request")
}
return
}
// FindSimilarPreparer prepares the FindSimilar request.
func (client Client) FindSimilarPreparer(ctx context.Context, body FindSimilarRequest) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPath("/findsimilars"),
autorest.WithJSON(body))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// FindSimilarSender sends the FindSimilar request. The method will close the
// http.Response Body if it receives an error.
func (client Client) FindSimilarSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// FindSimilarResponder handles the response to the FindSimilar request. The method always
// closes the http.Response Body.
func (client Client) FindSimilarResponder(resp *http.Response) (result ListSimilarFaceResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Group divide candidate faces into groups based on face similarity.
//
// body is request body for grouping.
func (client Client) Group(ctx context.Context, body GroupRequest) (result GroupResponse, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: body,
Constraints: []validation.Constraint{{Target: "body.FaceIds", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "body.FaceIds", Name: validation.MaxItems, Rule: 1000, Chain: nil}}}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.Client", "Group")
}
req, err := client.GroupPreparer(ctx, body)
if err != nil {
err = autorest.NewErrorWithError(err, "face.Client", "Group", nil, "Failure preparing request")
return
}
resp, err := client.GroupSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.Client", "Group", resp, "Failure sending request")
return
}
result, err = client.GroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.Client", "Group", resp, "Failure responding to request")
}
return
}
// GroupPreparer prepares the Group request.
func (client Client) GroupPreparer(ctx context.Context, body GroupRequest) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPath("/group"),
autorest.WithJSON(body))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GroupSender sends the Group request. The method will close the
// http.Response Body if it receives an error.
func (client Client) GroupSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// GroupResponder handles the response to the Group request. The method always
// closes the http.Response Body.
func (client Client) GroupResponder(resp *http.Response) (result GroupResponse, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Identify identify unknown faces from a person group.
//
// body is request body for identify operation.
func (client Client) Identify(ctx context.Context, body IdentifyRequest) (result ListIdentifyResultItem, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: body,
Constraints: []validation.Constraint{{Target: "body.PersonGroupID", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "body.PersonGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "body.PersonGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil},
}},
{Target: "body.FaceIds", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "body.FaceIds", Name: validation.MaxItems, Rule: 1000, Chain: nil}}},
{Target: "body.MaxNumOfCandidatesReturned", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "body.MaxNumOfCandidatesReturned", Name: validation.InclusiveMaximum, Rule: 1000, Chain: nil},
{Target: "body.MaxNumOfCandidatesReturned", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil},
}}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.Client", "Identify")
}
req, err := client.IdentifyPreparer(ctx, body)
if err != nil {
err = autorest.NewErrorWithError(err, "face.Client", "Identify", nil, "Failure preparing request")
return
}
resp, err := client.IdentifySender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.Client", "Identify", resp, "Failure sending request")
return
}
result, err = client.IdentifyResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.Client", "Identify", resp, "Failure responding to request")
}
return
}
// IdentifyPreparer prepares the Identify request.
func (client Client) IdentifyPreparer(ctx context.Context, body IdentifyRequest) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPath("/identify"),
autorest.WithJSON(body))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// IdentifySender sends the Identify request. The method will close the
// http.Response Body if it receives an error.
func (client Client) IdentifySender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// IdentifyResponder handles the response to the Identify request. The method always
// closes the http.Response Body.
func (client Client) IdentifyResponder(resp *http.Response) (result ListIdentifyResultItem, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Verify verify whether two faces belong to a same person or whether one face belongs to a person.
//
// body is request body for verify operation.
func (client Client) Verify(ctx context.Context, body VerifyRequest) (result VerifyResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: body,
Constraints: []validation.Constraint{{Target: "body.FaceID1", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "body.FaceID1", Name: validation.MaxLength, Rule: 64, Chain: nil}}},
{Target: "body.FaceID2", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "body.FaceID2", Name: validation.MaxLength, Rule: 64, Chain: nil}}}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.Client", "Verify")
}
req, err := client.VerifyPreparer(ctx, body)
if err != nil {
err = autorest.NewErrorWithError(err, "face.Client", "Verify", nil, "Failure preparing request")
return
}
resp, err := client.VerifySender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.Client", "Verify", resp, "Failure sending request")
return
}
result, err = client.VerifyResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.Client", "Verify", resp, "Failure responding to request")
}
return
}
// VerifyPreparer prepares the Verify request.
func (client Client) VerifyPreparer(ctx context.Context, body VerifyRequest) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPath("/verify"),
autorest.WithJSON(body))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// VerifySender sends the Verify request. The method will close the
// http.Response Body if it receives an error.
func (client Client) VerifySender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// VerifyResponder handles the response to the Verify request. The method always
// closes the http.Response Body.
func (client Client) VerifyResponder(resp *http.Response) (result VerifyResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// VerifyWithPersonGroup verify whether two faces belong to a same person. Compares a face Id with a Person Id
//
// body is request body for verifying two faces in a person group
func (client Client) VerifyWithPersonGroup(ctx context.Context, body VerifyPersonGroupRequest) (result VerifyResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: body,
Constraints: []validation.Constraint{{Target: "body.FaceID", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "body.FaceID", Name: validation.MaxLength, Rule: 64, Chain: nil}}},
{Target: "body.PersonID", Name: validation.Null, Rule: true, Chain: nil},
{Target: "body.PersonGroupID", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "body.PersonGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "body.PersonGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil},
}}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.Client", "VerifyWithPersonGroup")
}
req, err := client.VerifyWithPersonGroupPreparer(ctx, body)
if err != nil {
err = autorest.NewErrorWithError(err, "face.Client", "VerifyWithPersonGroup", nil, "Failure preparing request")
return
}
resp, err := client.VerifyWithPersonGroupSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.Client", "VerifyWithPersonGroup", resp, "Failure sending request")
return
}
result, err = client.VerifyWithPersonGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.Client", "VerifyWithPersonGroup", resp, "Failure responding to request")
}
return
}
// VerifyWithPersonGroupPreparer prepares the VerifyWithPersonGroup request.
func (client Client) VerifyWithPersonGroupPreparer(ctx context.Context, body VerifyPersonGroupRequest) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPath("/verify"),
autorest.WithJSON(body))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// VerifyWithPersonGroupSender sends the VerifyWithPersonGroup request. The method will close the
// http.Response Body if it receives an error.
func (client Client) VerifyWithPersonGroupSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// VerifyWithPersonGroupResponder handles the response to the VerifyWithPersonGroup request. The method always
// closes the http.Response Body.
func (client Client) VerifyWithPersonGroupResponder(resp *http.Response) (result VerifyResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,623 @@
package face
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"io"
"net/http"
)
// ListClient is the an API for face detection, verification, and identification.
type ListClient struct {
BaseClient
}
// NewListClient creates an instance of the ListClient client.
func NewListClient(azureRegion AzureRegions) ListClient {
return ListClient{New(azureRegion)}
}
// AddFace add a face to a face list. The input face is specified as an image with a targetFace rectangle. It returns a
// persistedFaceId representing the added face, and persistedFaceId will not expire.
//
// faceListID is id referencing a Face List. imageURL is a JSON document with a URL pointing to the image that is to be
// analyzed. userData is user-specified data about the face list for any purpose. The maximum length is 1KB. targetFace
// is a face rectangle to specify the target face to be added to a person in the format of
// "targetFace=left,top,width,height". E.g. "targetFace=10,10,100,100". If there is more than one face in the image,
// targetFace is required to specify which face to add. No targetFace means there is only one face detected in the
// entire image.
func (client ListClient) AddFace(ctx context.Context, faceListID string, imageURL ImageURL, userData string, targetFace []int32) (result PersistedFaceResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: faceListID,
Constraints: []validation.Constraint{{Target: "faceListID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "faceListID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}},
{TargetValue: userData,
Constraints: []validation.Constraint{{Target: "userData", Name: validation.MaxLength, Rule: 1024, Chain: nil}}},
{TargetValue: imageURL,
Constraints: []validation.Constraint{{Target: "imageURL.URL", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.ListClient", "AddFace")
}
req, err := client.AddFacePreparer(ctx, faceListID, imageURL, userData, targetFace)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "AddFace", nil, "Failure preparing request")
return
}
resp, err := client.AddFaceSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.ListClient", "AddFace", resp, "Failure sending request")
return
}
result, err = client.AddFaceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "AddFace", resp, "Failure responding to request")
}
return
}
// AddFacePreparer prepares the AddFace request.
func (client ListClient) AddFacePreparer(ctx context.Context, faceListID string, imageURL ImageURL, userData string, targetFace []int32) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"faceListId": autorest.Encode("path", faceListID),
}
queryParameters := map[string]interface{}{}
if len(userData) > 0 {
queryParameters["userData"] = autorest.Encode("query", userData)
}
if targetFace != nil && len(targetFace) > 0 {
queryParameters["targetFace"] = autorest.Encode("query", targetFace, ",")
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/facelists/{faceListId}/persistedFaces", pathParameters),
autorest.WithJSON(imageURL),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// AddFaceSender sends the AddFace request. The method will close the
// http.Response Body if it receives an error.
func (client ListClient) AddFaceSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// AddFaceResponder handles the response to the AddFace request. The method always
// closes the http.Response Body.
func (client ListClient) AddFaceResponder(resp *http.Response) (result PersistedFaceResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// AddFaceFromStream add a face to a face list. The input face is specified as an image with a targetFace rectangle. It
// returns a persistedFaceId representing the added face, and persistedFaceId will not expire.
//
// faceListID is id referencing a Face List. imageParameter is an image stream. imageParameter will be closed upon
// successful return. Callers should ensure closure when receiving an error.userData is user-specified data about the
// face list for any purpose. The maximum length is 1KB. targetFace is a face rectangle to specify the target face to
// be added to a person in the format of "targetFace=left,top,width,height". E.g. "targetFace=10,10,100,100". If there
// is more than one face in the image, targetFace is required to specify which face to add. No targetFace means there
// is only one face detected in the entire image.
func (client ListClient) AddFaceFromStream(ctx context.Context, faceListID string, imageParameter io.ReadCloser, userData string, targetFace []int32) (result PersistedFaceResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: faceListID,
Constraints: []validation.Constraint{{Target: "faceListID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "faceListID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}},
{TargetValue: userData,
Constraints: []validation.Constraint{{Target: "userData", Name: validation.MaxLength, Rule: 1024, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.ListClient", "AddFaceFromStream")
}
req, err := client.AddFaceFromStreamPreparer(ctx, faceListID, imageParameter, userData, targetFace)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "AddFaceFromStream", nil, "Failure preparing request")
return
}
resp, err := client.AddFaceFromStreamSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.ListClient", "AddFaceFromStream", resp, "Failure sending request")
return
}
result, err = client.AddFaceFromStreamResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "AddFaceFromStream", resp, "Failure responding to request")
}
return
}
// AddFaceFromStreamPreparer prepares the AddFaceFromStream request.
func (client ListClient) AddFaceFromStreamPreparer(ctx context.Context, faceListID string, imageParameter io.ReadCloser, userData string, targetFace []int32) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"faceListId": autorest.Encode("path", faceListID),
}
queryParameters := map[string]interface{}{}
if len(userData) > 0 {
queryParameters["userData"] = autorest.Encode("query", userData)
}
if targetFace != nil && len(targetFace) > 0 {
queryParameters["targetFace"] = autorest.Encode("query", targetFace, ",")
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/facelists/{faceListId}/persistedFaces", pathParameters),
autorest.WithFile(imageParameter),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// AddFaceFromStreamSender sends the AddFaceFromStream request. The method will close the
// http.Response Body if it receives an error.
func (client ListClient) AddFaceFromStreamSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// AddFaceFromStreamResponder handles the response to the AddFaceFromStream request. The method always
// closes the http.Response Body.
func (client ListClient) AddFaceFromStreamResponder(resp *http.Response) (result PersistedFaceResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Create create an empty face list. Up to 64 face lists are allowed to exist in one subscription.
//
// faceListID is id referencing a particular face list. body is request body for creating a face list.
func (client ListClient) Create(ctx context.Context, faceListID string, body CreateFaceListRequest) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: faceListID,
Constraints: []validation.Constraint{{Target: "faceListID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "faceListID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}},
{TargetValue: body,
Constraints: []validation.Constraint{{Target: "body.Name", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "body.Name", Name: validation.MaxLength, Rule: 128, Chain: nil}}},
{Target: "body.UserData", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "body.UserData", Name: validation.MaxLength, Rule: 16384, Chain: nil}}}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.ListClient", "Create")
}
req, err := client.CreatePreparer(ctx, faceListID, body)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "Create", nil, "Failure preparing request")
return
}
resp, err := client.CreateSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.ListClient", "Create", resp, "Failure sending request")
return
}
result, err = client.CreateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "Create", resp, "Failure responding to request")
}
return
}
// CreatePreparer prepares the Create request.
func (client ListClient) CreatePreparer(ctx context.Context, faceListID string, body CreateFaceListRequest) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"faceListId": autorest.Encode("path", faceListID),
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPut(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/facelists/{faceListId}", pathParameters),
autorest.WithJSON(body))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client ListClient) CreateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// CreateResponder handles the response to the Create request. The method always
// closes the http.Response Body.
func (client ListClient) CreateResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// Delete delete an existing face list according to faceListId. Persisted face images in the face list will also be
// deleted.
//
// faceListID is id referencing a Face List.
func (client ListClient) Delete(ctx context.Context, faceListID string) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: faceListID,
Constraints: []validation.Constraint{{Target: "faceListID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "faceListID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.ListClient", "Delete")
}
req, err := client.DeletePreparer(ctx, faceListID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.ListClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client ListClient) DeletePreparer(ctx context.Context, faceListID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"faceListId": autorest.Encode("path", faceListID),
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/facelists/{faceListId}", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client ListClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client ListClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// DeleteFace delete an existing face from a face list (given by a persisitedFaceId and a faceListId). Persisted image
// related to the face will also be deleted.
//
// faceListID is faceListId of an existing face list. persistedFaceID is persistedFaceId of an existing face.
func (client ListClient) DeleteFace(ctx context.Context, faceListID string, persistedFaceID string) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: faceListID,
Constraints: []validation.Constraint{{Target: "faceListID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "faceListID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.ListClient", "DeleteFace")
}
req, err := client.DeleteFacePreparer(ctx, faceListID, persistedFaceID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "DeleteFace", nil, "Failure preparing request")
return
}
resp, err := client.DeleteFaceSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.ListClient", "DeleteFace", resp, "Failure sending request")
return
}
result, err = client.DeleteFaceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "DeleteFace", resp, "Failure responding to request")
}
return
}
// DeleteFacePreparer prepares the DeleteFace request.
func (client ListClient) DeleteFacePreparer(ctx context.Context, faceListID string, persistedFaceID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"faceListId": autorest.Encode("path", faceListID),
"persistedFaceId": autorest.Encode("path", persistedFaceID),
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/facelists/{faceListId}/persistedFaces/{persistedFaceId}", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteFaceSender sends the DeleteFace request. The method will close the
// http.Response Body if it receives an error.
func (client ListClient) DeleteFaceSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DeleteFaceResponder handles the response to the DeleteFace request. The method always
// closes the http.Response Body.
func (client ListClient) DeleteFaceResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// Get retrieve a face list's information.
//
// faceListID is id referencing a Face List.
func (client ListClient) Get(ctx context.Context, faceListID string) (result GetFaceListResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: faceListID,
Constraints: []validation.Constraint{{Target: "faceListID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "faceListID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.ListClient", "Get")
}
req, err := client.GetPreparer(ctx, faceListID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.ListClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client ListClient) GetPreparer(ctx context.Context, faceListID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"faceListId": autorest.Encode("path", faceListID),
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/facelists/{faceListId}", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client ListClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client ListClient) GetResponder(resp *http.Response) (result GetFaceListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List retrieve information about all existing face lists. Only faceListId, name and userData will be returned.
func (client ListClient) List(ctx context.Context) (result ListGetFaceListResult, err error) {
req, err := client.ListPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.ListClient", "List", resp, "Failure sending request")
return
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client ListClient) ListPreparer(ctx context.Context) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPath("/facelists"))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client ListClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client ListClient) ListResponder(resp *http.Response) (result ListGetFaceListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Update update information of a face list.
//
// faceListID is id referencing a Face List. body is request body for updating a face list.
func (client ListClient) Update(ctx context.Context, faceListID string, body CreateFaceListRequest) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: faceListID,
Constraints: []validation.Constraint{{Target: "faceListID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "faceListID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.ListClient", "Update")
}
req, err := client.UpdatePreparer(ctx, faceListID, body)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "Update", nil, "Failure preparing request")
return
}
resp, err := client.UpdateSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.ListClient", "Update", resp, "Failure sending request")
return
}
result, err = client.UpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.ListClient", "Update", resp, "Failure responding to request")
}
return
}
// UpdatePreparer prepares the Update request.
func (client ListClient) UpdatePreparer(ctx context.Context, faceListID string, body CreateFaceListRequest) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"faceListId": autorest.Encode("path", faceListID),
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPatch(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/facelists/{faceListId}", pathParameters),
autorest.WithJSON(body))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client ListClient) UpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client ListClient) UpdateResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
@@ -0,0 +1,589 @@
package face
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/date"
)
// AttributeTypes enumerates the values for attribute types.
type AttributeTypes string
const (
// AttributeTypesAccessories ...
AttributeTypesAccessories AttributeTypes = "accessories"
// AttributeTypesAge ...
AttributeTypesAge AttributeTypes = "age"
// AttributeTypesBlur ...
AttributeTypesBlur AttributeTypes = "blur"
// AttributeTypesEmotion ...
AttributeTypesEmotion AttributeTypes = "emotion"
// AttributeTypesExposure ...
AttributeTypesExposure AttributeTypes = "exposure"
// AttributeTypesFacialHair ...
AttributeTypesFacialHair AttributeTypes = "facialHair"
// AttributeTypesGender ...
AttributeTypesGender AttributeTypes = "gender"
// AttributeTypesGlasses ...
AttributeTypesGlasses AttributeTypes = "glasses"
// AttributeTypesHair ...
AttributeTypesHair AttributeTypes = "hair"
// AttributeTypesHeadPose ...
AttributeTypesHeadPose AttributeTypes = "headPose"
// AttributeTypesMakeup ...
AttributeTypesMakeup AttributeTypes = "makeup"
// AttributeTypesNoise ...
AttributeTypesNoise AttributeTypes = "noise"
// AttributeTypesOcclusion ...
AttributeTypesOcclusion AttributeTypes = "occlusion"
// AttributeTypesSmile ...
AttributeTypesSmile AttributeTypes = "smile"
)
// AzureRegions enumerates the values for azure regions.
type AzureRegions string
const (
// Australiaeast ...
Australiaeast AzureRegions = "australiaeast"
// Brazilsouth ...
Brazilsouth AzureRegions = "brazilsouth"
// Eastasia ...
Eastasia AzureRegions = "eastasia"
// Eastus ...
Eastus AzureRegions = "eastus"
// Eastus2 ...
Eastus2 AzureRegions = "eastus2"
// Northeurope ...
Northeurope AzureRegions = "northeurope"
// Southcentralus ...
Southcentralus AzureRegions = "southcentralus"
// Southeastasia ...
Southeastasia AzureRegions = "southeastasia"
// Westcentralus ...
Westcentralus AzureRegions = "westcentralus"
// Westeurope ...
Westeurope AzureRegions = "westeurope"
// Westus ...
Westus AzureRegions = "westus"
// Westus2 ...
Westus2 AzureRegions = "westus2"
)
// BlurLevels enumerates the values for blur levels.
type BlurLevels string
const (
// High ...
High BlurLevels = "High"
// Low ...
Low BlurLevels = "Low"
// Medium ...
Medium BlurLevels = "Medium"
)
// ExposureLevels enumerates the values for exposure levels.
type ExposureLevels string
const (
// GoodExposure ...
GoodExposure ExposureLevels = "GoodExposure"
// OverExposure ...
OverExposure ExposureLevels = "OverExposure"
// UnderExposure ...
UnderExposure ExposureLevels = "UnderExposure"
)
// Gender enumerates the values for gender.
type Gender string
const (
// Female ...
Female Gender = "female"
// Genderless ...
Genderless Gender = "genderless"
// Male ...
Male Gender = "male"
)
// GlassesTypes enumerates the values for glasses types.
type GlassesTypes string
const (
// NoGlasses ...
NoGlasses GlassesTypes = "noGlasses"
// ReadingGlasses ...
ReadingGlasses GlassesTypes = "readingGlasses"
// Sunglasses ...
Sunglasses GlassesTypes = "sunglasses"
// SwimmingGoggles ...
SwimmingGoggles GlassesTypes = "swimmingGoggles"
)
// MatchingMode enumerates the values for matching mode.
type MatchingMode string
const (
// MatchFace ...
MatchFace MatchingMode = "matchFace"
// MatchPerson ...
MatchPerson MatchingMode = "matchPerson"
)
// NoiseLevels enumerates the values for noise levels.
type NoiseLevels string
const (
// NoiseLevelsHigh ...
NoiseLevelsHigh NoiseLevels = "High"
// NoiseLevelsLow ...
NoiseLevelsLow NoiseLevels = "Low"
// NoiseLevelsMedium ...
NoiseLevelsMedium NoiseLevels = "Medium"
)
// TrainingStatusType enumerates the values for training status type.
type TrainingStatusType string
const (
// Failed ...
Failed TrainingStatusType = "failed"
// Nonstarted ...
Nonstarted TrainingStatusType = "nonstarted"
// Running ...
Running TrainingStatusType = "running"
// Succeeded ...
Succeeded TrainingStatusType = "succeeded"
)
// AccessoryItem accessory item and corresponding confidence level.
type AccessoryItem struct {
// Type - Description of an accessory
Type *string `json:"type,omitempty"`
Confidence *float64 `json:"confidence,omitempty"`
}
// APIError error information returned by the API
type APIError struct {
Error *Error `json:"error,omitempty"`
}
// Attributes face Attributes
type Attributes struct {
// Age - Age in years
Age *float64 `json:"age,omitempty"`
// Gender - Possible gender of the face. Possible values include: 'Male', 'Female', 'Genderless'
Gender Gender `json:"gender,omitempty"`
// Smile - Smile intensity, a number between [0,1]
Smile *float64 `json:"smile,omitempty"`
FacialHair *FacialHairProperties `json:"facialHair,omitempty"`
// Glasses - Glasses type if any of the face. Possible values include: 'NoGlasses', 'ReadingGlasses', 'Sunglasses', 'SwimmingGoggles'
Glasses GlassesTypes `json:"glasses,omitempty"`
HeadPose *HeadPoseProperties `json:"headPose,omitempty"`
Emotion *EmotionProperties `json:"emotion,omitempty"`
Hair *HairProperties `json:"hair,omitempty"`
Makeup *MakeupProperties `json:"makeup,omitempty"`
Occlusion *OcclusionProperties `json:"occlusion,omitempty"`
Accessories *[]AccessoryItem `json:"accessories,omitempty"`
Blur *BlurProperties `json:"blur,omitempty"`
Exposure *ExposureProperties `json:"exposure,omitempty"`
Noise *NoiseProperties `json:"noise,omitempty"`
}
// BlurProperties properties describing any presence of blur within the image.
type BlurProperties struct {
// BlurLevel - An enum value indicating level of blurriness. Possible values include: 'Low', 'Medium', 'High'
BlurLevel BlurLevels `json:"blurLevel,omitempty"`
// Value - A number indicating level of blurriness ranging from 0 to 1.
Value *float64 `json:"value,omitempty"`
}
// ColorProperty hair color and associated confidence
type ColorProperty struct {
// Color - Name of the color.
Color *string `json:"color,omitempty"`
Confidence *float64 `json:"confidence,omitempty"`
}
// CreateFaceListRequest request to create a face list.
type CreateFaceListRequest struct {
// Name - Name of the face list, maximum length is 128.
Name *string `json:"name,omitempty"`
// UserData - Optional user defined data for the face list. Length should not exceed 16KB.
UserData *string `json:"userData,omitempty"`
}
// CreatePersonGroupRequest request to create a person group.
type CreatePersonGroupRequest struct {
// Name - Person group display name. The maximum length is 128.
Name *string `json:"name,omitempty"`
// UserData - User-provided data attached to the person group. The size limit is 16KB.
UserData *string `json:"userData,omitempty"`
}
// CreatePersonRequest request to create a person object.
type CreatePersonRequest struct {
// Name - Display name of the target person. The maximum length is 128.
Name *string `json:"name,omitempty"`
// UserData - Optional fields for user-provided data attached to a person. Size limit is 16KB.
UserData *string `json:"userData,omitempty"`
}
// CreatePersonResult result of creating person.
type CreatePersonResult struct {
autorest.Response `json:"-"`
// PersonID - personID of the new created person.
PersonID *string `json:"personId,omitempty"`
}
// DetectedFace detected Face object.
type DetectedFace struct {
FaceID *string `json:"faceId,omitempty"`
FaceRectangle *Rectangle `json:"faceRectangle,omitempty"`
FaceLandmarks *Landmarks `json:"faceLandmarks,omitempty"`
FaceAttributes *Attributes `json:"faceAttributes,omitempty"`
}
// EmotionProperties properties describing facial emotion in form of confidence ranging from 0 to 1.
type EmotionProperties struct {
Anger *float64 `json:"anger,omitempty"`
Contempt *float64 `json:"contempt,omitempty"`
Disgust *float64 `json:"disgust,omitempty"`
Fear *float64 `json:"fear,omitempty"`
Happiness *float64 `json:"happiness,omitempty"`
Neutral *float64 `json:"neutral,omitempty"`
Sadness *float64 `json:"sadness,omitempty"`
Surprise *float64 `json:"surprise,omitempty"`
}
// Error error body.
type Error struct {
Code *string `json:"code,omitempty"`
Message *string `json:"message,omitempty"`
}
// ExposureProperties properties describing exposure level of the image.
type ExposureProperties struct {
// ExposureLevel - An enum value indicating level of exposure. Possible values include: 'UnderExposure', 'GoodExposure', 'OverExposure'
ExposureLevel ExposureLevels `json:"exposureLevel,omitempty"`
// Value - A number indicating level of exposure level ranging from 0 to 1. [0, 0.25) is under exposure. [0.25, 0.75) is good exposure. [0.75, 1] is over exposure.
Value *float64 `json:"value,omitempty"`
}
// FacialHairProperties properties describing facial hair attributes.
type FacialHairProperties struct {
Moustache *float64 `json:"moustache,omitempty"`
Beard *float64 `json:"beard,omitempty"`
Sideburns *float64 `json:"sideburns,omitempty"`
}
// FindSimilarRequest request body for find similar operation.
type FindSimilarRequest struct {
// FaceID - FaceId of the query face. User needs to call Face - Detect first to get a valid faceId. Note that this faceId is not persisted and will expire 24 hours after the detection call
FaceID *string `json:"faceId,omitempty"`
// FaceListID - An existing user-specified unique candidate face list, created in Face List - Create a Face List. Face list contains a set of persistedFaceIds which are persisted and will never expire. Parameter faceListId and faceIds should not be provided at the same time
FaceListID *string `json:"faceListId,omitempty"`
// FaceIds - An array of candidate faceIds. All of them are created by Face - Detect and the faceIds will expire 24 hours after the detection call.
FaceIds *[]string `json:"faceIds,omitempty"`
// MaxNumOfCandidatesReturned - The number of top similar faces returned. The valid range is [1, 1000].
MaxNumOfCandidatesReturned *int32 `json:"maxNumOfCandidatesReturned,omitempty"`
// Mode - Similar face searching mode. It can be "matchPerson" or "matchFace". Possible values include: 'MatchPerson', 'MatchFace'
Mode MatchingMode `json:"mode,omitempty"`
}
// GetFaceListResult result of the GetFaceList operation.
type GetFaceListResult struct {
autorest.Response `json:"-"`
// FaceListID - faceListId of the target face list.
FaceListID *string `json:"faceListId,omitempty"`
// Name - Face list's display name, maximum length is 128.
Name *string `json:"name,omitempty"`
// UserData - User-provided data attached to this face list. Length should not exceed 16KB.
UserData *string `json:"userData,omitempty"`
// PersistedFaces - Persisted faces within the face list.
PersistedFaces *[]PersonFaceResult `json:"persistedFaces,omitempty"`
}
// GroupRequest request body for group request.
type GroupRequest struct {
// FaceIds - Array of candidate faceId created by Face - Detect. The maximum is 1000 faces
FaceIds *[]string `json:"faceIds,omitempty"`
}
// GroupResponse an array of face groups based on face similarity.
type GroupResponse struct {
autorest.Response `json:"-"`
// Groups - A partition of the original faces based on face similarity. Groups are ranked by number of faces
Groups *[][]string `json:"groups,omitempty"`
// MessyGroup - Face ids array of faces that cannot find any similar faces from original faces.
MessyGroup *[]string `json:"messyGroup,omitempty"`
}
// HairProperties properties describing hair attributes.
type HairProperties struct {
// Bald - A number describing confidence level of whether the person is bald.
Bald *float64 `json:"bald,omitempty"`
// Invisible - A boolean value describing whether the hair is visible in the image.
Invisible *bool `json:"invisible,omitempty"`
HairColor *[]ColorProperty `json:"hairColor,omitempty"`
}
// HeadPoseProperties properties indicating head pose of the face.
type HeadPoseProperties struct {
Roll *float64 `json:"roll,omitempty"`
Yaw *float64 `json:"yaw,omitempty"`
Pitch *float64 `json:"pitch,omitempty"`
}
// IdentifyRequest request body for identify face operation.
type IdentifyRequest struct {
// PersonGroupID - personGroupId of the target person group, created by PersonGroups.Create
PersonGroupID *string `json:"personGroupId,omitempty"`
// FaceIds - Array of candidate faceId created by Face - Detect.
FaceIds *[]string `json:"faceIds,omitempty"`
// MaxNumOfCandidatesReturned - The number of top similar faces returned.
MaxNumOfCandidatesReturned *int32 `json:"maxNumOfCandidatesReturned,omitempty"`
ConfidenceThreshold *float64 `json:"confidenceThreshold,omitempty"`
}
// IdentifyResultCandidate all possible faces that may qualify.
type IdentifyResultCandidate struct {
// PersonID - Id of candidate
PersonID *string `json:"personId,omitempty"`
Confidence *float64 `json:"confidence,omitempty"`
}
// IdentifyResultItem response body for identify face operation.
type IdentifyResultItem struct {
// FaceID - faceId of the query face
FaceID *string `json:"faceId,omitempty"`
Candidates *[]IdentifyResultCandidate `json:"candidates,omitempty"`
}
// ImageURL ...
type ImageURL struct {
URL *string `json:"url,omitempty"`
}
// Landmarks a collection of 27-point face landmarks pointing to the important positions of face components.
type Landmarks struct {
PupilLeft *Position `json:"pupilLeft,omitempty"`
PupilRight *Position `json:"pupilRight,omitempty"`
NoseTip *Position `json:"noseTip,omitempty"`
MouthLeft *Position `json:"mouthLeft,omitempty"`
MouthRight *Position `json:"mouthRight,omitempty"`
EyebrowLeftOuter *Position `json:"eyebrowLeftOuter,omitempty"`
EyebrowLeftInner *Position `json:"eyebrowLeftInner,omitempty"`
EyeLeftOuter *Position `json:"eyeLeftOuter,omitempty"`
EyeLeftTop *Position `json:"eyeLeftTop,omitempty"`
EyeLeftBottom *Position `json:"eyeLeftBottom,omitempty"`
EyeLeftInner *Position `json:"eyeLeftInner,omitempty"`
EyebrowRightInner *Position `json:"eyebrowRightInner,omitempty"`
EyebrowRightOuter *Position `json:"eyebrowRightOuter,omitempty"`
EyeRightInner *Position `json:"eyeRightInner,omitempty"`
EyeRightTop *Position `json:"eyeRightTop,omitempty"`
EyeRightBottom *Position `json:"eyeRightBottom,omitempty"`
EyeRightOuter *Position `json:"eyeRightOuter,omitempty"`
NoseRootLeft *Position `json:"noseRootLeft,omitempty"`
NoseRootRight *Position `json:"noseRootRight,omitempty"`
NoseLeftAlarTop *Position `json:"noseLeftAlarTop,omitempty"`
NoseRightAlarTop *Position `json:"noseRightAlarTop,omitempty"`
NoseLeftAlarOutTip *Position `json:"noseLeftAlarOutTip,omitempty"`
NoseRightAlarOutTip *Position `json:"noseRightAlarOutTip,omitempty"`
UpperLipTop *Position `json:"upperLipTop,omitempty"`
UpperLipBottom *Position `json:"upperLipBottom,omitempty"`
UnderLipTop *Position `json:"underLipTop,omitempty"`
UnderLipBottom *Position `json:"underLipBottom,omitempty"`
}
// ListDetectedFace ...
type ListDetectedFace struct {
autorest.Response `json:"-"`
Value *[]DetectedFace `json:"value,omitempty"`
}
// ListGetFaceListResult ...
type ListGetFaceListResult struct {
autorest.Response `json:"-"`
Value *[]GetFaceListResult `json:"value,omitempty"`
}
// ListIdentifyResultItem ...
type ListIdentifyResultItem struct {
autorest.Response `json:"-"`
Value *[]IdentifyResultItem `json:"value,omitempty"`
}
// ListPersonGroupResult ...
type ListPersonGroupResult struct {
autorest.Response `json:"-"`
Value *[]PersonGroupResult `json:"value,omitempty"`
}
// ListPersonResult ...
type ListPersonResult struct {
autorest.Response `json:"-"`
Value *[]PersonResult `json:"value,omitempty"`
}
// ListSimilarFaceResult ...
type ListSimilarFaceResult struct {
autorest.Response `json:"-"`
Value *[]SimilarFaceResult `json:"value,omitempty"`
}
// MakeupProperties properties describing present makeups on a given face.
type MakeupProperties struct {
// EyeMakeup - A boolean value describing whether eye makeup is present on a face.
EyeMakeup *bool `json:"eyeMakeup,omitempty"`
// LipMakeup - A boolean value describing whether lip makeup is present on a face.
LipMakeup *bool `json:"lipMakeup,omitempty"`
}
// NoiseProperties properties describing noise level of the image.
type NoiseProperties struct {
// NoiseLevel - An enum value indicating level of noise. Possible values include: 'NoiseLevelsLow', 'NoiseLevelsMedium', 'NoiseLevelsHigh'
NoiseLevel NoiseLevels `json:"noiseLevel,omitempty"`
// Value - A number indicating level of noise level ranging from 0 to 1. [0, 0.25) is under exposure. [0.25, 0.75) is good exposure. [0.75, 1] is over exposure. [0, 0.3) is low noise level. [0.3, 0.7) is medium noise level. [0.7, 1] is high noise level.
Value *float64 `json:"value,omitempty"`
}
// OcclusionProperties properties describing occulusions on a given face.
type OcclusionProperties struct {
// ForeheadOccluded - A boolean value indicating whether forehead is occluded.
ForeheadOccluded *bool `json:"foreheadOccluded,omitempty"`
// EyeOccluded - A boolean value indicating whether eyes are occluded.
EyeOccluded *bool `json:"eyeOccluded,omitempty"`
// MouthOccluded - A boolean value indicating whether the mouth is occluded.
MouthOccluded *bool `json:"mouthOccluded,omitempty"`
}
// PersistedFaceResult persisted face result.
type PersistedFaceResult struct {
autorest.Response `json:"-"`
// PersistedFaceID - persistedFaceId of candidate face when find by faceListId. persistedFaceId in face list is persisted and will not expire. As showed in below response
PersistedFaceID *string `json:"persistedFaceId,omitempty"`
}
// PersonFaceResult personFace object.
type PersonFaceResult struct {
autorest.Response `json:"-"`
// PersistedFaceID - The persistedFaceId of the target face, which is persisted and will not expire. Different from faceId created by Face - Detect and will expire in 24 hours after the detection call.
PersistedFaceID *string `json:"persistedFaceId,omitempty"`
// UserData - User-provided data attached to the face. The size limit is 1KB.
UserData *string `json:"userData,omitempty"`
}
// PersonGroupResult person group object.
type PersonGroupResult struct {
autorest.Response `json:"-"`
// PersonGroupID - personGroupId of the existing person groups.
PersonGroupID *string `json:"personGroupId,omitempty"`
// Name - Person group's display name, maximum length is 128.
Name *string `json:"name,omitempty"`
// UserData - User-provided data attached to this person group. Length should not exceed 16KB.
UserData *string `json:"userData,omitempty"`
}
// PersonResult person object.
type PersonResult struct {
autorest.Response `json:"-"`
// PersonID - personId of the target face list.
PersonID *string `json:"personId,omitempty"`
// PersistedFaceIds - persistedFaceIds of registered faces in the person. These persistedFaceIds are returned from Person - Add a Person Face, and will not expire.
PersistedFaceIds *[]string `json:"persistedFaceIds,omitempty"`
// Name - Person's display name, maximum length is 128.
Name *string `json:"name,omitempty"`
// UserData - User-provided data attached to this person. Length should not exceed 16KB.
UserData *string `json:"userData,omitempty"`
}
// Position coordinates within an image
type Position struct {
// X - The horizontal component, in pixels.
X *float64 `json:"x,omitempty"`
// Y - The vertical component, in pixels.
Y *float64 `json:"y,omitempty"`
}
// Rectangle a rectangle within which a face can be found
type Rectangle struct {
// Width - The width of the rectangle, in pixels.
Width *int32 `json:"width,omitempty"`
// Height - The height of the rectangle, in pixels.
Height *int32 `json:"height,omitempty"`
// Left - The distance from the left edge if the image to the left edge of the rectangle, in pixels.
Left *int32 `json:"left,omitempty"`
// Top - The distance from the top edge if the image to the top edge of the rectangle, in pixels.
Top *int32 `json:"top,omitempty"`
}
// SimilarFaceResult response body for find similar face operation.
type SimilarFaceResult struct {
// FaceID - faceId of candidate face when find by faceIds. faceId is created by Face - Detect and will expire 24 hours after the detection call
FaceID *string `json:"faceId,omitempty"`
// PersistedFaceID - persistedFaceId of candidate face when find by faceListId. persistedFaceId in face list is persisted and will not expire. As showed in below response
PersistedFaceID *string `json:"persistedFaceId,omitempty"`
Confidence *float64 `json:"confidence,omitempty"`
}
// TrainingStatus training status object.
type TrainingStatus struct {
autorest.Response `json:"-"`
// Status - Training status: notstarted, running, succeeded, failed. If the training process is waiting to perform, the status is notstarted. If the training is ongoing, the status is running. Status succeed means this person group is ready for Face - Identify. Status failed is often caused by no person or no persisted face exist in the person group. Possible values include: 'Nonstarted', 'Running', 'Succeeded', 'Failed'
Status TrainingStatusType `json:"status,omitempty"`
// Created - A combined UTC date and time string that describes person group created time.
Created *date.Time `json:"createdDateTime,omitempty"`
// LastAction - Person group last modify time in the UTC, could be null value when the person group is not successfully trained.
LastAction *date.Time `json:"lastActionDateTime,omitempty"`
// Message - Show failure message when training failed (omitted when training succeed).
Message *string `json:"message,omitempty"`
}
// UpdatePersonFaceDataRequest request to update person face data.
type UpdatePersonFaceDataRequest struct {
// UserData - User-provided data attached to the face. The size limit is 1KB.
UserData *string `json:"userData,omitempty"`
}
// VerifyPersonGroupRequest request body for verify operation.
type VerifyPersonGroupRequest struct {
// FaceID - faceId the face, comes from Face - Detect
FaceID *string `json:"faceId,omitempty"`
// PersonID - Specify a certain person in a person group. personId is created in Persons.Create.
PersonID *string `json:"personId,omitempty"`
// PersonGroupID - Using existing personGroupId and personId for fast loading a specified person. personGroupId is created in Person Groups.Create.
PersonGroupID *string `json:"personGroupId,omitempty"`
}
// VerifyRequest request body for verify operation.
type VerifyRequest struct {
// FaceID1 - faceId of the first face, comes from Face - Detect
FaceID1 *string `json:"faceId1,omitempty"`
// FaceID2 - faceId of the second face, comes from Face - Detect
FaceID2 *string `json:"faceId2,omitempty"`
}
// VerifyResult result of the verify operation.
type VerifyResult struct {
autorest.Response `json:"-"`
// IsIdentical - True if the two faces belong to the same person or the face belongs to the person, otherwise false.
IsIdentical *bool `json:"isIdentical,omitempty"`
Confidence *float64 `json:"confidence,omitempty"`
}
@@ -0,0 +1,809 @@
package face
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"io"
"net/http"
)
// PersonClient is the an API for face detection, verification, and identification.
type PersonClient struct {
BaseClient
}
// NewPersonClient creates an instance of the PersonClient client.
func NewPersonClient(azureRegion AzureRegions) PersonClient {
return PersonClient{New(azureRegion)}
}
// AddPersonFace add a representative face to a person for identification. The input face is specified as an image with
// a targetFace rectangle.
//
// personGroupID is specifying the person group containing the target person. personID is target person that the face
// is added to. imageURL is a JSON document with a URL pointing to the image that is to be analyzed. userData is
// user-specified data about the target face to add for any purpose. The maximum length is 1KB. targetFace is a face
// rectangle to specify the target face to be added to a person in the format of "targetFace=left,top,width,height".
// E.g. "targetFace=10,10,100,100". If there is more than one face in the image, targetFace is required to specify
// which face to add. No targetFace means there is only one face detected in the entire image.
func (client PersonClient) AddPersonFace(ctx context.Context, personGroupID string, personID string, imageURL ImageURL, userData string, targetFace []int32) (result PersistedFaceResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}},
{TargetValue: userData,
Constraints: []validation.Constraint{{Target: "userData", Name: validation.MaxLength, Rule: 1024, Chain: nil}}},
{TargetValue: imageURL,
Constraints: []validation.Constraint{{Target: "imageURL.URL", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonClient", "AddPersonFace")
}
req, err := client.AddPersonFacePreparer(ctx, personGroupID, personID, imageURL, userData, targetFace)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "AddPersonFace", nil, "Failure preparing request")
return
}
resp, err := client.AddPersonFaceSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.PersonClient", "AddPersonFace", resp, "Failure sending request")
return
}
result, err = client.AddPersonFaceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "AddPersonFace", resp, "Failure responding to request")
}
return
}
// AddPersonFacePreparer prepares the AddPersonFace request.
func (client PersonClient) AddPersonFacePreparer(ctx context.Context, personGroupID string, personID string, imageURL ImageURL, userData string, targetFace []int32) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
queryParameters := map[string]interface{}{}
if len(userData) > 0 {
queryParameters["userData"] = autorest.Encode("query", userData)
}
if targetFace != nil && len(targetFace) > 0 {
queryParameters["targetFace"] = autorest.Encode("query", targetFace, ",")
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}/persistedFaces", pathParameters),
autorest.WithJSON(imageURL),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// AddPersonFaceSender sends the AddPersonFace request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) AddPersonFaceSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// AddPersonFaceResponder handles the response to the AddPersonFace request. The method always
// closes the http.Response Body.
func (client PersonClient) AddPersonFaceResponder(resp *http.Response) (result PersistedFaceResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// AddPersonFaceFromStream add a representative face to a person for identification. The input face is specified as an
// image with a targetFace rectangle.
//
// personGroupID is specifying the person group containing the target person. personID is target person that the face
// is added to. imageParameter is an image stream. imageParameter will be closed upon successful return. Callers should
// ensure closure when receiving an error.userData is user-specified data about the target face to add for any purpose.
// The maximum length is 1KB. targetFace is a face rectangle to specify the target face to be added to a person in the
// format of "targetFace=left,top,width,height". E.g. "targetFace=10,10,100,100". If there is more than one face in the
// image, targetFace is required to specify which face to add. No targetFace means there is only one face detected in
// the entire image.
func (client PersonClient) AddPersonFaceFromStream(ctx context.Context, personGroupID string, personID string, imageParameter io.ReadCloser, userData string, targetFace []int32) (result PersistedFaceResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}},
{TargetValue: userData,
Constraints: []validation.Constraint{{Target: "userData", Name: validation.MaxLength, Rule: 1024, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonClient", "AddPersonFaceFromStream")
}
req, err := client.AddPersonFaceFromStreamPreparer(ctx, personGroupID, personID, imageParameter, userData, targetFace)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "AddPersonFaceFromStream", nil, "Failure preparing request")
return
}
resp, err := client.AddPersonFaceFromStreamSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.PersonClient", "AddPersonFaceFromStream", resp, "Failure sending request")
return
}
result, err = client.AddPersonFaceFromStreamResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "AddPersonFaceFromStream", resp, "Failure responding to request")
}
return
}
// AddPersonFaceFromStreamPreparer prepares the AddPersonFaceFromStream request.
func (client PersonClient) AddPersonFaceFromStreamPreparer(ctx context.Context, personGroupID string, personID string, imageParameter io.ReadCloser, userData string, targetFace []int32) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
queryParameters := map[string]interface{}{}
if len(userData) > 0 {
queryParameters["userData"] = autorest.Encode("query", userData)
}
if targetFace != nil && len(targetFace) > 0 {
queryParameters["targetFace"] = autorest.Encode("query", targetFace, ",")
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}/persistedFaces", pathParameters),
autorest.WithFile(imageParameter),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// AddPersonFaceFromStreamSender sends the AddPersonFaceFromStream request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) AddPersonFaceFromStreamSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// AddPersonFaceFromStreamResponder handles the response to the AddPersonFaceFromStream request. The method always
// closes the http.Response Body.
func (client PersonClient) AddPersonFaceFromStreamResponder(resp *http.Response) (result PersistedFaceResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Create create a new person in a specified person group.
//
// personGroupID is specifying the target person group to create the person. body is request body for creating new
// person.
func (client PersonClient) Create(ctx context.Context, personGroupID string, body CreatePersonRequest) (result CreatePersonResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}},
{TargetValue: body,
Constraints: []validation.Constraint{{Target: "body.Name", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "body.Name", Name: validation.MaxLength, Rule: 128, Chain: nil}}},
{Target: "body.UserData", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "body.UserData", Name: validation.MaxLength, Rule: 16384, Chain: nil}}}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonClient", "Create")
}
req, err := client.CreatePreparer(ctx, personGroupID, body)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Create", nil, "Failure preparing request")
return
}
resp, err := client.CreateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.PersonClient", "Create", resp, "Failure sending request")
return
}
result, err = client.CreateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Create", resp, "Failure responding to request")
}
return
}
// CreatePreparer prepares the Create request.
func (client PersonClient) CreatePreparer(ctx context.Context, personGroupID string, body CreatePersonRequest) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons", pathParameters),
autorest.WithJSON(body))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) CreateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// CreateResponder handles the response to the Create request. The method always
// closes the http.Response Body.
func (client PersonClient) CreateResponder(resp *http.Response) (result CreatePersonResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete delete an existing person from a person group. Persisted face images of the person will also be deleted.
//
// personGroupID is specifying the person group containing the person. personID is the target personId to delete.
func (client PersonClient) Delete(ctx context.Context, personGroupID string, personID string) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonClient", "Delete")
}
req, err := client.DeletePreparer(ctx, personGroupID, personID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.PersonClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client PersonClient) DeletePreparer(ctx context.Context, personGroupID string, personID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client PersonClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// DeleteFace delete a face from a person. Relative image for the persisted face will also be deleted.
//
// personGroupID is specifying the person group containing the target person. personID is specifying the person that
// the target persisted face belong to. persistedFaceID is the persisted face to remove.
func (client PersonClient) DeleteFace(ctx context.Context, personGroupID string, personID string, persistedFaceID string) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonClient", "DeleteFace")
}
req, err := client.DeleteFacePreparer(ctx, personGroupID, personID, persistedFaceID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "DeleteFace", nil, "Failure preparing request")
return
}
resp, err := client.DeleteFaceSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.PersonClient", "DeleteFace", resp, "Failure sending request")
return
}
result, err = client.DeleteFaceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "DeleteFace", resp, "Failure responding to request")
}
return
}
// DeleteFacePreparer prepares the DeleteFace request.
func (client PersonClient) DeleteFacePreparer(ctx context.Context, personGroupID string, personID string, persistedFaceID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"persistedFaceId": autorest.Encode("path", persistedFaceID),
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}/persistedFaces/{persistedFaceId}", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteFaceSender sends the DeleteFace request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) DeleteFaceSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DeleteFaceResponder handles the response to the DeleteFace request. The method always
// closes the http.Response Body.
func (client PersonClient) DeleteFaceResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// Get retrieve a person's information, including registered persisted faces, name and userData.
//
// personGroupID is specifying the person group containing the target person. personID is specifying the target person.
func (client PersonClient) Get(ctx context.Context, personGroupID string, personID string) (result PersonResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonClient", "Get")
}
req, err := client.GetPreparer(ctx, personGroupID, personID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.PersonClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client PersonClient) GetPreparer(ctx context.Context, personGroupID string, personID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client PersonClient) GetResponder(resp *http.Response) (result PersonResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetFace retrieve information about a persisted face (specified by persistedFaceId, personId and its belonging
// personGroupId).
//
// personGroupID is specifying the person group containing the target person. personID is specifying the target person
// that the face belongs to. persistedFaceID is the persistedFaceId of the target persisted face of the person.
func (client PersonClient) GetFace(ctx context.Context, personGroupID string, personID string, persistedFaceID string) (result PersonFaceResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonClient", "GetFace")
}
req, err := client.GetFacePreparer(ctx, personGroupID, personID, persistedFaceID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "GetFace", nil, "Failure preparing request")
return
}
resp, err := client.GetFaceSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.PersonClient", "GetFace", resp, "Failure sending request")
return
}
result, err = client.GetFaceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "GetFace", resp, "Failure responding to request")
}
return
}
// GetFacePreparer prepares the GetFace request.
func (client PersonClient) GetFacePreparer(ctx context.Context, personGroupID string, personID string, persistedFaceID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"persistedFaceId": autorest.Encode("path", persistedFaceID),
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}/persistedFaces/{persistedFaceId}", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetFaceSender sends the GetFace request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) GetFaceSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// GetFaceResponder handles the response to the GetFace request. The method always
// closes the http.Response Body.
func (client PersonClient) GetFaceResponder(resp *http.Response) (result PersonFaceResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List list all persons in a person group, and retrieve person information (including personId, name, userData and
// persistedFaceIds of registered faces of the person).
//
// personGroupID is personGroupId of the target person group. start is starting person id to return (used to list a
// range of persons). top is number of persons to return starting with the person id indicated by the 'start'
// parameter.
func (client PersonClient) List(ctx context.Context, personGroupID string, start string, top *int32) (result ListPersonResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}},
{TargetValue: top,
Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: 1000, Chain: nil},
{Target: "top", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil},
}}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonClient", "List")
}
req, err := client.ListPreparer(ctx, personGroupID, start, top)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.PersonClient", "List", resp, "Failure sending request")
return
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client PersonClient) ListPreparer(ctx context.Context, personGroupID string, start string, top *int32) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
}
queryParameters := map[string]interface{}{}
if len(start) > 0 {
queryParameters["start"] = autorest.Encode("query", start)
}
if top != nil {
queryParameters["top"] = autorest.Encode("query", *top)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client PersonClient) ListResponder(resp *http.Response) (result ListPersonResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Update update name or userData of a person.
//
// personGroupID is specifying the person group containing the target person. personID is personId of the target
// person. body is request body for person update operation.
func (client PersonClient) Update(ctx context.Context, personGroupID string, personID string, body CreatePersonRequest) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonClient", "Update")
}
req, err := client.UpdatePreparer(ctx, personGroupID, personID, body)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Update", nil, "Failure preparing request")
return
}
resp, err := client.UpdateSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.PersonClient", "Update", resp, "Failure sending request")
return
}
result, err = client.UpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Update", resp, "Failure responding to request")
}
return
}
// UpdatePreparer prepares the Update request.
func (client PersonClient) UpdatePreparer(ctx context.Context, personGroupID string, personID string, body CreatePersonRequest) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPatch(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}", pathParameters),
autorest.WithJSON(body))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) UpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client PersonClient) UpdateResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// UpdateFace update a person persisted face's userData field.
//
// personGroupID is specifying the person group containing the target person. personID is personId of the target
// person. persistedFaceID is persistedFaceId of target face, which is persisted and will not expire. body is request
// body for updating persisted face.
func (client PersonClient) UpdateFace(ctx context.Context, personGroupID string, personID string, persistedFaceID string, body UpdatePersonFaceDataRequest) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonClient", "UpdateFace")
}
req, err := client.UpdateFacePreparer(ctx, personGroupID, personID, persistedFaceID, body)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "UpdateFace", nil, "Failure preparing request")
return
}
resp, err := client.UpdateFaceSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.PersonClient", "UpdateFace", resp, "Failure sending request")
return
}
result, err = client.UpdateFaceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "UpdateFace", resp, "Failure responding to request")
}
return
}
// UpdateFacePreparer prepares the UpdateFace request.
func (client PersonClient) UpdateFacePreparer(ctx context.Context, personGroupID string, personID string, persistedFaceID string, body UpdatePersonFaceDataRequest) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"persistedFaceId": autorest.Encode("path", persistedFaceID),
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPatch(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}/persistedFaces/{persistedFaceId}", pathParameters),
autorest.WithJSON(body))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateFaceSender sends the UpdateFace request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) UpdateFaceSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// UpdateFaceResponder handles the response to the UpdateFace request. The method always
// closes the http.Response Body.
func (client PersonClient) UpdateFaceResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
@@ -0,0 +1,536 @@
package face
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// PersonGroupClient is the an API for face detection, verification, and identification.
type PersonGroupClient struct {
BaseClient
}
// NewPersonGroupClient creates an instance of the PersonGroupClient client.
func NewPersonGroupClient(azureRegion AzureRegions) PersonGroupClient {
return PersonGroupClient{New(azureRegion)}
}
// Create create a new person group with specified personGroupId, name and user-provided userData.
//
// personGroupID is user-provided personGroupId as a string. body is request body for creating new person group.
func (client PersonGroupClient) Create(ctx context.Context, personGroupID string, body CreatePersonGroupRequest) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}},
{TargetValue: body,
Constraints: []validation.Constraint{{Target: "body.Name", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "body.Name", Name: validation.MaxLength, Rule: 128, Chain: nil}}},
{Target: "body.UserData", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "body.UserData", Name: validation.MaxLength, Rule: 16384, Chain: nil}}}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonGroupClient", "Create")
}
req, err := client.CreatePreparer(ctx, personGroupID, body)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "Create", nil, "Failure preparing request")
return
}
resp, err := client.CreateSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "Create", resp, "Failure sending request")
return
}
result, err = client.CreateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "Create", resp, "Failure responding to request")
}
return
}
// CreatePreparer prepares the Create request.
func (client PersonGroupClient) CreatePreparer(ctx context.Context, personGroupID string, body CreatePersonGroupRequest) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPut(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}", pathParameters),
autorest.WithJSON(body))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupClient) CreateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// CreateResponder handles the response to the Create request. The method always
// closes the http.Response Body.
func (client PersonGroupClient) CreateResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// Delete delete an existing person group. Persisted face images of all people in the person group will also be
// deleted.
//
// personGroupID is the personGroupId of the person group to be deleted.
func (client PersonGroupClient) Delete(ctx context.Context, personGroupID string) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonGroupClient", "Delete")
}
req, err := client.DeletePreparer(ctx, personGroupID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client PersonGroupClient) DeletePreparer(ctx context.Context, personGroupID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client PersonGroupClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// Get retrieve the information of a person group, including its name and userData.
//
// personGroupID is personGroupId of the target person group.
func (client PersonGroupClient) Get(ctx context.Context, personGroupID string) (result PersonGroupResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonGroupClient", "Get")
}
req, err := client.GetPreparer(ctx, personGroupID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client PersonGroupClient) GetPreparer(ctx context.Context, personGroupID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client PersonGroupClient) GetResponder(resp *http.Response) (result PersonGroupResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetTrainingStatus retrieve the training status of a person group (completed or ongoing).
//
// personGroupID is personGroupId of target person group.
func (client PersonGroupClient) GetTrainingStatus(ctx context.Context, personGroupID string) (result TrainingStatus, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonGroupClient", "GetTrainingStatus")
}
req, err := client.GetTrainingStatusPreparer(ctx, personGroupID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "GetTrainingStatus", nil, "Failure preparing request")
return
}
resp, err := client.GetTrainingStatusSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "GetTrainingStatus", resp, "Failure sending request")
return
}
result, err = client.GetTrainingStatusResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "GetTrainingStatus", resp, "Failure responding to request")
}
return
}
// GetTrainingStatusPreparer prepares the GetTrainingStatus request.
func (client PersonGroupClient) GetTrainingStatusPreparer(ctx context.Context, personGroupID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/training", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetTrainingStatusSender sends the GetTrainingStatus request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupClient) GetTrainingStatusSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// GetTrainingStatusResponder handles the response to the GetTrainingStatus request. The method always
// closes the http.Response Body.
func (client PersonGroupClient) GetTrainingStatusResponder(resp *http.Response) (result TrainingStatus, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List list person groups and their information.
//
// start is list person groups from the least personGroupId greater than the "start". top is the number of person
// groups to list.
func (client PersonGroupClient) List(ctx context.Context, start string, top *int32) (result ListPersonGroupResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: start,
Constraints: []validation.Constraint{{Target: "start", Name: validation.MaxLength, Rule: 64, Chain: nil}}},
{TargetValue: top,
Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: 1000, Chain: nil},
{Target: "top", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil},
}}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonGroupClient", "List")
}
req, err := client.ListPreparer(ctx, start, top)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "List", resp, "Failure sending request")
return
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client PersonGroupClient) ListPreparer(ctx context.Context, start string, top *int32) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
queryParameters := map[string]interface{}{}
if len(start) > 0 {
queryParameters["start"] = autorest.Encode("query", start)
}
if top != nil {
queryParameters["top"] = autorest.Encode("query", *top)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPath("/persongroups"),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client PersonGroupClient) ListResponder(resp *http.Response) (result ListPersonGroupResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Train queue a person group training task, the training task may not be started immediately.
//
// personGroupID is target person group to be trained.
func (client PersonGroupClient) Train(ctx context.Context, personGroupID string) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonGroupClient", "Train")
}
req, err := client.TrainPreparer(ctx, personGroupID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "Train", nil, "Failure preparing request")
return
}
resp, err := client.TrainSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "Train", resp, "Failure sending request")
return
}
result, err = client.TrainResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "Train", resp, "Failure responding to request")
}
return
}
// TrainPreparer prepares the Train request.
func (client PersonGroupClient) TrainPreparer(ctx context.Context, personGroupID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/train", pathParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// TrainSender sends the Train request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupClient) TrainSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// TrainResponder handles the response to the Train request. The method always
// closes the http.Response Body.
func (client PersonGroupClient) TrainResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByClosing())
result.Response = resp
return
}
// Update update an existing person group's display name and userData. The properties which does not appear in request
// body will not be updated.
//
// personGroupID is personGroupId of the person group to be updated. body is request body for updating person group.
func (client PersonGroupClient) Update(ctx context.Context, personGroupID string, body CreatePersonGroupRequest) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: personGroupID,
Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonGroupClient", "Update")
}
req, err := client.UpdatePreparer(ctx, personGroupID, body)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "Update", nil, "Failure preparing request")
return
}
resp, err := client.UpdateSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "Update", resp, "Failure sending request")
return
}
result, err = client.UpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonGroupClient", "Update", resp, "Failure responding to request")
}
return
}
// UpdatePreparer prepares the Update request.
func (client PersonGroupClient) UpdatePreparer(ctx context.Context, personGroupID string, body CreatePersonGroupRequest) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPatch(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}", pathParameters),
autorest.WithJSON(body))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupClient) UpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client PersonGroupClient) UpdateResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
@@ -0,0 +1,28 @@
package face
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/v12.2.0-beta services"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v12.2.0-beta"
}
@@ -0,0 +1,52 @@
// Package imagesearch implements the Azure ARM Imagesearch service API version 1.0.
//
// The Image Search API lets you send a search query to Bing and get back a list of relevant images. This section
// provides technical details about the query parameters and headers that you use to request images and the JSON
// response objects that contain them. For examples that show how to make requests, see [Searching the Web for
// Images](https://docs.microsoft.com/azure/cognitive-services/bing-image-search/search-the-web).
package imagesearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
const (
// DefaultBaseURI is the default URI used for the service Imagesearch
DefaultBaseURI = "https://api.cognitive.microsoft.com/bing/v7.0"
)
// BaseClient is the base client for Imagesearch.
type BaseClient struct {
autorest.Client
BaseURI string
}
// New creates an instance of the BaseClient client.
func New() BaseClient {
return NewWithBaseURI(DefaultBaseURI)
}
// NewWithBaseURI creates an instance of the BaseClient client.
func NewWithBaseURI(baseURI string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
}
}
@@ -0,0 +1,864 @@
package imagesearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// ImagesClient is the the Image Search API lets you send a search query to Bing and get back a list of relevant
// images. This section provides technical details about the query parameters and headers that you use to request
// images and the JSON response objects that contain them. For examples that show how to make requests, see [Searching
// the Web for Images](https://docs.microsoft.com/azure/cognitive-services/bing-image-search/search-the-web).
type ImagesClient struct {
BaseClient
}
// NewImagesClient creates an instance of the ImagesClient client.
func NewImagesClient() ImagesClient {
return NewImagesClientWithBaseURI(DefaultBaseURI)
}
// NewImagesClientWithBaseURI creates an instance of the ImagesClient client.
func NewImagesClientWithBaseURI(baseURI string) ImagesClient {
return ImagesClient{NewWithBaseURI(baseURI)}
}
// Details sends the details request.
//
// xBingApisSDK is activate swagger compliance query is the user's search query term. The term cannot be empty. The
// term may contain [Bing Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit
// images to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator. To help
// improve relevance of an insights query (see
// [insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken)),
// you should always include the user's query term. Use this parameter only with the Image Search API.Do not specify
// this parameter when calling the Trending Images API. acceptLanguage is a comma-delimited list of one or more
// languages to use for user interface strings. The list is in decreasing order of preference. For additional
// information, including expected format, see [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
// header and the
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#setlang) query
// parameter are mutually exclusive; do not specify both. If you set this header, you must also specify the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#cc) query parameter.
// To determine the market to return results for, Bing uses the first supported language it finds from the list and
// combines it with the cc parameter value. If the list does not include a supported language, Bing finds the closest
// language and market that supports the request or it uses an aggregated or default market for the results. To
// determine the market that Bing used, see the BingAPIs-Market header. Use this header and the cc query parameter only
// if you specify multiple languages. Otherwise, use the
// [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#mkt) and
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#setlang) query
// parameters. A user interface string is a string that's used as a label in a user interface. There are few user
// interface strings in the JSON response objects. Any links to Bing.com properties in the response objects apply the
// specified language. contentType is optional request header. If you set the
// [modules](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#modulesrequested)
// query parameter to RecognizedEntities, you may specify the binary of an image in the body of a POST request. If you
// specify the image in the body of a POST request, you must specify this header and set its value to
// multipart/form-data. The maximum image size is 1 MB. userAgent is the user agent originating the request. Bing uses
// the user agent to provide mobile users with an optimized experience. Although optional, you are encouraged to always
// specify this header. The user-agent should be the same string that any commonly used browser sends. For information
// about user agents, see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The following are
// examples of user-agent strings. Windows Phone: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0;
// IEMobile/10.0; ARM; Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500
// Build / GINGERBREAD) AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla /
// 5.0 (iPhone; CPU iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142 iPhone4; 1
// BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko.
// iPad: Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML, like Gecko) Version / 7.0 Mobile
// / 11A465 Safari / 9537.53 clientID is bing uses this header to provide users with consistent behavior across Bing
// API calls. Bing often flights new features and improvements, and it uses the client ID as a key for assigning
// traffic on different flights. If you do not use the same client ID for a user across multiple requests, then Bing
// may assign the user to multiple conflicting flights. Being assigned to multiple conflicting flights can lead to an
// inconsistent user experience. For example, if the second request has a different flight assignment than the first,
// the experience may be unexpected. Also, Bing can use the client ID to tailor web results to that client ID’s search
// history, providing a richer experience for the user. Bing also uses this header to help improve result rankings by
// analyzing the activity generated by a client ID. The relevance improvements help with better quality of results
// delivered by Bing APIs and in turn enables higher click-through rates for the API consumer. IMPORTANT: Although
// optional, you should consider this header required. Persisting the client ID across multiple requests for the same
// end user and device combination enables 1) the API consumer to receive a consistent user experience, and 2) higher
// click-through rates via better quality of results from the Bing APIs. Each user that uses your application on the
// device must have a unique, Bing generated client ID. If you do not include this header in the request, Bing
// generates an ID and returns it in the X-MSEdge-ClientID response header. The only time that you should NOT include
// this header in a request is the first time the user uses your app on that device. Use the client ID for each Bing
// API request that your app makes for this user on the device. Persist the client ID. To persist the ID in a browser
// app, use a persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session cookie. For
// other apps such as mobile apps, use the device's persistent storage to persist the ID. The next time the user uses
// your app on that device, get the client ID that you persisted. Bing responses may or may not include this header. If
// the response includes this header, capture the client ID and use it for all subsequent Bing requests for the user on
// that device. If you include the X-MSEdge-ClientID, you must not include cookies in the request. clientIP is the IPv4
// or IPv6 address of the client device. The IP address is used to discover the user's location. Bing uses the location
// information to determine safe search behavior. Although optional, you are encouraged to always specify this header
// and the X-Search-Location header. Do not obfuscate the address (for example, by changing the last octet to 0).
// Obfuscating the address results in the location not being anywhere near the device's actual location, which may
// result in Bing serving erroneous results. location is a semicolon-delimited list of key/value pairs that describe
// the client's geographical location. Bing uses the location information to determine safe search behavior and to
// return relevant local content. Specify the key/value pair as <key>:<value>. The following are the keys that you use
// to specify the user's location. lat (required): The latitude of the client's location, in degrees. The latitude must
// be greater than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and
// positive values indicate northern latitudes. long (required): The longitude of the client's location, in degrees.
// The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative values indicate
// western longitudes and positive values indicate eastern longitudes. re (required): The radius, in meters, which
// specifies the horizontal accuracy of the coordinates. Pass the value returned by the device's location service.
// Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts
// (optional): The UTC UNIX timestamp of when the client was at the location. (The UNIX timestamp is the number of
// seconds since January 1, 1970.) head (optional): The client's relative heading or direction of travel. Specify the
// direction of travel as degrees from 0 through 360, counting clockwise relative to true north. Specify this key only
// if the sp key is nonzero. sp (optional): The horizontal velocity (speed), in meters per second, that the client
// device is traveling. alt (optional): The altitude of the client device, in meters. are (optional): The radius, in
// meters, that specifies the vertical accuracy of the coordinates. Specify this key only if you specify the alt key.
// Although many of the keys are optional, the more information that you provide, the more accurate the location
// results are. Although optional, you are encouraged to always specify the user's geographical location. Providing the
// location is especially important if the client's IP address does not accurately reflect the user's physical location
// (for example, if the client uses VPN). For optimal results, you should include this header and the X-MSEdge-ClientIP
// header, but at a minimum, you should include this header. cropBottom is the bottom coordinate of the region to crop.
// The coordinate is a fractional value of the original image's height and is measured from the top, left corner of the
// image. Specify the coordinate as a value from 0.0 through 1.0. Use this parameter only with the Insights API. Do not
// specify this parameter when calling the Images, Trending Images, or Web Search APIs. cropLeft is the left coordinate
// of the region to crop. The coordinate is a fractional value of the original image's height and is measured from the
// top, left corner of the image. Specify the coordinate as a value from 0.0 through 1.0. Use this parameter only with
// the Insights API. Do not specify this parameter when calling the Images, Trending Images, or Web Search APIs.
// cropRight is the right coordinate of the region to crop. The coordinate is a fractional value of the original
// image's height and is measured from the top, left corner of the image. Specify the coordinate as a value from 0.0
// through 1.0. Use this parameter only with the Insights API. Do not specify this parameter when calling the Images,
// Trending Images, or Web Search APIs. cropTop is the top coordinate of the region to crop. The coordinate is a
// fractional value of the original image's height and is measured from the top, left corner of the image. Specify the
// coordinate as a value from 0.0 through 1.0. Use this parameter only with the Insights API. Do not specify this
// parameter when calling the Images, Trending Images, or Web Search APIs. cropType is the crop type to use when
// cropping the image based on the coordinates specified in the cal, cat, car, and cab parameters. The following are
// the possible values. 0: Rectangular (default). Use this parameter only with the Insights API. Do not specify this
// parameter when calling the Images, Trending Images, or Web Search APIs. countryCode is a 2-character country code of
// the country where the results come from. For a list of possible values, see [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#market-codes). If
// you set this parameter, you must also specify the
// [Accept-Language](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#acceptlanguage)
// header. Bing uses the first supported language it finds from the languages list, and combine that language with the
// country code that you specify to determine the market to return results for. If the languages list does not include
// a supported language, Bing finds the closest language and market that supports the request, or it may use an
// aggregated or default market for the results instead of a specified one. You should use this query parameter and the
// Accept-Language query parameter only if you specify multiple languages; otherwise, you should use the mkt and
// setLang query parameters. This parameter and the
// [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#mkt) query parameter
// are mutually exclusive—do not specify both. ID is an ID that uniquely identifies an image. Use this parameter to
// ensure that the specified image is the first image in the list of images that Bing returns. The
// [Image](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#image) object's
// imageId field contains the ID that you set this parameter to. imageURL is the URL of an image that you want to get
// insights of. Use this parameter as an alternative to using the insightsToken parameter to specify the image. You may
// also specify the image by placing the binary of the image in the body of a POST request. If you use the binary
// option, see the
// [Content-Type](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#contenttype)
// header. The maximum supported image size is 1 MB. Use this parameter only with the Insights API. Do not specify this
// parameter when calling the Images, Trending Images, or Web Search APIs. insightsToken is an image token. The
// [Image](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#image) object's
// [imageInsightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#image-imageinsightstoken)
// contains the token. Specify this parameter to get additional information about an image, such as a caption or
// shopping source. For a list of the additional information about an image that you can get, see the
// [modules](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#modulesrequested)
// query parameter. Use this parameter only with the Insights API. Do not specify this parameter when calling the
// Images, Trending Images, or Web Search APIs. modules is a comma-delimited list of insights to request. The following
// are the possible case-insensitive values. All: Return all insights, if available, except RecognizedEntities. BRQ:
// Best representative query. The query term that best describes the image. Caption: A caption that provides
// information about the image. If the caption contains entities, the response may include links to images of those
// entities. Collections: A list of related images. Recipes: A list of recipes for cooking the food shown in the
// images. PagesIncluding: A list of webpages that include the image. RecognizedEntities: A list of entities (people)
// that were recognized in the image. NOTE: You may not specify this module with any other module. If you specify it
// with other modules, the response doesn't include recognized entities. RelatedSearches: A list of related searches
// made by others. ShoppingSources: A list of merchants where you can buy related offerings. SimilarImages: A list of
// images that are visually similar to the original image. SimilarProducts: A list of images that contain a product
// that is similar to a product found in the original image. Tags: Provides characteristics of the type of content
// found in the image. For example, if the image is of a person, the tags might indicate the person's gender and type
// of clothes they're wearing. If you specify a module and there is no data for the module, the response object doesn't
// include the related field. For example, if you specify Caption and it does not exist, the response doesn't include
// the imageCaption field. To include related searches, the request must include the original query string. Although
// the original query string is not required for similar images or products, you should always include it because it
// can help improve relevance and the results. Use this parameter only with the Insights API. Do not specify this
// parameter when calling the Images, Trending Images, or Web Search APIs. market is the market where the results come
// from. Typically, mkt is the country where the user is making the request from. However, it could be a different
// country if the user is not located in a country where Bing delivers results. The market must be in the form
// <language code>-<country code>. For example, en-US. The string is case insensitive. For a list of possible market
// values, see [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#market-codes). NOTE:
// If known, you are encouraged to always specify the market. Specifying the market helps Bing route the request and
// return an appropriate and optimal response. If you specify a market that is not listed in [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#market-codes), Bing
// uses a best fit market code based on an internal mapping that is subject to change. This parameter and the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#cc) query parameter
// are mutually exclusive—do not specify both. safeSearch is filter images for adult content. The following are the
// possible filter values. Off: May return images with adult content. If the request is through the Image Search API,
// the response includes thumbnail images that are clear (non-fuzzy). However, if the request is through the Web Search
// API, the response includes thumbnail images that are pixelated (fuzzy). Moderate: If the request is through the
// Image Search API, the response doesn't include images with adult content. If the request is through the Web Search
// API, the response may include images with adult content (the thumbnail images are pixelated (fuzzy)). Strict: Do not
// return images with adult content. The default is Moderate. If the request comes from a market that Bing's adult
// policy requires that safeSearch is set to Strict, Bing ignores the safeSearch value and uses Strict. If you use the
// site: query operator, there is the chance that the response may contain adult content regardless of what the
// safeSearch query parameter is set to. Use site: only if you are aware of the content on the site and your scenario
// supports the possibility of adult content. setLang is the language to use for user interface strings. Specify the
// language using the ISO 639-1 2-letter language code. For example, the language code for English is EN. The default
// is EN (English). Although optional, you should always specify the language. Typically, you set setLang to the same
// language specified by mkt unless the user wants the user interface strings displayed in a different language. This
// parameter and the
// [Accept-Language](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#acceptlanguage)
// header are mutually exclusive; do not specify both. A user interface string is a string that's used as a label in a
// user interface. There are few user interface strings in the JSON response objects. Also, any links to Bing.com
// properties in the response objects apply the specified language.
func (client ImagesClient) Details(ctx context.Context, xBingApisSDK string, query string, acceptLanguage string, contentType string, userAgent string, clientID string, clientIP string, location string, cropBottom *float64, cropLeft *float64, cropRight *float64, cropTop *float64, cropType ImageCropType, countryCode string, ID string, imageURL string, insightsToken string, modules []ImageInsightModule, market string, safeSearch SafeSearch, setLang string) (result ImageInsights, err error) {
req, err := client.DetailsPreparer(ctx, xBingApisSDK, query, acceptLanguage, contentType, userAgent, clientID, clientIP, location, cropBottom, cropLeft, cropRight, cropTop, cropType, countryCode, ID, imageURL, insightsToken, modules, market, safeSearch, setLang)
if err != nil {
err = autorest.NewErrorWithError(err, "imagesearch.ImagesClient", "Details", nil, "Failure preparing request")
return
}
resp, err := client.DetailsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "imagesearch.ImagesClient", "Details", resp, "Failure sending request")
return
}
result, err = client.DetailsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "imagesearch.ImagesClient", "Details", resp, "Failure responding to request")
}
return
}
// DetailsPreparer prepares the Details request.
func (client ImagesClient) DetailsPreparer(ctx context.Context, xBingApisSDK string, query string, acceptLanguage string, contentType string, userAgent string, clientID string, clientIP string, location string, cropBottom *float64, cropLeft *float64, cropRight *float64, cropTop *float64, cropType ImageCropType, countryCode string, ID string, imageURL string, insightsToken string, modules []ImageInsightModule, market string, safeSearch SafeSearch, setLang string) (*http.Request, error) {
queryParameters := map[string]interface{}{
"q": autorest.Encode("query", query),
}
if cropBottom != nil {
queryParameters["cab"] = autorest.Encode("query", *cropBottom)
}
if cropLeft != nil {
queryParameters["cal"] = autorest.Encode("query", *cropLeft)
}
if cropRight != nil {
queryParameters["car"] = autorest.Encode("query", *cropRight)
}
if cropTop != nil {
queryParameters["cat"] = autorest.Encode("query", *cropTop)
}
if len(string(cropType)) > 0 {
queryParameters["ct"] = autorest.Encode("query", cropType)
}
if len(countryCode) > 0 {
queryParameters["cc"] = autorest.Encode("query", countryCode)
}
if len(ID) > 0 {
queryParameters["id"] = autorest.Encode("query", ID)
}
if len(imageURL) > 0 {
queryParameters["imgUrl"] = autorest.Encode("query", imageURL)
}
if len(insightsToken) > 0 {
queryParameters["insightsToken"] = autorest.Encode("query", insightsToken)
}
if modules != nil && len(modules) > 0 {
queryParameters["modules"] = autorest.Encode("query", modules, ",")
}
if len(market) > 0 {
queryParameters["mkt"] = autorest.Encode("query", market)
}
if len(string(safeSearch)) > 0 {
queryParameters["safeSearch"] = autorest.Encode("query", safeSearch)
}
if len(setLang) > 0 {
queryParameters["setLang"] = autorest.Encode("query", setLang)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/images/details"),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("X-BingApis-SDK", autorest.String(xBingApisSDK)))
if len(acceptLanguage) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
}
if len(contentType) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Content-Type", autorest.String(contentType)))
}
if len(userAgent) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("User-Agent", autorest.String(userAgent)))
}
if len(clientID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
}
if len(clientIP) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
}
if len(location) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-Search-Location", autorest.String(location)))
}
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DetailsSender sends the Details request. The method will close the
// http.Response Body if it receives an error.
func (client ImagesClient) DetailsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DetailsResponder handles the response to the Details request. The method always
// closes the http.Response Body.
func (client ImagesClient) DetailsResponder(resp *http.Response) (result ImageInsights, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Search sends the search request.
//
// xBingApisSDK is activate swagger compliance query is the user's search query term. The term cannot be empty. The
// term may contain [Bing Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit
// images to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator. To help
// improve relevance of an insights query (see
// [insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken)),
// you should always include the user's query term. Use this parameter only with the Image Search API.Do not specify
// this parameter when calling the Trending Images API. acceptLanguage is a comma-delimited list of one or more
// languages to use for user interface strings. The list is in decreasing order of preference. For additional
// information, including expected format, see [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
// header and the
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#setlang) query
// parameter are mutually exclusive; do not specify both. If you set this header, you must also specify the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#cc) query parameter.
// To determine the market to return results for, Bing uses the first supported language it finds from the list and
// combines it with the cc parameter value. If the list does not include a supported language, Bing finds the closest
// language and market that supports the request or it uses an aggregated or default market for the results. To
// determine the market that Bing used, see the BingAPIs-Market header. Use this header and the cc query parameter only
// if you specify multiple languages. Otherwise, use the
// [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#mkt) and
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#setlang) query
// parameters. A user interface string is a string that's used as a label in a user interface. There are few user
// interface strings in the JSON response objects. Any links to Bing.com properties in the response objects apply the
// specified language. userAgent is the user agent originating the request. Bing uses the user agent to provide mobile
// users with an optimized experience. Although optional, you are encouraged to always specify this header. The
// user-agent should be the same string that any commonly used browser sends. For information about user agents, see
// [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The following are examples of user-agent
// strings. Windows Phone: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM;
// Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build / GINGERBREAD)
// AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU
// iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142 iPhone4; 1 BingWeb /
// 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad:
// Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML, like Gecko) Version / 7.0 Mobile /
// 11A465 Safari / 9537.53 clientID is bing uses this header to provide users with consistent behavior across Bing API
// calls. Bing often flights new features and improvements, and it uses the client ID as a key for assigning traffic on
// different flights. If you do not use the same client ID for a user across multiple requests, then Bing may assign
// the user to multiple conflicting flights. Being assigned to multiple conflicting flights can lead to an inconsistent
// user experience. For example, if the second request has a different flight assignment than the first, the experience
// may be unexpected. Also, Bing can use the client ID to tailor web results to that client ID’s search history,
// providing a richer experience for the user. Bing also uses this header to help improve result rankings by analyzing
// the activity generated by a client ID. The relevance improvements help with better quality of results delivered by
// Bing APIs and in turn enables higher click-through rates for the API consumer. IMPORTANT: Although optional, you
// should consider this header required. Persisting the client ID across multiple requests for the same end user and
// device combination enables 1) the API consumer to receive a consistent user experience, and 2) higher click-through
// rates via better quality of results from the Bing APIs. Each user that uses your application on the device must have
// a unique, Bing generated client ID. If you do not include this header in the request, Bing generates an ID and
// returns it in the X-MSEdge-ClientID response header. The only time that you should NOT include this header in a
// request is the first time the user uses your app on that device. Use the client ID for each Bing API request that
// your app makes for this user on the device. Persist the client ID. To persist the ID in a browser app, use a
// persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session cookie. For other apps
// such as mobile apps, use the device's persistent storage to persist the ID. The next time the user uses your app on
// that device, get the client ID that you persisted. Bing responses may or may not include this header. If the
// response includes this header, capture the client ID and use it for all subsequent Bing requests for the user on
// that device. If you include the X-MSEdge-ClientID, you must not include cookies in the request. clientIP is the IPv4
// or IPv6 address of the client device. The IP address is used to discover the user's location. Bing uses the location
// information to determine safe search behavior. Although optional, you are encouraged to always specify this header
// and the X-Search-Location header. Do not obfuscate the address (for example, by changing the last octet to 0).
// Obfuscating the address results in the location not being anywhere near the device's actual location, which may
// result in Bing serving erroneous results. location is a semicolon-delimited list of key/value pairs that describe
// the client's geographical location. Bing uses the location information to determine safe search behavior and to
// return relevant local content. Specify the key/value pair as <key>:<value>. The following are the keys that you use
// to specify the user's location. lat (required): The latitude of the client's location, in degrees. The latitude must
// be greater than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and
// positive values indicate northern latitudes. long (required): The longitude of the client's location, in degrees.
// The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative values indicate
// western longitudes and positive values indicate eastern longitudes. re (required): The radius, in meters, which
// specifies the horizontal accuracy of the coordinates. Pass the value returned by the device's location service.
// Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts
// (optional): The UTC UNIX timestamp of when the client was at the location. (The UNIX timestamp is the number of
// seconds since January 1, 1970.) head (optional): The client's relative heading or direction of travel. Specify the
// direction of travel as degrees from 0 through 360, counting clockwise relative to true north. Specify this key only
// if the sp key is nonzero. sp (optional): The horizontal velocity (speed), in meters per second, that the client
// device is traveling. alt (optional): The altitude of the client device, in meters. are (optional): The radius, in
// meters, that specifies the vertical accuracy of the coordinates. Specify this key only if you specify the alt key.
// Although many of the keys are optional, the more information that you provide, the more accurate the location
// results are. Although optional, you are encouraged to always specify the user's geographical location. Providing the
// location is especially important if the client's IP address does not accurately reflect the user's physical location
// (for example, if the client uses VPN). For optimal results, you should include this header and the X-MSEdge-ClientIP
// header, but at a minimum, you should include this header. aspect is filter images by the following aspect ratios.
// All: Do not filter by aspect.Specifying this value is the same as not specifying the aspect parameter. Square:
// Return images with standard aspect ratio. Wide: Return images with wide screen aspect ratio. Tall: Return images
// with tall aspect ratio. colorParameter is filter images by the following color options. ColorOnly: Return color
// images. Monochrome: Return black and white images. Return images with one of the following dominant colors: Black,
// Blue, Brown, Gray, Green, Orange, Pink, Purple, Red, Teal, White, Yellow countryCode is a 2-character country code
// of the country where the results come from. For a list of possible values, see [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#market-codes). If
// you set this parameter, you must also specify the
// [Accept-Language](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#acceptlanguage)
// header. Bing uses the first supported language it finds from the languages list, and combine that language with the
// country code that you specify to determine the market to return results for. If the languages list does not include
// a supported language, Bing finds the closest language and market that supports the request, or it may use an
// aggregated or default market for the results instead of a specified one. You should use this query parameter and the
// Accept-Language query parameter only if you specify multiple languages; otherwise, you should use the mkt and
// setLang query parameters. This parameter and the
// [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#mkt) query parameter
// are mutually exclusive—do not specify both. count is the number of images to return in the response. The actual
// number delivered may be less than requested. The default is 35. The maximum value is 150. You use this parameter
// along with the offset parameter to page results.For example, if your user interface displays 20 images per page, set
// count to 20 and offset to 0 to get the first page of results.For each subsequent page, increment offset by 20 (for
// example, 0, 20, 40). Use this parameter only with the Image Search API.Do not specify this parameter when calling
// the Insights, Trending Images, or Web Search APIs. freshness is filter images by the following discovery options.
// Day: Return images discovered by Bing within the last 24 hours. Week: Return images discovered by Bing within the
// last 7 days. Month: Return images discovered by Bing within the last 30 days. height is filter images that have the
// specified height, in pixels. You may use this filter with the size filter to return small images that have a height
// of 150 pixels. ID is an ID that uniquely identifies an image. Use this parameter to ensure that the specified image
// is the first image in the list of images that Bing returns. The
// [Image](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#image) object's
// imageId field contains the ID that you set this parameter to. imageContent is filter images by the following content
// types. Face: Return images that show only a person's face. Portrait: Return images that show only a person's head
// and shoulders. imageType is filter images by the following image types. AnimatedGif: Return only animated GIFs.
// Clipart: Return only clip art images. Line: Return only line drawings. Photo: Return only photographs(excluding line
// drawings, animated Gifs, and clip art). Shopping: Return only images that contain items where Bing knows of a
// merchant that is selling the items. This option is valid in the en - US market only.Transparent: Return only images
// with a transparent background. license is filter images by the following license types. All: Do not filter by
// license type.Specifying this value is the same as not specifying the license parameter. Any: Return images that are
// under any license type. The response doesn't include images that do not specify a license or the license is unknown.
// Public: Return images where the creator has waived their exclusive rights, to the fullest extent allowed by law.
// Share: Return images that may be shared with others. Changing or editing the image might not be allowed. Also,
// modifying, sharing, and using the image for commercial purposes might not be allowed. Typically, this option returns
// the most images. ShareCommercially: Return images that may be shared with others for personal or commercial
// purposes. Changing or editing the image might not be allowed. Modify: Return images that may be modified, shared,
// and used. Changing or editing the image might not be allowed. Modifying, sharing, and using the image for commercial
// purposes might not be allowed. ModifyCommercially: Return images that may be modified, shared, and used for personal
// or commercial purposes. Typically, this option returns the fewest images. For more information about these license
// types, see [Filter Images By License Type](http://go.microsoft.com/fwlink/?LinkId=309768). market is the market
// where the results come from. Typically, mkt is the country where the user is making the request from. However, it
// could be a different country if the user is not located in a country where Bing delivers results. The market must be
// in the form <language code>-<country code>. For example, en-US. The string is case insensitive. For a list of
// possible market values, see [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#market-codes). NOTE:
// If known, you are encouraged to always specify the market. Specifying the market helps Bing route the request and
// return an appropriate and optimal response. If you specify a market that is not listed in [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#market-codes), Bing
// uses a best fit market code based on an internal mapping that is subject to change. This parameter and the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#cc) query parameter
// are mutually exclusive—do not specify both. maxFileSize is filter images that are less than or equal to the
// specified file size. The maximum file size that you may specify is 520,192 bytes. If you specify a larger value, the
// API uses 520,192. It is possible that the response may include images that are slightly larger than the specified
// maximum. You may specify this filter and minFileSize to filter images within a range of file sizes. maxHeight is
// filter images that have a height that is less than or equal to the specified height. Specify the height in pixels.
// You may specify this filter and minHeight to filter images within a range of heights. This filter and the height
// filter are mutually exclusive. maxWidth is filter images that have a width that is less than or equal to the
// specified width. Specify the width in pixels. You may specify this filter and maxWidth to filter images within a
// range of widths. This filter and the width filter are mutually exclusive. minFileSize is filter images that are
// greater than or equal to the specified file size. The maximum file size that you may specify is 520,192 bytes. If
// you specify a larger value, the API uses 520,192. It is possible that the response may include images that are
// slightly smaller than the specified minimum. You may specify this filter and maxFileSize to filter images within a
// range of file sizes. minHeight is filter images that have a height that is greater than or equal to the specified
// height. Specify the height in pixels. You may specify this filter and maxHeight to filter images within a range of
// heights. This filter and the height filter are mutually exclusive. minWidth is filter images that have a width that
// is greater than or equal to the specified width. Specify the width in pixels. You may specify this filter and
// maxWidth to filter images within a range of widths. This filter and the width filter are mutually exclusive. offset
// is the zero-based offset that indicates the number of images to skip before returning images. The default is 0. The
// offset should be less than
// ([totalEstimatedMatches](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#totalestimatedmatches)
// - count). Use this parameter along with the count parameter to page results. For example, if your user interface
// displays 20 images per page, set count to 20 and offset to 0 to get the first page of results. For each subsequent
// page, increment offset by 20 (for example, 0, 20, 40). It is possible for multiple pages to include some overlap in
// results. To prevent duplicates, see
// [nextOffset](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#nextoffset).
// Use this parameter only with the Image API. Do not specify this parameter when calling the Trending Images API or
// the Web Search API. safeSearch is filter images for adult content. The following are the possible filter values.
// Off: May return images with adult content. If the request is through the Image Search API, the response includes
// thumbnail images that are clear (non-fuzzy). However, if the request is through the Web Search API, the response
// includes thumbnail images that are pixelated (fuzzy). Moderate: If the request is through the Image Search API, the
// response doesn't include images with adult content. If the request is through the Web Search API, the response may
// include images with adult content (the thumbnail images are pixelated (fuzzy)). Strict: Do not return images with
// adult content. The default is Moderate. If the request comes from a market that Bing's adult policy requires that
// safeSearch is set to Strict, Bing ignores the safeSearch value and uses Strict. If you use the site: query operator,
// there is the chance that the response may contain adult content regardless of what the safeSearch query parameter is
// set to. Use site: only if you are aware of the content on the site and your scenario supports the possibility of
// adult content. size is filter images by the following sizes. All: Do not filter by size. Specifying this value is
// the same as not specifying the size parameter. Small: Return images that are less than 200x200 pixels. Medium:
// Return images that are greater than or equal to 200x200 pixels but less than 500x500 pixels. Large: Return images
// that are 500x500 pixels or larger. Wallpaper: Return wallpaper images. You may use this parameter along with the
// height or width parameters. For example, you may use height and size to request small images that are 150 pixels
// tall. setLang is the language to use for user interface strings. Specify the language using the ISO 639-1 2-letter
// language code. For example, the language code for English is EN. The default is EN (English). Although optional, you
// should always specify the language. Typically, you set setLang to the same language specified by mkt unless the user
// wants the user interface strings displayed in a different language. This parameter and the
// [Accept-Language](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#acceptlanguage)
// header are mutually exclusive; do not specify both. A user interface string is a string that's used as a label in a
// user interface. There are few user interface strings in the JSON response objects. Also, any links to Bing.com
// properties in the response objects apply the specified language. width is filter images that have the specified
// width, in pixels. You may use this filter with the size filter to return small images that have a width of 150
// pixels.
func (client ImagesClient) Search(ctx context.Context, xBingApisSDK string, query string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, aspect ImageAspect, colorParameter ImageColor, countryCode string, count *int32, freshness Freshness, height *int32, ID string, imageContent ImageContent, imageType ImageType, license ImageLicense, market string, maxFileSize *int64, maxHeight *int64, maxWidth *int64, minFileSize *int64, minHeight *int64, minWidth *int64, offset *int64, safeSearch SafeSearch, size ImageSize, setLang string, width *int32) (result Images, err error) {
req, err := client.SearchPreparer(ctx, xBingApisSDK, query, acceptLanguage, userAgent, clientID, clientIP, location, aspect, colorParameter, countryCode, count, freshness, height, ID, imageContent, imageType, license, market, maxFileSize, maxHeight, maxWidth, minFileSize, minHeight, minWidth, offset, safeSearch, size, setLang, width)
if err != nil {
err = autorest.NewErrorWithError(err, "imagesearch.ImagesClient", "Search", nil, "Failure preparing request")
return
}
resp, err := client.SearchSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "imagesearch.ImagesClient", "Search", resp, "Failure sending request")
return
}
result, err = client.SearchResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "imagesearch.ImagesClient", "Search", resp, "Failure responding to request")
}
return
}
// SearchPreparer prepares the Search request.
func (client ImagesClient) SearchPreparer(ctx context.Context, xBingApisSDK string, query string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, aspect ImageAspect, colorParameter ImageColor, countryCode string, count *int32, freshness Freshness, height *int32, ID string, imageContent ImageContent, imageType ImageType, license ImageLicense, market string, maxFileSize *int64, maxHeight *int64, maxWidth *int64, minFileSize *int64, minHeight *int64, minWidth *int64, offset *int64, safeSearch SafeSearch, size ImageSize, setLang string, width *int32) (*http.Request, error) {
queryParameters := map[string]interface{}{
"q": autorest.Encode("query", query),
}
if len(string(aspect)) > 0 {
queryParameters["aspect"] = autorest.Encode("query", aspect)
}
if len(string(colorParameter)) > 0 {
queryParameters["color"] = autorest.Encode("query", colorParameter)
}
if len(countryCode) > 0 {
queryParameters["cc"] = autorest.Encode("query", countryCode)
}
if count != nil {
queryParameters["count"] = autorest.Encode("query", *count)
}
if len(string(freshness)) > 0 {
queryParameters["freshness"] = autorest.Encode("query", freshness)
}
if height != nil {
queryParameters["height"] = autorest.Encode("query", *height)
}
if len(ID) > 0 {
queryParameters["id"] = autorest.Encode("query", ID)
}
if len(string(imageContent)) > 0 {
queryParameters["imageContent"] = autorest.Encode("query", imageContent)
}
if len(string(imageType)) > 0 {
queryParameters["imageType"] = autorest.Encode("query", imageType)
}
if len(string(license)) > 0 {
queryParameters["license"] = autorest.Encode("query", license)
}
if len(market) > 0 {
queryParameters["mkt"] = autorest.Encode("query", market)
}
if maxFileSize != nil {
queryParameters["maxFileSize"] = autorest.Encode("query", *maxFileSize)
}
if maxHeight != nil {
queryParameters["maxHeight"] = autorest.Encode("query", *maxHeight)
}
if maxWidth != nil {
queryParameters["maxWidth"] = autorest.Encode("query", *maxWidth)
}
if minFileSize != nil {
queryParameters["minFileSize"] = autorest.Encode("query", *minFileSize)
}
if minHeight != nil {
queryParameters["minHeight"] = autorest.Encode("query", *minHeight)
}
if minWidth != nil {
queryParameters["minWidth"] = autorest.Encode("query", *minWidth)
}
if offset != nil {
queryParameters["offset"] = autorest.Encode("query", *offset)
}
if len(string(safeSearch)) > 0 {
queryParameters["safeSearch"] = autorest.Encode("query", safeSearch)
}
if len(string(size)) > 0 {
queryParameters["size"] = autorest.Encode("query", size)
}
if len(setLang) > 0 {
queryParameters["setLang"] = autorest.Encode("query", setLang)
}
if width != nil {
queryParameters["width"] = autorest.Encode("query", *width)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/images/search"),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("X-BingApis-SDK", autorest.String(xBingApisSDK)))
if len(acceptLanguage) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
}
if len(userAgent) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("User-Agent", autorest.String(userAgent)))
}
if len(clientID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
}
if len(clientIP) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
}
if len(location) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-Search-Location", autorest.String(location)))
}
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// SearchSender sends the Search request. The method will close the
// http.Response Body if it receives an error.
func (client ImagesClient) SearchSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// SearchResponder handles the response to the Search request. The method always
// closes the http.Response Body.
func (client ImagesClient) SearchResponder(resp *http.Response) (result Images, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Trending sends the trending request.
//
// xBingApisSDK is activate swagger compliance acceptLanguage is a comma-delimited list of one or more languages to use
// for user interface strings. The list is in decreasing order of preference. For additional information, including
// expected format, see [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#setlang) query
// parameter are mutually exclusive; do not specify both. If you set this header, you must also specify the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#cc) query parameter.
// To determine the market to return results for, Bing uses the first supported language it finds from the list and
// combines it with the cc parameter value. If the list does not include a supported language, Bing finds the closest
// language and market that supports the request or it uses an aggregated or default market for the results. To
// determine the market that Bing used, see the BingAPIs-Market header. Use this header and the cc query parameter only
// if you specify multiple languages. Otherwise, use the
// [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#mkt) and
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#setlang) query
// parameters. A user interface string is a string that's used as a label in a user interface. There are few user
// interface strings in the JSON response objects. Any links to Bing.com properties in the response objects apply the
// specified language. userAgent is the user agent originating the request. Bing uses the user agent to provide mobile
// users with an optimized experience. Although optional, you are encouraged to always specify this header. The
// user-agent should be the same string that any commonly used browser sends. For information about user agents, see
// [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The following are examples of user-agent
// strings. Windows Phone: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM;
// Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build / GINGERBREAD)
// AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU
// iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142 iPhone4; 1 BingWeb /
// 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad:
// Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML, like Gecko) Version / 7.0 Mobile /
// 11A465 Safari / 9537.53 clientID is bing uses this header to provide users with consistent behavior across Bing API
// calls. Bing often flights new features and improvements, and it uses the client ID as a key for assigning traffic on
// different flights. If you do not use the same client ID for a user across multiple requests, then Bing may assign
// the user to multiple conflicting flights. Being assigned to multiple conflicting flights can lead to an inconsistent
// user experience. For example, if the second request has a different flight assignment than the first, the experience
// may be unexpected. Also, Bing can use the client ID to tailor web results to that client ID’s search history,
// providing a richer experience for the user. Bing also uses this header to help improve result rankings by analyzing
// the activity generated by a client ID. The relevance improvements help with better quality of results delivered by
// Bing APIs and in turn enables higher click-through rates for the API consumer. IMPORTANT: Although optional, you
// should consider this header required. Persisting the client ID across multiple requests for the same end user and
// device combination enables 1) the API consumer to receive a consistent user experience, and 2) higher click-through
// rates via better quality of results from the Bing APIs. Each user that uses your application on the device must have
// a unique, Bing generated client ID. If you do not include this header in the request, Bing generates an ID and
// returns it in the X-MSEdge-ClientID response header. The only time that you should NOT include this header in a
// request is the first time the user uses your app on that device. Use the client ID for each Bing API request that
// your app makes for this user on the device. Persist the client ID. To persist the ID in a browser app, use a
// persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session cookie. For other apps
// such as mobile apps, use the device's persistent storage to persist the ID. The next time the user uses your app on
// that device, get the client ID that you persisted. Bing responses may or may not include this header. If the
// response includes this header, capture the client ID and use it for all subsequent Bing requests for the user on
// that device. If you include the X-MSEdge-ClientID, you must not include cookies in the request. clientIP is the IPv4
// or IPv6 address of the client device. The IP address is used to discover the user's location. Bing uses the location
// information to determine safe search behavior. Although optional, you are encouraged to always specify this header
// and the X-Search-Location header. Do not obfuscate the address (for example, by changing the last octet to 0).
// Obfuscating the address results in the location not being anywhere near the device's actual location, which may
// result in Bing serving erroneous results. location is a semicolon-delimited list of key/value pairs that describe
// the client's geographical location. Bing uses the location information to determine safe search behavior and to
// return relevant local content. Specify the key/value pair as <key>:<value>. The following are the keys that you use
// to specify the user's location. lat (required): The latitude of the client's location, in degrees. The latitude must
// be greater than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and
// positive values indicate northern latitudes. long (required): The longitude of the client's location, in degrees.
// The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative values indicate
// western longitudes and positive values indicate eastern longitudes. re (required): The radius, in meters, which
// specifies the horizontal accuracy of the coordinates. Pass the value returned by the device's location service.
// Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts
// (optional): The UTC UNIX timestamp of when the client was at the location. (The UNIX timestamp is the number of
// seconds since January 1, 1970.) head (optional): The client's relative heading or direction of travel. Specify the
// direction of travel as degrees from 0 through 360, counting clockwise relative to true north. Specify this key only
// if the sp key is nonzero. sp (optional): The horizontal velocity (speed), in meters per second, that the client
// device is traveling. alt (optional): The altitude of the client device, in meters. are (optional): The radius, in
// meters, that specifies the vertical accuracy of the coordinates. Specify this key only if you specify the alt key.
// Although many of the keys are optional, the more information that you provide, the more accurate the location
// results are. Although optional, you are encouraged to always specify the user's geographical location. Providing the
// location is especially important if the client's IP address does not accurately reflect the user's physical location
// (for example, if the client uses VPN). For optimal results, you should include this header and the X-MSEdge-ClientIP
// header, but at a minimum, you should include this header. countryCode is a 2-character country code of the country
// where the results come from. This API supports only the United States, Canada, Australia, and China markets. If you
// specify this query parameter, it must be set to us, ca, au, or cn. If you set this parameter, you must also specify
// the Accept-Language header. Bing uses the first supported language it finds from the languages list, and combine
// that language with the country code that you specify to determine the market to return results for. If the languages
// list does not include a supported language, Bing finds the closest language and market that supports the request, or
// it may use an aggregated or default market for the results instead of a specified one. You should use this query
// parameter and the Accept-Language query parameter only if you specify multiple languages; otherwise, you should use
// the mkt and setLang query parameters. This parameter and the mkt query parameter are mutually exclusive—do not
// specify both. market is the market where the results come from. Typically, mkt is the country where the user is
// making the request from. However, it could be a different country if the user is not located in a country where Bing
// delivers results. The market must be in the form <language code>-<country code>. For example, en-US. The string is
// case insensitive. For a list of possible market values, see [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#market-codes). NOTE:
// If known, you are encouraged to always specify the market. Specifying the market helps Bing route the request and
// return an appropriate and optimal response. If you specify a market that is not listed in [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#market-codes), Bing
// uses a best fit market code based on an internal mapping that is subject to change. This parameter and the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#cc) query parameter
// are mutually exclusive—do not specify both. safeSearch is filter images for adult content. The following are the
// possible filter values. Off: May return images with adult content. If the request is through the Image Search API,
// the response includes thumbnail images that are clear (non-fuzzy). However, if the request is through the Web Search
// API, the response includes thumbnail images that are pixelated (fuzzy). Moderate: If the request is through the
// Image Search API, the response doesn't include images with adult content. If the request is through the Web Search
// API, the response may include images with adult content (the thumbnail images are pixelated (fuzzy)). Strict: Do not
// return images with adult content. The default is Moderate. If the request comes from a market that Bing's adult
// policy requires that safeSearch is set to Strict, Bing ignores the safeSearch value and uses Strict. If you use the
// site: query operator, there is the chance that the response may contain adult content regardless of what the
// safeSearch query parameter is set to. Use site: only if you are aware of the content on the site and your scenario
// supports the possibility of adult content. setLang is the language to use for user interface strings. Specify the
// language using the ISO 639-1 2-letter language code. For example, the language code for English is EN. The default
// is EN (English). Although optional, you should always specify the language. Typically, you set setLang to the same
// language specified by mkt unless the user wants the user interface strings displayed in a different language. This
// parameter and the
// [Accept-Language](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#acceptlanguage)
// header are mutually exclusive; do not specify both. A user interface string is a string that's used as a label in a
// user interface. There are few user interface strings in the JSON response objects. Also, any links to Bing.com
// properties in the response objects apply the specified language.
func (client ImagesClient) Trending(ctx context.Context, xBingApisSDK string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, countryCode string, market string, safeSearch SafeSearch, setLang string) (result TrendingImages, err error) {
req, err := client.TrendingPreparer(ctx, xBingApisSDK, acceptLanguage, userAgent, clientID, clientIP, location, countryCode, market, safeSearch, setLang)
if err != nil {
err = autorest.NewErrorWithError(err, "imagesearch.ImagesClient", "Trending", nil, "Failure preparing request")
return
}
resp, err := client.TrendingSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "imagesearch.ImagesClient", "Trending", resp, "Failure sending request")
return
}
result, err = client.TrendingResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "imagesearch.ImagesClient", "Trending", resp, "Failure responding to request")
}
return
}
// TrendingPreparer prepares the Trending request.
func (client ImagesClient) TrendingPreparer(ctx context.Context, xBingApisSDK string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, countryCode string, market string, safeSearch SafeSearch, setLang string) (*http.Request, error) {
queryParameters := map[string]interface{}{}
if len(countryCode) > 0 {
queryParameters["cc"] = autorest.Encode("query", countryCode)
}
if len(market) > 0 {
queryParameters["mkt"] = autorest.Encode("query", market)
}
if len(string(safeSearch)) > 0 {
queryParameters["safeSearch"] = autorest.Encode("query", safeSearch)
}
if len(setLang) > 0 {
queryParameters["setLang"] = autorest.Encode("query", setLang)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/images/trending"),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("X-BingApis-SDK", autorest.String(xBingApisSDK)))
if len(acceptLanguage) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
}
if len(userAgent) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("User-Agent", autorest.String(userAgent)))
}
if len(clientID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
}
if len(clientIP) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
}
if len(location) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-Search-Location", autorest.String(location)))
}
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// TrendingSender sends the Trending request. The method will close the
// http.Response Body if it receives an error.
func (client ImagesClient) TrendingSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// TrendingResponder handles the response to the Trending request. The method always
// closes the http.Response Body.
func (client ImagesClient) TrendingResponder(resp *http.Response) (result TrendingImages, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,28 @@
package imagesearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/v12.2.0-beta services"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v12.2.0-beta"
}
@@ -0,0 +1,52 @@
// Package newssearch implements the Azure ARM Newssearch service API version 1.0.
//
// The News Search API lets you send a search query to Bing and get back a list of news that are relevant to the search
// query. This section provides technical details about the query parameters and headers that you use to request news
// and the JSON response objects that contain them. For examples that show how to make requests, see [Searching the web
// for news](https://docs.microsoft.com/en-us/azure/cognitive-services/bing-news-search/search-the-web).
package newssearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
const (
// DefaultBaseURI is the default URI used for the service Newssearch
DefaultBaseURI = "https://api.cognitive.microsoft.com/bing/v7.0"
)
// BaseClient is the base client for Newssearch.
type BaseClient struct {
autorest.Client
BaseURI string
}
// New creates an instance of the BaseClient client.
func New() BaseClient {
return NewWithBaseURI(DefaultBaseURI)
}
// NewWithBaseURI creates an instance of the BaseClient client.
func NewWithBaseURI(baseURI string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,797 @@
package newssearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// NewsClient is the the News Search API lets you send a search query to Bing and get back a list of news that are
// relevant to the search query. This section provides technical details about the query parameters and headers that
// you use to request news and the JSON response objects that contain them. For examples that show how to make
// requests, see [Searching the web for
// news](https://docs.microsoft.com/en-us/azure/cognitive-services/bing-news-search/search-the-web).
type NewsClient struct {
BaseClient
}
// NewNewsClient creates an instance of the NewsClient client.
func NewNewsClient() NewsClient {
return NewNewsClientWithBaseURI(DefaultBaseURI)
}
// NewNewsClientWithBaseURI creates an instance of the NewsClient client.
func NewNewsClientWithBaseURI(baseURI string) NewsClient {
return NewsClient{NewWithBaseURI(baseURI)}
}
// Category sends the category request.
//
// xBingApisSDK is activate swagger compliance acceptLanguage is a comma-delimited list of one or more languages to use
// for user interface strings. The list is in decreasing order of preference. For additional information, including
// expected format, see [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#setlang) query
// parameter are mutually exclusive; do not specify both. If you set this header, you must also specify the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#cc) query parameter. To
// determine the market to return results for, Bing uses the first supported language it finds from the list and
// combines it with the cc parameter value. If the list does not include a supported language, Bing finds the closest
// language and market that supports the request or it uses an aggregated or default market for the results. To
// determine the market that Bing used, see the BingAPIs-Market header. Use this header and the cc query parameter only
// if you specify multiple languages. Otherwise, use the
// [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#mkt) and
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#setlang) query
// parameters. A user interface string is a string that's used as a label in a user interface. There are few user
// interface strings in the JSON response objects. Any links to Bing.com properties in the response objects apply the
// specified language. userAgent is the user agent originating the request. Bing uses the user agent to provide mobile
// users with an optimized experience. Although optional, you are encouraged to always specify this header. The
// user-agent should be the same string that any commonly used browser sends. For information about user agents, see
// [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The following are examples of user-agent
// strings. Windows Phone: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM;
// Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build / GINGERBREAD)
// AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU
// iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142 iPhone4; 1 BingWeb /
// 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad:
// Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML, like Gecko) Version / 7.0 Mobile /
// 11A465 Safari / 9537.53 clientID is bing uses this header to provide users with consistent behavior across Bing API
// calls. Bing often flights new features and improvements, and it uses the client ID as a key for assigning traffic on
// different flights. If you do not use the same client ID for a user across multiple requests, then Bing may assign
// the user to multiple conflicting flights. Being assigned to multiple conflicting flights can lead to an inconsistent
// user experience. For example, if the second request has a different flight assignment than the first, the experience
// may be unexpected. Also, Bing can use the client ID to tailor web results to that client ID’s search history,
// providing a richer experience for the user. Bing also uses this header to help improve result rankings by analyzing
// the activity generated by a client ID. The relevance improvements help with better quality of results delivered by
// Bing APIs and in turn enables higher click-through rates for the API consumer. IMPORTANT: Although optional, you
// should consider this header required. Persisting the client ID across multiple requests for the same end user and
// device combination enables 1) the API consumer to receive a consistent user experience, and 2) higher click-through
// rates via better quality of results from the Bing APIs. Each user that uses your application on the device must have
// a unique, Bing generated client ID. If you do not include this header in the request, Bing generates an ID and
// returns it in the X-MSEdge-ClientID response header. The only time that you should NOT include this header in a
// request is the first time the user uses your app on that device. Use the client ID for each Bing API request that
// your app makes for this user on the device. Persist the client ID. To persist the ID in a browser app, use a
// persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session cookie. For other apps
// such as mobile apps, use the device's persistent storage to persist the ID. The next time the user uses your app on
// that device, get the client ID that you persisted. Bing responses may or may not include this header. If the
// response includes this header, capture the client ID and use it for all subsequent Bing requests for the user on
// that device. If you include the X-MSEdge-ClientID, you must not include cookies in the request. clientIP is the IPv4
// or IPv6 address of the client device. The IP address is used to discover the user's location. Bing uses the location
// information to determine safe search behavior. Although optional, you are encouraged to always specify this header
// and the X-Search-Location header. Do not obfuscate the address (for example, by changing the last octet to 0).
// Obfuscating the address results in the location not being anywhere near the device's actual location, which may
// result in Bing serving erroneous results. location is a semicolon-delimited list of key/value pairs that describe
// the client's geographical location. Bing uses the location information to determine safe search behavior and to
// return relevant local content. Specify the key/value pair as <key>:<value>. The following are the keys that you use
// to specify the user's location. lat (required): The latitude of the client's location, in degrees. The latitude must
// be greater than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and
// positive values indicate northern latitudes. long (required): The longitude of the client's location, in degrees.
// The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative values indicate
// western longitudes and positive values indicate eastern longitudes. re (required): The radius, in meters, which
// specifies the horizontal accuracy of the coordinates. Pass the value returned by the device's location service.
// Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts
// (optional): The UTC UNIX timestamp of when the client was at the location. (The UNIX timestamp is the number of
// seconds since January 1, 1970.) head (optional): The client's relative heading or direction of travel. Specify the
// direction of travel as degrees from 0 through 360, counting clockwise relative to true north. Specify this key only
// if the sp key is nonzero. sp (optional): The horizontal velocity (speed), in meters per second, that the client
// device is traveling. alt (optional): The altitude of the client device, in meters. are (optional): The radius, in
// meters, that specifies the vertical accuracy of the coordinates. Specify this key only if you specify the alt key.
// Although many of the keys are optional, the more information that you provide, the more accurate the location
// results are. Although optional, you are encouraged to always specify the user's geographical location. Providing the
// location is especially important if the client's IP address does not accurately reflect the user's physical location
// (for example, if the client uses VPN). For optimal results, you should include this header and the X-MSEdge-ClientIP
// header, but at a minimum, you should include this header. countryCode is a 2-character country code of the country
// where the results come from. This API supports only the United States market. If you specify this query parameter,
// it must be set to us. If you set this parameter, you must also specify the Accept-Language header. Bing uses the
// first supported language it finds from the languages list, and combine that language with the country code that you
// specify to determine the market to return results for. If the languages list does not include a supported language,
// Bing finds the closest language and market that supports the request, or it may use an aggregated or default market
// for the results instead of a specified one. You should use this query parameter and the Accept-Language query
// parameter only if you specify multiple languages; otherwise, you should use the mkt and setLang query parameters.
// This parameter and the mkt query parameter are mutually exclusive—do not specify both. category is the category of
// articles to return. For example, Sports articles or Entertainment articles. For a list of possible categories, see
// [News Categories by
// Market](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#categories-by-market).
// Use this parameter only with News Category API. If you do not specify this parameter, the response includes both:
// Headline articles typically published in the last 24 hours from any category and articles from each parent category
// (up to four articles). If the article is a headline, the article's headline field is set to true. By default, the
// response includes up to 12 headline articles. To specify the number of headline articles to return, set the
// [headlineCount](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#headlineCount)
// query parameter. count is the number of news articles to return in the response. The actual number delivered may be
// less than requested. The default is 10 and the maximum value is 100. The actual number delivered may be less than
// requested.You may use this parameter along with the offset parameter to page results. For example, if your user
// interface displays 20 articles per page, set count to 20 and offset to 0 to get the first page of results. For each
// subsequent page, increment offset by 20 (for example, 0, 20, 40). It is possible for multiple pages to include some
// overlap in results. If you do not specify the
// [category](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#category)
// parameter, Bing ignores this paramter. headlineCount is the number of headline articles to return in the response.
// The default is 12. Specify this parameter only if you do not specify the
// [category](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#category)
// parameter. market is the market where the results come from. Typically, mkt is the country where the user is making
// the request from. However, it could be a different country if the user is not located in a country where Bing
// delivers results. The market must be in the form <language code>-<country code>. For example, en-US. The string is
// case insensitive. For a list of possible market values, see [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#market-codes). NOTE:
// If known, you are encouraged to always specify the market. Specifying the market helps Bing route the request and
// return an appropriate and optimal response. If you specify a market that is not listed in [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#market-codes), Bing
// uses a best fit market code based on an internal mapping that is subject to change. This parameter and the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#cc) query parameter are
// mutually exclusive—do not specify both. offset is the zero-based offset that indicates the number of news to skip
// before returning news. The default is 0. The offset should be less than
// ([totalEstimatedMatches](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#news-totalmatches)
// - count). Use this parameter along with the count parameter to page results. For example, if your user interface
// displays 20 news per page, set count to 20 and offset to 0 to get the first page of results. For each subsequent
// page, increment offset by 20 (for example, 0, 20, 40). It is possible for multiple pages to include some overlap in
// results. If you do not specify the
// [category](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#category)
// parameter, Bing ignores this paramter. originalImage is a Boolean value that determines whether the image's
// contentUrl contains a URL that points to a thumbnail of the original article's image or the image itself. If the
// article includes an image, and this parameter is set to true, the image's contentUrl property contains a URL that
// you may use to download the original image from the publisher's website. Otherwise, if this parameter is false, the
// image's contentUrl and thumbnailUrl URLs both point to the same thumbnail image. Use this parameter only with the
// News Search API or News Category API. Trending Topics API ignore this parameter. safeSearch is filter news for adult
// content. The following are the possible filter values. Off: Return news articles with adult text, images, or videos.
// Moderate: Return news articles with adult text but not adult images or videos. Strict: Do not return news articles
// with adult text, images, or videos. If the request comes from a market that Bing's adult policy requires that
// safeSearch is set to Strict, Bing ignores the safeSearch value and uses Strict. If you use the site: query operator,
// there is the chance that the response may contain adult content regardless of what the safeSearch query parameter is
// set to. Use site: only if you are aware of the content on the site and your scenario supports the possibility of
// adult content. setLang is the language to use for user interface strings. Specify the language using the ISO 639-1
// 2-letter language code. For example, the language code for English is EN. The default is EN (English). Although
// optional, you should always specify the language. Typically, you set setLang to the same language specified by mkt
// unless the user wants the user interface strings displayed in a different language. This parameter and the
// [Accept-Language](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#acceptlanguage)
// header are mutually exclusive; do not specify both. A user interface string is a string that's used as a label in a
// user interface. There are few user interface strings in the JSON response objects. Also, any links to Bing.com
// properties in the response objects apply the specified language. textDecorations is a Boolean value that determines
// whether display strings contain decoration markers such as hit highlighting characters. If true, the strings may
// include markers. The default is false. To specify whether to use Unicode characters or HTML tags as the markers, see
// the [textFormat](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#textformat)
// query parameter. For information about hit highlighting, see [Hit
// Highlighting](https://docs.microsoft.com/azure/cognitive-services/bing-news-search/hit-highlighting). textFormat is
// the type of markers to use for text decorations (see the textDecorations query parameter). Possible values are
// Raw—Use Unicode characters to mark content that needs special formatting. The Unicode characters are in the range
// E000 through E019. For example, Bing uses E000 and E001 to mark the beginning and end of query terms for hit
// highlighting. HTML—Use HTML tags to mark content that needs special formatting. For example, use <b> tags to
// highlight query terms in display strings. The default is Raw. For display strings that contain escapable HTML
// characters such as <, >, and &, if textFormat is set to HTML, Bing escapes the characters as appropriate (for
// example, < is escaped to &lt;).
func (client NewsClient) Category(ctx context.Context, xBingApisSDK string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, countryCode string, category string, count *int32, headlineCount *int32, market string, offset *int32, originalImage *bool, safeSearch SafeSearch, setLang string, textDecorations *bool, textFormat TextFormat) (result News, err error) {
req, err := client.CategoryPreparer(ctx, xBingApisSDK, acceptLanguage, userAgent, clientID, clientIP, location, countryCode, category, count, headlineCount, market, offset, originalImage, safeSearch, setLang, textDecorations, textFormat)
if err != nil {
err = autorest.NewErrorWithError(err, "newssearch.NewsClient", "Category", nil, "Failure preparing request")
return
}
resp, err := client.CategorySender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "newssearch.NewsClient", "Category", resp, "Failure sending request")
return
}
result, err = client.CategoryResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "newssearch.NewsClient", "Category", resp, "Failure responding to request")
}
return
}
// CategoryPreparer prepares the Category request.
func (client NewsClient) CategoryPreparer(ctx context.Context, xBingApisSDK string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, countryCode string, category string, count *int32, headlineCount *int32, market string, offset *int32, originalImage *bool, safeSearch SafeSearch, setLang string, textDecorations *bool, textFormat TextFormat) (*http.Request, error) {
queryParameters := map[string]interface{}{}
if len(countryCode) > 0 {
queryParameters["cc"] = autorest.Encode("query", countryCode)
}
if len(category) > 0 {
queryParameters["category"] = autorest.Encode("query", category)
}
if count != nil {
queryParameters["count"] = autorest.Encode("query", *count)
}
if headlineCount != nil {
queryParameters["headlineCount"] = autorest.Encode("query", *headlineCount)
}
if len(market) > 0 {
queryParameters["mkt"] = autorest.Encode("query", market)
}
if offset != nil {
queryParameters["offset"] = autorest.Encode("query", *offset)
}
if originalImage != nil {
queryParameters["originalImg"] = autorest.Encode("query", *originalImage)
}
if len(string(safeSearch)) > 0 {
queryParameters["safeSearch"] = autorest.Encode("query", safeSearch)
}
if len(setLang) > 0 {
queryParameters["setLang"] = autorest.Encode("query", setLang)
}
if textDecorations != nil {
queryParameters["textDecorations"] = autorest.Encode("query", *textDecorations)
}
if len(string(textFormat)) > 0 {
queryParameters["textFormat"] = autorest.Encode("query", textFormat)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/news"),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("X-BingApis-SDK", autorest.String(xBingApisSDK)))
if len(acceptLanguage) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
}
if len(userAgent) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("User-Agent", autorest.String(userAgent)))
}
if len(clientID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
}
if len(clientIP) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
}
if len(location) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-Search-Location", autorest.String(location)))
}
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CategorySender sends the Category request. The method will close the
// http.Response Body if it receives an error.
func (client NewsClient) CategorySender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// CategoryResponder handles the response to the Category request. The method always
// closes the http.Response Body.
func (client NewsClient) CategoryResponder(resp *http.Response) (result News, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Search sends the search request.
//
// xBingApisSDK is activate swagger compliance query is the user's search query string. The query string cannot be
// empty. The query string may contain [Bing Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For
// example, to limit news to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx)
// operator. Use this parameter only with the News Search API. Do not specify this parameter when calling the Trending
// Topics API or News Category API. acceptLanguage is a comma-delimited list of one or more languages to use for user
// interface strings. The list is in decreasing order of preference. For additional information, including expected
// format, see [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#setlang) query
// parameter are mutually exclusive; do not specify both. If you set this header, you must also specify the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#cc) query parameter. To
// determine the market to return results for, Bing uses the first supported language it finds from the list and
// combines it with the cc parameter value. If the list does not include a supported language, Bing finds the closest
// language and market that supports the request or it uses an aggregated or default market for the results. To
// determine the market that Bing used, see the BingAPIs-Market header. Use this header and the cc query parameter only
// if you specify multiple languages. Otherwise, use the
// [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#mkt) and
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#setlang) query
// parameters. A user interface string is a string that's used as a label in a user interface. There are few user
// interface strings in the JSON response objects. Any links to Bing.com properties in the response objects apply the
// specified language. userAgent is the user agent originating the request. Bing uses the user agent to provide mobile
// users with an optimized experience. Although optional, you are encouraged to always specify this header. The
// user-agent should be the same string that any commonly used browser sends. For information about user agents, see
// [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The following are examples of user-agent
// strings. Windows Phone: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM;
// Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build / GINGERBREAD)
// AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU
// iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142 iPhone4; 1 BingWeb /
// 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad:
// Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML, like Gecko) Version / 7.0 Mobile /
// 11A465 Safari / 9537.53 clientID is bing uses this header to provide users with consistent behavior across Bing API
// calls. Bing often flights new features and improvements, and it uses the client ID as a key for assigning traffic on
// different flights. If you do not use the same client ID for a user across multiple requests, then Bing may assign
// the user to multiple conflicting flights. Being assigned to multiple conflicting flights can lead to an inconsistent
// user experience. For example, if the second request has a different flight assignment than the first, the experience
// may be unexpected. Also, Bing can use the client ID to tailor web results to that client ID’s search history,
// providing a richer experience for the user. Bing also uses this header to help improve result rankings by analyzing
// the activity generated by a client ID. The relevance improvements help with better quality of results delivered by
// Bing APIs and in turn enables higher click-through rates for the API consumer. IMPORTANT: Although optional, you
// should consider this header required. Persisting the client ID across multiple requests for the same end user and
// device combination enables 1) the API consumer to receive a consistent user experience, and 2) higher click-through
// rates via better quality of results from the Bing APIs. Each user that uses your application on the device must have
// a unique, Bing generated client ID. If you do not include this header in the request, Bing generates an ID and
// returns it in the X-MSEdge-ClientID response header. The only time that you should NOT include this header in a
// request is the first time the user uses your app on that device. Use the client ID for each Bing API request that
// your app makes for this user on the device. Persist the client ID. To persist the ID in a browser app, use a
// persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session cookie. For other apps
// such as mobile apps, use the device's persistent storage to persist the ID. The next time the user uses your app on
// that device, get the client ID that you persisted. Bing responses may or may not include this header. If the
// response includes this header, capture the client ID and use it for all subsequent Bing requests for the user on
// that device. If you include the X-MSEdge-ClientID, you must not include cookies in the request. clientIP is the IPv4
// or IPv6 address of the client device. The IP address is used to discover the user's location. Bing uses the location
// information to determine safe search behavior. Although optional, you are encouraged to always specify this header
// and the X-Search-Location header. Do not obfuscate the address (for example, by changing the last octet to 0).
// Obfuscating the address results in the location not being anywhere near the device's actual location, which may
// result in Bing serving erroneous results. location is a semicolon-delimited list of key/value pairs that describe
// the client's geographical location. Bing uses the location information to determine safe search behavior and to
// return relevant local content. Specify the key/value pair as <key>:<value>. The following are the keys that you use
// to specify the user's location. lat (required): The latitude of the client's location, in degrees. The latitude must
// be greater than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and
// positive values indicate northern latitudes. long (required): The longitude of the client's location, in degrees.
// The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative values indicate
// western longitudes and positive values indicate eastern longitudes. re (required): The radius, in meters, which
// specifies the horizontal accuracy of the coordinates. Pass the value returned by the device's location service.
// Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts
// (optional): The UTC UNIX timestamp of when the client was at the location. (The UNIX timestamp is the number of
// seconds since January 1, 1970.) head (optional): The client's relative heading or direction of travel. Specify the
// direction of travel as degrees from 0 through 360, counting clockwise relative to true north. Specify this key only
// if the sp key is nonzero. sp (optional): The horizontal velocity (speed), in meters per second, that the client
// device is traveling. alt (optional): The altitude of the client device, in meters. are (optional): The radius, in
// meters, that specifies the vertical accuracy of the coordinates. Specify this key only if you specify the alt key.
// Although many of the keys are optional, the more information that you provide, the more accurate the location
// results are. Although optional, you are encouraged to always specify the user's geographical location. Providing the
// location is especially important if the client's IP address does not accurately reflect the user's physical location
// (for example, if the client uses VPN). For optimal results, you should include this header and the X-MSEdge-ClientIP
// header, but at a minimum, you should include this header. countryCode is a 2-character country code of the country
// where the results come from. This API supports only the United States market. If you specify this query parameter,
// it must be set to us. If you set this parameter, you must also specify the Accept-Language header. Bing uses the
// first supported language it finds from the languages list, and combine that language with the country code that you
// specify to determine the market to return results for. If the languages list does not include a supported language,
// Bing finds the closest language and market that supports the request, or it may use an aggregated or default market
// for the results instead of a specified one. You should use this query parameter and the Accept-Language query
// parameter only if you specify multiple languages; otherwise, you should use the mkt and setLang query parameters.
// This parameter and the mkt query parameter are mutually exclusive—do not specify both. count is the number of news
// articles to return in the response. The actual number delivered may be less than requested. The default is 10 and
// the maximum value is 100. The actual number delivered may be less than requested.You may use this parameter along
// with the offset parameter to page results. For example, if your user interface displays 20 articles per page, set
// count to 20 and offset to 0 to get the first page of results. For each subsequent page, increment offset by 20 (for
// example, 0, 20, 40). It is possible for multiple pages to include some overlap in results. freshness is filter news
// by the date and time that Bing discovered the news. The following are the possible filter values. Day: Return news
// discovered within the last 24 hours. Week: Return news discovered within the last 7 days. Month: Return news
// discovered within the last 30 days. Use this parameter only with the News Search API. Do not specify this parameter
// when calling the News Category API or the Trending Topics API. market is the market where the results come from.
// Typically, mkt is the country where the user is making the request from. However, it could be a different country if
// the user is not located in a country where Bing delivers results. The market must be in the form <language
// code>-<country code>. For example, en-US. The string is case insensitive. For a list of possible market values, see
// [Market Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#market-codes).
// NOTE: If known, you are encouraged to always specify the market. Specifying the market helps Bing route the request
// and return an appropriate and optimal response. If you specify a market that is not listed in [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#market-codes), Bing
// uses a best fit market code based on an internal mapping that is subject to change. This parameter and the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#cc) query parameter are
// mutually exclusive—do not specify both. offset is the zero-based offset that indicates the number of news to skip
// before returning news. The default is 0. The offset should be less than
// ([totalEstimatedMatches](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#news-totalmatches)
// - count). Use this parameter along with the count parameter to page results. For example, if your user interface
// displays 20 news per page, set count to 20 and offset to 0 to get the first page of results. For each subsequent
// page, increment offset by 20 (for example, 0, 20, 40). It is possible for multiple pages to include some overlap in
// results. originalImage is a Boolean value that determines whether the image's contentUrl contains a URL that points
// to a thumbnail of the original article's image or the image itself. If the article includes an image, and this
// parameter is set to true, the image's contentUrl property contains a URL that you may use to download the original
// image from the publisher's website. Otherwise, if this parameter is false, the image's contentUrl and thumbnailUrl
// URLs both point to the same thumbnail image. Use this parameter only with the News Search API. Do not specify this
// parameter when calling the Trending Topics API or News Category API. safeSearch is filter news for adult content.
// The following are the possible filter values. Off: Return news articles with adult text, images, or videos.
// Moderate: Return news articles with adult text but not adult images or videos. Strict: Do not return news articles
// with adult text, images, or videos. If the request comes from a market that Bing's adult policy requires that
// safeSearch is set to Strict, Bing ignores the safeSearch value and uses Strict. If you use the site: query operator,
// there is the chance that the response may contain adult content regardless of what the safeSearch query parameter is
// set to. Use site: only if you are aware of the content on the site and your scenario supports the possibility of
// adult content. setLang is the language to use for user interface strings. Specify the language using the ISO 639-1
// 2-letter language code. For example, the language code for English is EN. The default is EN (English). Although
// optional, you should always specify the language. Typically, you set setLang to the same language specified by mkt
// unless the user wants the user interface strings displayed in a different language. This parameter and the
// [Accept-Language](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#acceptlanguage)
// header are mutually exclusive; do not specify both. A user interface string is a string that's used as a label in a
// user interface. There are few user interface strings in the JSON response objects. Also, any links to Bing.com
// properties in the response objects apply the specified language. sortBy is the order to return the news in. The
// following are the possible case-insensitive values. Date: If the request is through the News Search API, the
// response returns news articles sorted by date from the most recent to the oldest. If the request is through the News
// Trending Topics API, the response returns trending topics sorted by date from the most recent to the oldest.
// textDecorations is a Boolean value that determines whether display strings contain decoration markers such as hit
// highlighting characters. If true, the strings may include markers. The default is false. To specify whether to use
// Unicode characters or HTML tags as the markers, see the
// [textFormat](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#textformat)
// query parameter. For information about hit highlighting, see [Hit
// Highlighting](https://docs.microsoft.com/azure/cognitive-services/bing-news-search/hit-highlighting). textFormat is
// the type of markers to use for text decorations (see the textDecorations query parameter). Possible values are
// Raw—Use Unicode characters to mark content that needs special formatting. The Unicode characters are in the range
// E000 through E019. For example, Bing uses E000 and E001 to mark the beginning and end of query terms for hit
// highlighting. HTML—Use HTML tags to mark content that needs special formatting. For example, use <b> tags to
// highlight query terms in display strings. The default is Raw. For display strings that contain escapable HTML
// characters such as <, >, and &, if textFormat is set to HTML, Bing escapes the characters as appropriate (for
// example, < is escaped to &lt;).
func (client NewsClient) Search(ctx context.Context, xBingApisSDK string, query string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, countryCode string, count *int32, freshness Freshness, market string, offset *int32, originalImage *bool, safeSearch SafeSearch, setLang string, sortBy string, textDecorations *bool, textFormat TextFormat) (result News, err error) {
req, err := client.SearchPreparer(ctx, xBingApisSDK, query, acceptLanguage, userAgent, clientID, clientIP, location, countryCode, count, freshness, market, offset, originalImage, safeSearch, setLang, sortBy, textDecorations, textFormat)
if err != nil {
err = autorest.NewErrorWithError(err, "newssearch.NewsClient", "Search", nil, "Failure preparing request")
return
}
resp, err := client.SearchSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "newssearch.NewsClient", "Search", resp, "Failure sending request")
return
}
result, err = client.SearchResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "newssearch.NewsClient", "Search", resp, "Failure responding to request")
}
return
}
// SearchPreparer prepares the Search request.
func (client NewsClient) SearchPreparer(ctx context.Context, xBingApisSDK string, query string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, countryCode string, count *int32, freshness Freshness, market string, offset *int32, originalImage *bool, safeSearch SafeSearch, setLang string, sortBy string, textDecorations *bool, textFormat TextFormat) (*http.Request, error) {
queryParameters := map[string]interface{}{
"q": autorest.Encode("query", query),
}
if len(countryCode) > 0 {
queryParameters["cc"] = autorest.Encode("query", countryCode)
}
if count != nil {
queryParameters["count"] = autorest.Encode("query", *count)
}
if len(string(freshness)) > 0 {
queryParameters["freshness"] = autorest.Encode("query", freshness)
}
if len(market) > 0 {
queryParameters["mkt"] = autorest.Encode("query", market)
}
if offset != nil {
queryParameters["offset"] = autorest.Encode("query", *offset)
}
if originalImage != nil {
queryParameters["originalImg"] = autorest.Encode("query", *originalImage)
}
if len(string(safeSearch)) > 0 {
queryParameters["safeSearch"] = autorest.Encode("query", safeSearch)
}
if len(setLang) > 0 {
queryParameters["setLang"] = autorest.Encode("query", setLang)
}
if len(sortBy) > 0 {
queryParameters["sortBy"] = autorest.Encode("query", sortBy)
}
if textDecorations != nil {
queryParameters["textDecorations"] = autorest.Encode("query", *textDecorations)
}
if len(string(textFormat)) > 0 {
queryParameters["textFormat"] = autorest.Encode("query", textFormat)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/news/search"),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("X-BingApis-SDK", autorest.String(xBingApisSDK)))
if len(acceptLanguage) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
}
if len(userAgent) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("User-Agent", autorest.String(userAgent)))
}
if len(clientID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
}
if len(clientIP) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
}
if len(location) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-Search-Location", autorest.String(location)))
}
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// SearchSender sends the Search request. The method will close the
// http.Response Body if it receives an error.
func (client NewsClient) SearchSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// SearchResponder handles the response to the Search request. The method always
// closes the http.Response Body.
func (client NewsClient) SearchResponder(resp *http.Response) (result News, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Trending sends the trending request.
//
// xBingApisSDK is activate swagger compliance acceptLanguage is a comma-delimited list of one or more languages to use
// for user interface strings. The list is in decreasing order of preference. For additional information, including
// expected format, see [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#setlang) query
// parameter are mutually exclusive; do not specify both. If you set this header, you must also specify the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#cc) query parameter. To
// determine the market to return results for, Bing uses the first supported language it finds from the list and
// combines it with the cc parameter value. If the list does not include a supported language, Bing finds the closest
// language and market that supports the request or it uses an aggregated or default market for the results. To
// determine the market that Bing used, see the BingAPIs-Market header. Use this header and the cc query parameter only
// if you specify multiple languages. Otherwise, use the
// [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#mkt) and
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#setlang) query
// parameters. A user interface string is a string that's used as a label in a user interface. There are few user
// interface strings in the JSON response objects. Any links to Bing.com properties in the response objects apply the
// specified language. userAgent is the user agent originating the request. Bing uses the user agent to provide mobile
// users with an optimized experience. Although optional, you are encouraged to always specify this header. The
// user-agent should be the same string that any commonly used browser sends. For information about user agents, see
// [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The following are examples of user-agent
// strings. Windows Phone: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM;
// Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build / GINGERBREAD)
// AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU
// iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142 iPhone4; 1 BingWeb /
// 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad:
// Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML, like Gecko) Version / 7.0 Mobile /
// 11A465 Safari / 9537.53 clientID is bing uses this header to provide users with consistent behavior across Bing API
// calls. Bing often flights new features and improvements, and it uses the client ID as a key for assigning traffic on
// different flights. If you do not use the same client ID for a user across multiple requests, then Bing may assign
// the user to multiple conflicting flights. Being assigned to multiple conflicting flights can lead to an inconsistent
// user experience. For example, if the second request has a different flight assignment than the first, the experience
// may be unexpected. Also, Bing can use the client ID to tailor web results to that client ID’s search history,
// providing a richer experience for the user. Bing also uses this header to help improve result rankings by analyzing
// the activity generated by a client ID. The relevance improvements help with better quality of results delivered by
// Bing APIs and in turn enables higher click-through rates for the API consumer. IMPORTANT: Although optional, you
// should consider this header required. Persisting the client ID across multiple requests for the same end user and
// device combination enables 1) the API consumer to receive a consistent user experience, and 2) higher click-through
// rates via better quality of results from the Bing APIs. Each user that uses your application on the device must have
// a unique, Bing generated client ID. If you do not include this header in the request, Bing generates an ID and
// returns it in the X-MSEdge-ClientID response header. The only time that you should NOT include this header in a
// request is the first time the user uses your app on that device. Use the client ID for each Bing API request that
// your app makes for this user on the device. Persist the client ID. To persist the ID in a browser app, use a
// persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session cookie. For other apps
// such as mobile apps, use the device's persistent storage to persist the ID. The next time the user uses your app on
// that device, get the client ID that you persisted. Bing responses may or may not include this header. If the
// response includes this header, capture the client ID and use it for all subsequent Bing requests for the user on
// that device. If you include the X-MSEdge-ClientID, you must not include cookies in the request. clientIP is the IPv4
// or IPv6 address of the client device. The IP address is used to discover the user's location. Bing uses the location
// information to determine safe search behavior. Although optional, you are encouraged to always specify this header
// and the X-Search-Location header. Do not obfuscate the address (for example, by changing the last octet to 0).
// Obfuscating the address results in the location not being anywhere near the device's actual location, which may
// result in Bing serving erroneous results. location is a semicolon-delimited list of key/value pairs that describe
// the client's geographical location. Bing uses the location information to determine safe search behavior and to
// return relevant local content. Specify the key/value pair as <key>:<value>. The following are the keys that you use
// to specify the user's location. lat (required): The latitude of the client's location, in degrees. The latitude must
// be greater than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and
// positive values indicate northern latitudes. long (required): The longitude of the client's location, in degrees.
// The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative values indicate
// western longitudes and positive values indicate eastern longitudes. re (required): The radius, in meters, which
// specifies the horizontal accuracy of the coordinates. Pass the value returned by the device's location service.
// Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts
// (optional): The UTC UNIX timestamp of when the client was at the location. (The UNIX timestamp is the number of
// seconds since January 1, 1970.) head (optional): The client's relative heading or direction of travel. Specify the
// direction of travel as degrees from 0 through 360, counting clockwise relative to true north. Specify this key only
// if the sp key is nonzero. sp (optional): The horizontal velocity (speed), in meters per second, that the client
// device is traveling. alt (optional): The altitude of the client device, in meters. are (optional): The radius, in
// meters, that specifies the vertical accuracy of the coordinates. Specify this key only if you specify the alt key.
// Although many of the keys are optional, the more information that you provide, the more accurate the location
// results are. Although optional, you are encouraged to always specify the user's geographical location. Providing the
// location is especially important if the client's IP address does not accurately reflect the user's physical location
// (for example, if the client uses VPN). For optimal results, you should include this header and the X-MSEdge-ClientIP
// header, but at a minimum, you should include this header. countryCode is a 2-character country code of the country
// where the results come from. This API supports only the United States market. If you specify this query parameter,
// it must be set to us. If you set this parameter, you must also specify the Accept-Language header. Bing uses the
// first supported language it finds from the languages list, and combine that language with the country code that you
// specify to determine the market to return results for. If the languages list does not include a supported language,
// Bing finds the closest language and market that supports the request, or it may use an aggregated or default market
// for the results instead of a specified one. You should use this query parameter and the Accept-Language query
// parameter only if you specify multiple languages; otherwise, you should use the mkt and setLang query parameters.
// This parameter and the mkt query parameter are mutually exclusive—do not specify both. count is the number of news
// articles to return in the response. The actual number delivered may be less than requested. The default is 10 and
// the maximum value is 100. The actual number delivered may be less than requested.You may use this parameter along
// with the offset parameter to page results. For example, if your user interface displays 20 articles per page, set
// count to 20 and offset to 0 to get the first page of results. For each subsequent page, increment offset by 20 (for
// example, 0, 20, 40). It is possible for multiple pages to include some overlap in results. market is the market
// where the results come from. Typically, mkt is the country where the user is making the request from. However, it
// could be a different country if the user is not located in a country where Bing delivers results. The market must be
// in the form <language code>-<country code>. For example, en-US. The string is case insensitive. For a list of
// possible market values, see [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#market-codes). NOTE:
// If known, you are encouraged to always specify the market. Specifying the market helps Bing route the request and
// return an appropriate and optimal response. If you specify a market that is not listed in [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#market-codes), Bing
// uses a best fit market code based on an internal mapping that is subject to change. This parameter and the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#cc) query parameter are
// mutually exclusive—do not specify both. offset is the zero-based offset that indicates the number of news to skip
// before returning news. The default is 0. The offset should be less than
// ([totalEstimatedMatches](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#news-totalmatches)
// - count). Use this parameter along with the count parameter to page results. For example, if your user interface
// displays 20 news per page, set count to 20 and offset to 0 to get the first page of results. For each subsequent
// page, increment offset by 20 (for example, 0, 20, 40). It is possible for multiple pages to include some overlap in
// results. safeSearch is filter news for adult content. The following are the possible filter values. Off: Return news
// articles with adult text, images, or videos. Moderate: Return news articles with adult text but not adult images or
// videos. Strict: Do not return news articles with adult text, images, or videos. If the request comes from a market
// that Bing's adult policy requires that safeSearch is set to Strict, Bing ignores the safeSearch value and uses
// Strict. If you use the site: query operator, there is the chance that the response may contain adult content
// regardless of what the safeSearch query parameter is set to. Use site: only if you are aware of the content on the
// site and your scenario supports the possibility of adult content. setLang is the language to use for user interface
// strings. Specify the language using the ISO 639-1 2-letter language code. For example, the language code for English
// is EN. The default is EN (English). Although optional, you should always specify the language. Typically, you set
// setLang to the same language specified by mkt unless the user wants the user interface strings displayed in a
// different language. This parameter and the
// [Accept-Language](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#acceptlanguage)
// header are mutually exclusive; do not specify both. A user interface string is a string that's used as a label in a
// user interface. There are few user interface strings in the JSON response objects. Also, any links to Bing.com
// properties in the response objects apply the specified language. since is the Unix epoch time (Unix timestamp) that
// Bing uses to select the trending topics. Bing returns trending topics that it discovered on or after the specified
// date and time, not the date the topic was published. To use this parameter, also specify the sortBy parameter. Use
// this parameter only with the News Trending Topics API. Do not specify this parameter when calling the News Search
// API or News Category API. sortBy is the order to return the news in. The following are the possible case-insensitive
// values. Date: If the request is through the News Search API, the response returns news articles sorted by date from
// the most recent to the oldest. If the request is through the News Trending Topics API, the response returns trending
// topics sorted by date from the most recent to the oldest. textDecorations is a Boolean value that determines whether
// display strings contain decoration markers such as hit highlighting characters. If true, the strings may include
// markers. The default is false. To specify whether to use Unicode characters or HTML tags as the markers, see the
// [textFormat](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference#textformat)
// query parameter. For information about hit highlighting, see [Hit
// Highlighting](https://docs.microsoft.com/azure/cognitive-services/bing-news-search/hit-highlighting). textFormat is
// the type of markers to use for text decorations (see the textDecorations query parameter). Possible values are
// Raw—Use Unicode characters to mark content that needs special formatting. The Unicode characters are in the range
// E000 through E019. For example, Bing uses E000 and E001 to mark the beginning and end of query terms for hit
// highlighting. HTML—Use HTML tags to mark content that needs special formatting. For example, use <b> tags to
// highlight query terms in display strings. The default is Raw. For display strings that contain escapable HTML
// characters such as <, >, and &, if textFormat is set to HTML, Bing escapes the characters as appropriate (for
// example, < is escaped to &lt;).
func (client NewsClient) Trending(ctx context.Context, xBingApisSDK string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, countryCode string, count *int32, market string, offset *int32, safeSearch SafeSearch, setLang string, since *int64, sortBy string, textDecorations *bool, textFormat TextFormat) (result TrendingTopics, err error) {
req, err := client.TrendingPreparer(ctx, xBingApisSDK, acceptLanguage, userAgent, clientID, clientIP, location, countryCode, count, market, offset, safeSearch, setLang, since, sortBy, textDecorations, textFormat)
if err != nil {
err = autorest.NewErrorWithError(err, "newssearch.NewsClient", "Trending", nil, "Failure preparing request")
return
}
resp, err := client.TrendingSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "newssearch.NewsClient", "Trending", resp, "Failure sending request")
return
}
result, err = client.TrendingResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "newssearch.NewsClient", "Trending", resp, "Failure responding to request")
}
return
}
// TrendingPreparer prepares the Trending request.
func (client NewsClient) TrendingPreparer(ctx context.Context, xBingApisSDK string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, countryCode string, count *int32, market string, offset *int32, safeSearch SafeSearch, setLang string, since *int64, sortBy string, textDecorations *bool, textFormat TextFormat) (*http.Request, error) {
queryParameters := map[string]interface{}{}
if len(countryCode) > 0 {
queryParameters["cc"] = autorest.Encode("query", countryCode)
}
if count != nil {
queryParameters["count"] = autorest.Encode("query", *count)
}
if len(market) > 0 {
queryParameters["mkt"] = autorest.Encode("query", market)
}
if offset != nil {
queryParameters["offset"] = autorest.Encode("query", *offset)
}
if len(string(safeSearch)) > 0 {
queryParameters["safeSearch"] = autorest.Encode("query", safeSearch)
}
if len(setLang) > 0 {
queryParameters["setLang"] = autorest.Encode("query", setLang)
}
if since != nil {
queryParameters["since"] = autorest.Encode("query", *since)
}
if len(sortBy) > 0 {
queryParameters["sortBy"] = autorest.Encode("query", sortBy)
}
if textDecorations != nil {
queryParameters["textDecorations"] = autorest.Encode("query", *textDecorations)
}
if len(string(textFormat)) > 0 {
queryParameters["textFormat"] = autorest.Encode("query", textFormat)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/news/trendingtopics"),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("X-BingApis-SDK", autorest.String(xBingApisSDK)))
if len(acceptLanguage) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
}
if len(userAgent) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("User-Agent", autorest.String(userAgent)))
}
if len(clientID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
}
if len(clientIP) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
}
if len(location) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-Search-Location", autorest.String(location)))
}
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// TrendingSender sends the Trending request. The method will close the
// http.Response Body if it receives an error.
func (client NewsClient) TrendingSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// TrendingResponder handles the response to the Trending request. The method always
// closes the http.Response Body.
func (client NewsClient) TrendingResponder(resp *http.Response) (result TrendingTopics, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,28 @@
package newssearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/v12.2.0-beta services"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v12.2.0-beta"
}
@@ -0,0 +1,283 @@
// Package spellcheck implements the Azure ARM Spellcheck service API version 1.0.
//
// The Spell Check API - V7 lets you check a text string for spelling and grammar errors.
package spellcheck
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
const (
// DefaultBaseURI is the default URI used for the service Spellcheck
DefaultBaseURI = "https://api.cognitive.microsoft.com/bing/v7.0"
)
// BaseClient is the base client for Spellcheck.
type BaseClient struct {
autorest.Client
BaseURI string
}
// New creates an instance of the BaseClient client.
func New() BaseClient {
return NewWithBaseURI(DefaultBaseURI)
}
// NewWithBaseURI creates an instance of the BaseClient client.
func NewWithBaseURI(baseURI string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
}
}
// SpellCheckerMethod sends the spell checker method request.
//
// xBingApisSDK is activate swagger compliance textParameter is the text string to check for spelling and grammar
// errors. The combined length of the text string, preContextText string, and postContextText string may not exceed
// 10,000 characters. You may specify this parameter in the query string of a GET request or in the body of a POST
// request. Because of the query string length limit, you'll typically use a POST request unless you're checking only
// short strings. acceptLanguage is a comma-delimited list of one or more languages to use for user interface strings.
// The list is in decreasing order of preference. For additional information, including expected format, see
// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the setLang query parameter are
// mutually exclusive; do not specify both. If you set this header, you must also specify the cc query parameter. Bing
// will use the first supported language it finds from the list, and combine that language with the cc parameter value
// to determine the market to return results for. If the list does not include a supported language, Bing will find the
// closest language and market that supports the request, and may use an aggregated or default market for the results
// instead of a specified one. You should use this header and the cc query parameter only if you specify multiple
// languages; otherwise, you should use the mkt and setLang query parameters. A user interface string is a string
// that's used as a label in a user interface. There are very few user interface strings in the JSON response objects.
// Any links in the response objects to Bing.com properties will apply the specified language. pragma is by default,
// Bing returns cached content, if available. To prevent Bing from returning cached content, set the Pragma header to
// no-cache (for example, Pragma: no-cache). userAgent is the user agent originating the request. Bing uses the user
// agent to provide mobile users with an optimized experience. Although optional, you are strongly encouraged to always
// specify this header. The user-agent should be the same string that any commonly used browser would send. For
// information about user agents, see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). clientID is
// bing uses this header to provide users with consistent behavior across Bing API calls. Bing often flights new
// features and improvements, and it uses the client ID as a key for assigning traffic on different flights. If you do
// not use the same client ID for a user across multiple requests, then Bing may assign the user to multiple
// conflicting flights. Being assigned to multiple conflicting flights can lead to an inconsistent user experience. For
// example, if the second request has a different flight assignment than the first, the experience may be unexpected.
// Also, Bing can use the client ID to tailor web results to that client ID’s search history, providing a richer
// experience for the user. Bing also uses this header to help improve result rankings by analyzing the activity
// generated by a client ID. The relevance improvements help with better quality of results delivered by Bing APIs and
// in turn enables higher click-through rates for the API consumer. IMPORTANT: Although optional, you should consider
// this header required. Persisting the client ID across multiple requests for the same end user and device combination
// enables 1) the API consumer to receive a consistent user experience, and 2) higher click-through rates via better
// quality of results from the Bing APIs. Each user that uses your application on the device must have a unique, Bing
// generated client ID. If you do not include this header in the request, Bing generates an ID and returns it in the
// X-MSEdge-ClientID response header. The only time that you should NOT include this header in a request is the first
// time the user uses your app on that device. Use the client ID for each Bing API request that your app makes for this
// user on the device. Persist the client ID. To persist the ID in a browser app, use a persistent HTTP cookie to
// ensure the ID is used across all sessions. Do not use a session cookie. For other apps such as mobile apps, use the
// device's persistent storage to persist the ID. The next time the user uses your app on that device, get the client
// ID that you persisted. Bing responses may or may not include this header. If the response includes this header,
// capture the client ID and use it for all subsequent Bing requests for the user on that device. If you include the
// X-MSEdge-ClientID, you must not include cookies in the request. clientIP is the IPv4 or IPv6 address of the client
// device. The IP address is used to discover the user's location. Bing uses the location information to determine safe
// search behavior. Although optional, you are encouraged to always specify this header and the X-Search-Location
// header. Do not obfuscate the address (for example, by changing the last octet to 0). Obfuscating the address results
// in the location not being anywhere near the device's actual location, which may result in Bing serving erroneous
// results. location is a semicolon-delimited list of key/value pairs that describe the client's geographical location.
// Bing uses the location information to determine safe search behavior and to return relevant local content. Specify
// the key/value pair as <key>:<value>. The following are the keys that you use to specify the user's location. lat
// (required): The latitude of the client's location, in degrees. The latitude must be greater than or equal to -90.0
// and less than or equal to +90.0. Negative values indicate southern latitudes and positive values indicate northern
// latitudes. long (required): The longitude of the client's location, in degrees. The longitude must be greater than
// or equal to -180.0 and less than or equal to +180.0. Negative values indicate western longitudes and positive values
// indicate eastern longitudes. re (required): The radius, in meters, which specifies the horizontal accuracy of the
// coordinates. Pass the value returned by the device's location service. Typical values might be 22m for GPS/Wi-Fi,
// 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts (optional): The UTC UNIX timestamp of when
// the client was at the location. (The UNIX timestamp is the number of seconds since January 1, 1970.) head
// (optional): The client's relative heading or direction of travel. Specify the direction of travel as degrees from 0
// through 360, counting clockwise relative to true north. Specify this key only if the sp key is nonzero. sp
// (optional): The horizontal velocity (speed), in meters per second, that the client device is traveling. alt
// (optional): The altitude of the client device, in meters. are (optional): The radius, in meters, that specifies the
// vertical accuracy of the coordinates. Specify this key only if you specify the alt key. Although many of the keys
// are optional, the more information that you provide, the more accurate the location results are. Although optional,
// you are encouraged to always specify the user's geographical location. Providing the location is especially
// important if the client's IP address does not accurately reflect the user's physical location (for example, if the
// client uses VPN). For optimal results, you should include this header and the X-Search-ClientIP header, but at a
// minimum, you should include this header. actionType is a string that's used by logging to determine whether the
// request is coming from an interactive session or a page load. The following are the possible values. 1) Edit—The
// request is from an interactive session 2) Load—The request is from a page load appName is the unique name of your
// app. The name must be known by Bing. Do not include this parameter unless you have previously contacted Bing to get
// a unique app name. To get a unique name, contact your Bing Business Development manager. countryCode is a
// 2-character country code of the country where the results come from. This API supports only the United States
// market. If you specify this query parameter, it must be set to us. If you set this parameter, you must also specify
// the Accept-Language header. Bing uses the first supported language it finds from the languages list, and combine
// that language with the country code that you specify to determine the market to return results for. If the languages
// list does not include a supported language, Bing finds the closest language and market that supports the request, or
// it may use an aggregated or default market for the results instead of a specified one. You should use this query
// parameter and the Accept-Language query parameter only if you specify multiple languages; otherwise, you should use
// the mkt and setLang query parameters. This parameter and the mkt query parameter are mutually exclusive—do not
// specify both. clientMachineName is a unique name of the device that the request is being made from. Generate a
// unique value for each device (the value is unimportant). The service uses the ID to help debug issues and improve
// the quality of corrections. docID is a unique ID that identifies the document that the text belongs to. Generate a
// unique value for each document (the value is unimportant). The service uses the ID to help debug issues and improve
// the quality of corrections. market is the market where the results come from. You are strongly encouraged to always
// specify the market, if known. Specifying the market helps Bing route the request and return an appropriate and
// optimal response. This parameter and the cc query parameter are mutually exclusive—do not specify both. sessionID is
// a unique ID that identifies this user session. Generate a unique value for each user session (the value is
// unimportant). The service uses the ID to help debug issues and improve the quality of corrections setLang is the
// language to use for user interface strings. Specify the language using the ISO 639-1 2-letter language code. For
// example, the language code for English is EN. The default is EN (English). Although optional, you should always
// specify the language. Typically, you set setLang to the same language specified by mkt unless the user wants the
// user interface strings displayed in a different language. This parameter and the Accept-Language header are mutually
// exclusive—do not specify both. A user interface string is a string that's used as a label in a user interface. There
// are few user interface strings in the JSON response objects. Also, any links to Bing.com properties in the response
// objects apply the specified language. userID is a unique ID that identifies the user. Generate a unique value for
// each user (the value is unimportant). The service uses the ID to help debug issues and improve the quality of
// corrections. mode is the type of spelling and grammar checks to perform. The following are the possible values (the
// values are case insensitive). The default is Proof. 1) Proof—Finds most spelling and grammar mistakes. 2)
// Spell—Finds most spelling mistakes but does not find some of the grammar errors that Proof catches (for example,
// capitalization and repeated words) preContextText is a string that gives context to the text string. For example,
// the text string petal is valid. However, if you set preContextText to bike, the context changes and the text string
// becomes not valid. In this case, the API suggests that you change petal to pedal (as in bike pedal). This text is
// not checked for grammar or spelling errors. The combined length of the text string, preContextText string, and
// postContextText string may not exceed 10,000 characters. You may specify this parameter in the query string of a GET
// request or in the body of a POST request. postContextText is a string that gives context to the text string. For
// example, the text string read is valid. However, if you set postContextText to carpet, the context changes and the
// text string becomes not valid. In this case, the API suggests that you change read to red (as in red carpet). This
// text is not checked for grammar or spelling errors. The combined length of the text string, preContextText string,
// and postContextText string may not exceed 10,000 characters. You may specify this parameter in the query string of a
// GET request or in the body of a POST request.
func (client BaseClient) SpellCheckerMethod(ctx context.Context, xBingApisSDK string, textParameter string, acceptLanguage string, pragma string, userAgent string, clientID string, clientIP string, location string, actionType ActionType, appName string, countryCode string, clientMachineName string, docID string, market string, sessionID string, setLang string, userID string, mode string, preContextText string, postContextText string) (result SpellCheck, err error) {
req, err := client.SpellCheckerMethodPreparer(ctx, xBingApisSDK, textParameter, acceptLanguage, pragma, userAgent, clientID, clientIP, location, actionType, appName, countryCode, clientMachineName, docID, market, sessionID, setLang, userID, mode, preContextText, postContextText)
if err != nil {
err = autorest.NewErrorWithError(err, "spellcheck.BaseClient", "SpellCheckerMethod", nil, "Failure preparing request")
return
}
resp, err := client.SpellCheckerMethodSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "spellcheck.BaseClient", "SpellCheckerMethod", resp, "Failure sending request")
return
}
result, err = client.SpellCheckerMethodResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "spellcheck.BaseClient", "SpellCheckerMethod", resp, "Failure responding to request")
}
return
}
// SpellCheckerMethodPreparer prepares the SpellCheckerMethod request.
func (client BaseClient) SpellCheckerMethodPreparer(ctx context.Context, xBingApisSDK string, textParameter string, acceptLanguage string, pragma string, userAgent string, clientID string, clientIP string, location string, actionType ActionType, appName string, countryCode string, clientMachineName string, docID string, market string, sessionID string, setLang string, userID string, mode string, preContextText string, postContextText string) (*http.Request, error) {
queryParameters := map[string]interface{}{}
if len(string(actionType)) > 0 {
queryParameters["ActionType"] = autorest.Encode("query", actionType)
}
if len(appName) > 0 {
queryParameters["AppName"] = autorest.Encode("query", appName)
}
if len(countryCode) > 0 {
queryParameters["cc"] = autorest.Encode("query", countryCode)
}
if len(clientMachineName) > 0 {
queryParameters["ClientMachineName"] = autorest.Encode("query", clientMachineName)
}
if len(docID) > 0 {
queryParameters["DocId"] = autorest.Encode("query", docID)
}
if len(market) > 0 {
queryParameters["mkt"] = autorest.Encode("query", market)
}
if len(sessionID) > 0 {
queryParameters["SessionId"] = autorest.Encode("query", sessionID)
}
if len(setLang) > 0 {
queryParameters["SetLang"] = autorest.Encode("query", setLang)
}
if len(userID) > 0 {
queryParameters["UserId"] = autorest.Encode("query", userID)
}
formDataParameters := map[string]interface{}{
"Text": textParameter,
}
if len(string(mode)) > 0 {
formDataParameters["Mode"] = mode
}
if len(preContextText) > 0 {
formDataParameters["PreContextText"] = preContextText
}
if len(postContextText) > 0 {
formDataParameters["PostContextText"] = postContextText
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/spellcheck"),
autorest.WithQueryParameters(queryParameters),
autorest.WithFormData(autorest.MapToValues(formDataParameters)),
autorest.WithHeader("X-BingApis-SDK", autorest.String(xBingApisSDK)))
if len(acceptLanguage) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
}
if len(pragma) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Pragma", autorest.String(pragma)))
}
if len(userAgent) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("User-Agent", autorest.String(userAgent)))
}
if len(clientID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
}
if len(clientIP) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
}
if len(location) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-Search-Location", autorest.String(location)))
}
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// SpellCheckerMethodSender sends the SpellCheckerMethod request. The method will close the
// http.Response Body if it receives an error.
func (client BaseClient) SpellCheckerMethodSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// SpellCheckerMethodResponder handles the response to the SpellCheckerMethod request. The method always
// closes the http.Response Body.
func (client BaseClient) SpellCheckerMethodResponder(resp *http.Response) (result SpellCheck, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,780 @@
package spellcheck
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"encoding/json"
"github.com/Azure/go-autorest/autorest"
)
// ActionType enumerates the values for action type.
type ActionType string
const (
// Edit ...
Edit ActionType = "Edit"
// Load ...
Load ActionType = "Load"
)
// ErrorCode enumerates the values for error code.
type ErrorCode string
const (
// InsufficientAuthorization ...
InsufficientAuthorization ErrorCode = "InsufficientAuthorization"
// InvalidAuthorization ...
InvalidAuthorization ErrorCode = "InvalidAuthorization"
// InvalidRequest ...
InvalidRequest ErrorCode = "InvalidRequest"
// None ...
None ErrorCode = "None"
// RateLimitExceeded ...
RateLimitExceeded ErrorCode = "RateLimitExceeded"
// ServerError ...
ServerError ErrorCode = "ServerError"
)
// ErrorSubCode enumerates the values for error sub code.
type ErrorSubCode string
const (
// AuthorizationDisabled ...
AuthorizationDisabled ErrorSubCode = "AuthorizationDisabled"
// AuthorizationExpired ...
AuthorizationExpired ErrorSubCode = "AuthorizationExpired"
// AuthorizationMissing ...
AuthorizationMissing ErrorSubCode = "AuthorizationMissing"
// AuthorizationRedundancy ...
AuthorizationRedundancy ErrorSubCode = "AuthorizationRedundancy"
// Blocked ...
Blocked ErrorSubCode = "Blocked"
// HTTPNotAllowed ...
HTTPNotAllowed ErrorSubCode = "HttpNotAllowed"
// NotImplemented ...
NotImplemented ErrorSubCode = "NotImplemented"
// ParameterInvalidValue ...
ParameterInvalidValue ErrorSubCode = "ParameterInvalidValue"
// ParameterMissing ...
ParameterMissing ErrorSubCode = "ParameterMissing"
// ResourceError ...
ResourceError ErrorSubCode = "ResourceError"
// UnexpectedError ...
UnexpectedError ErrorSubCode = "UnexpectedError"
)
// ErrorType enumerates the values for error type.
type ErrorType string
const (
// RepeatedToken ...
RepeatedToken ErrorType = "RepeatedToken"
// UnknownToken ...
UnknownToken ErrorType = "UnknownToken"
)
// Type enumerates the values for type.
type Type string
const (
// TypeAnswer ...
TypeAnswer Type = "Answer"
// TypeErrorResponse ...
TypeErrorResponse Type = "ErrorResponse"
// TypeIdentifiable ...
TypeIdentifiable Type = "Identifiable"
// TypeResponse ...
TypeResponse Type = "Response"
// TypeResponseBase ...
TypeResponseBase Type = "ResponseBase"
// TypeSpellCheck ...
TypeSpellCheck Type = "SpellCheck"
)
// BasicAnswer
type BasicAnswer interface {
AsSpellCheck() (*SpellCheck, bool)
AsAnswer() (*Answer, bool)
}
// Answer
type Answer struct {
// Type - Possible values include: 'TypeResponseBase', 'TypeSpellCheck', 'TypeAnswer', 'TypeResponse', 'TypeIdentifiable', 'TypeErrorResponse'
Type Type `json:"_type,omitempty"`
// ID - A String identifier.
ID *string `json:"id,omitempty"`
}
func unmarshalBasicAnswer(body []byte) (BasicAnswer, error) {
var m map[string]interface{}
err := json.Unmarshal(body, &m)
if err != nil {
return nil, err
}
switch m["_type"] {
case string(TypeSpellCheck):
var sc SpellCheck
err := json.Unmarshal(body, &sc)
return sc, err
default:
var a Answer
err := json.Unmarshal(body, &a)
return a, err
}
}
func unmarshalBasicAnswerArray(body []byte) ([]BasicAnswer, error) {
var rawMessages []*json.RawMessage
err := json.Unmarshal(body, &rawMessages)
if err != nil {
return nil, err
}
aArray := make([]BasicAnswer, len(rawMessages))
for index, rawMessage := range rawMessages {
a, err := unmarshalBasicAnswer(*rawMessage)
if err != nil {
return nil, err
}
aArray[index] = a
}
return aArray, nil
}
// MarshalJSON is the custom marshaler for Answer.
func (a Answer) MarshalJSON() ([]byte, error) {
a.Type = TypeAnswer
type Alias Answer
return json.Marshal(&struct {
Alias
}{
Alias: (Alias)(a),
})
}
// AsSpellCheck is the BasicResponseBase implementation for Answer.
func (a Answer) AsSpellCheck() (*SpellCheck, bool) {
return nil, false
}
// AsAnswer is the BasicResponseBase implementation for Answer.
func (a Answer) AsAnswer() (*Answer, bool) {
return &a, true
}
// AsBasicAnswer is the BasicResponseBase implementation for Answer.
func (a Answer) AsBasicAnswer() (BasicAnswer, bool) {
return &a, true
}
// AsResponse is the BasicResponseBase implementation for Answer.
func (a Answer) AsResponse() (*Response, bool) {
return nil, false
}
// AsBasicResponse is the BasicResponseBase implementation for Answer.
func (a Answer) AsBasicResponse() (BasicResponse, bool) {
return &a, true
}
// AsIdentifiable is the BasicResponseBase implementation for Answer.
func (a Answer) AsIdentifiable() (*Identifiable, bool) {
return nil, false
}
// AsBasicIdentifiable is the BasicResponseBase implementation for Answer.
func (a Answer) AsBasicIdentifiable() (BasicIdentifiable, bool) {
return &a, true
}
// AsErrorResponse is the BasicResponseBase implementation for Answer.
func (a Answer) AsErrorResponse() (*ErrorResponse, bool) {
return nil, false
}
// AsResponseBase is the BasicResponseBase implementation for Answer.
func (a Answer) AsResponseBase() (*ResponseBase, bool) {
return nil, false
}
// AsBasicResponseBase is the BasicResponseBase implementation for Answer.
func (a Answer) AsBasicResponseBase() (BasicResponseBase, bool) {
return &a, true
}
// Error defines the error that occurred.
type Error struct {
// Code - The error code that identifies the category of error. Possible values include: 'None', 'ServerError', 'InvalidRequest', 'RateLimitExceeded', 'InvalidAuthorization', 'InsufficientAuthorization'
Code ErrorCode `json:"code,omitempty"`
// SubCode - The error code that further helps to identify the error. Possible values include: 'UnexpectedError', 'ResourceError', 'NotImplemented', 'ParameterMissing', 'ParameterInvalidValue', 'HTTPNotAllowed', 'Blocked', 'AuthorizationMissing', 'AuthorizationRedundancy', 'AuthorizationDisabled', 'AuthorizationExpired'
SubCode ErrorSubCode `json:"subCode,omitempty"`
// Message - A description of the error.
Message *string `json:"message,omitempty"`
// MoreDetails - A description that provides additional information about the error.
MoreDetails *string `json:"moreDetails,omitempty"`
// Parameter - The parameter in the request that caused the error.
Parameter *string `json:"parameter,omitempty"`
// Value - The parameter's value in the request that was not valid.
Value *string `json:"value,omitempty"`
}
// ErrorResponse the top-level response that represents a failed request.
type ErrorResponse struct {
// Type - Possible values include: 'TypeResponseBase', 'TypeSpellCheck', 'TypeAnswer', 'TypeResponse', 'TypeIdentifiable', 'TypeErrorResponse'
Type Type `json:"_type,omitempty"`
// ID - A String identifier.
ID *string `json:"id,omitempty"`
// Errors - A list of errors that describe the reasons why the request failed.
Errors *[]Error `json:"errors,omitempty"`
}
// MarshalJSON is the custom marshaler for ErrorResponse.
func (er ErrorResponse) MarshalJSON() ([]byte, error) {
er.Type = TypeErrorResponse
type Alias ErrorResponse
return json.Marshal(&struct {
Alias
}{
Alias: (Alias)(er),
})
}
// AsSpellCheck is the BasicResponseBase implementation for ErrorResponse.
func (er ErrorResponse) AsSpellCheck() (*SpellCheck, bool) {
return nil, false
}
// AsAnswer is the BasicResponseBase implementation for ErrorResponse.
func (er ErrorResponse) AsAnswer() (*Answer, bool) {
return nil, false
}
// AsBasicAnswer is the BasicResponseBase implementation for ErrorResponse.
func (er ErrorResponse) AsBasicAnswer() (BasicAnswer, bool) {
return nil, false
}
// AsResponse is the BasicResponseBase implementation for ErrorResponse.
func (er ErrorResponse) AsResponse() (*Response, bool) {
return nil, false
}
// AsBasicResponse is the BasicResponseBase implementation for ErrorResponse.
func (er ErrorResponse) AsBasicResponse() (BasicResponse, bool) {
return &er, true
}
// AsIdentifiable is the BasicResponseBase implementation for ErrorResponse.
func (er ErrorResponse) AsIdentifiable() (*Identifiable, bool) {
return nil, false
}
// AsBasicIdentifiable is the BasicResponseBase implementation for ErrorResponse.
func (er ErrorResponse) AsBasicIdentifiable() (BasicIdentifiable, bool) {
return &er, true
}
// AsErrorResponse is the BasicResponseBase implementation for ErrorResponse.
func (er ErrorResponse) AsErrorResponse() (*ErrorResponse, bool) {
return &er, true
}
// AsResponseBase is the BasicResponseBase implementation for ErrorResponse.
func (er ErrorResponse) AsResponseBase() (*ResponseBase, bool) {
return nil, false
}
// AsBasicResponseBase is the BasicResponseBase implementation for ErrorResponse.
func (er ErrorResponse) AsBasicResponseBase() (BasicResponseBase, bool) {
return &er, true
}
// BasicIdentifiable defines the identity of a resource.
type BasicIdentifiable interface {
AsSpellCheck() (*SpellCheck, bool)
AsAnswer() (*Answer, bool)
AsBasicAnswer() (BasicAnswer, bool)
AsResponse() (*Response, bool)
AsBasicResponse() (BasicResponse, bool)
AsErrorResponse() (*ErrorResponse, bool)
AsIdentifiable() (*Identifiable, bool)
}
// Identifiable defines the identity of a resource.
type Identifiable struct {
// Type - Possible values include: 'TypeResponseBase', 'TypeSpellCheck', 'TypeAnswer', 'TypeResponse', 'TypeIdentifiable', 'TypeErrorResponse'
Type Type `json:"_type,omitempty"`
// ID - A String identifier.
ID *string `json:"id,omitempty"`
}
func unmarshalBasicIdentifiable(body []byte) (BasicIdentifiable, error) {
var m map[string]interface{}
err := json.Unmarshal(body, &m)
if err != nil {
return nil, err
}
switch m["_type"] {
case string(TypeSpellCheck):
var sc SpellCheck
err := json.Unmarshal(body, &sc)
return sc, err
case string(TypeAnswer):
var a Answer
err := json.Unmarshal(body, &a)
return a, err
case string(TypeResponse):
var r Response
err := json.Unmarshal(body, &r)
return r, err
case string(TypeErrorResponse):
var er ErrorResponse
err := json.Unmarshal(body, &er)
return er, err
default:
var i Identifiable
err := json.Unmarshal(body, &i)
return i, err
}
}
func unmarshalBasicIdentifiableArray(body []byte) ([]BasicIdentifiable, error) {
var rawMessages []*json.RawMessage
err := json.Unmarshal(body, &rawMessages)
if err != nil {
return nil, err
}
iArray := make([]BasicIdentifiable, len(rawMessages))
for index, rawMessage := range rawMessages {
i, err := unmarshalBasicIdentifiable(*rawMessage)
if err != nil {
return nil, err
}
iArray[index] = i
}
return iArray, nil
}
// MarshalJSON is the custom marshaler for Identifiable.
func (i Identifiable) MarshalJSON() ([]byte, error) {
i.Type = TypeIdentifiable
type Alias Identifiable
return json.Marshal(&struct {
Alias
}{
Alias: (Alias)(i),
})
}
// AsSpellCheck is the BasicResponseBase implementation for Identifiable.
func (i Identifiable) AsSpellCheck() (*SpellCheck, bool) {
return nil, false
}
// AsAnswer is the BasicResponseBase implementation for Identifiable.
func (i Identifiable) AsAnswer() (*Answer, bool) {
return nil, false
}
// AsBasicAnswer is the BasicResponseBase implementation for Identifiable.
func (i Identifiable) AsBasicAnswer() (BasicAnswer, bool) {
return nil, false
}
// AsResponse is the BasicResponseBase implementation for Identifiable.
func (i Identifiable) AsResponse() (*Response, bool) {
return nil, false
}
// AsBasicResponse is the BasicResponseBase implementation for Identifiable.
func (i Identifiable) AsBasicResponse() (BasicResponse, bool) {
return nil, false
}
// AsIdentifiable is the BasicResponseBase implementation for Identifiable.
func (i Identifiable) AsIdentifiable() (*Identifiable, bool) {
return &i, true
}
// AsBasicIdentifiable is the BasicResponseBase implementation for Identifiable.
func (i Identifiable) AsBasicIdentifiable() (BasicIdentifiable, bool) {
return &i, true
}
// AsErrorResponse is the BasicResponseBase implementation for Identifiable.
func (i Identifiable) AsErrorResponse() (*ErrorResponse, bool) {
return nil, false
}
// AsResponseBase is the BasicResponseBase implementation for Identifiable.
func (i Identifiable) AsResponseBase() (*ResponseBase, bool) {
return nil, false
}
// AsBasicResponseBase is the BasicResponseBase implementation for Identifiable.
func (i Identifiable) AsBasicResponseBase() (BasicResponseBase, bool) {
return &i, true
}
// BasicResponse defines a response. All schemas that could be returned at the root of a response should inherit from
// this
type BasicResponse interface {
AsSpellCheck() (*SpellCheck, bool)
AsAnswer() (*Answer, bool)
AsBasicAnswer() (BasicAnswer, bool)
AsErrorResponse() (*ErrorResponse, bool)
AsResponse() (*Response, bool)
}
// Response defines a response. All schemas that could be returned at the root of a response should inherit from this
type Response struct {
// Type - Possible values include: 'TypeResponseBase', 'TypeSpellCheck', 'TypeAnswer', 'TypeResponse', 'TypeIdentifiable', 'TypeErrorResponse'
Type Type `json:"_type,omitempty"`
// ID - A String identifier.
ID *string `json:"id,omitempty"`
}
func unmarshalBasicResponse(body []byte) (BasicResponse, error) {
var m map[string]interface{}
err := json.Unmarshal(body, &m)
if err != nil {
return nil, err
}
switch m["_type"] {
case string(TypeSpellCheck):
var sc SpellCheck
err := json.Unmarshal(body, &sc)
return sc, err
case string(TypeAnswer):
var a Answer
err := json.Unmarshal(body, &a)
return a, err
case string(TypeErrorResponse):
var er ErrorResponse
err := json.Unmarshal(body, &er)
return er, err
default:
var r Response
err := json.Unmarshal(body, &r)
return r, err
}
}
func unmarshalBasicResponseArray(body []byte) ([]BasicResponse, error) {
var rawMessages []*json.RawMessage
err := json.Unmarshal(body, &rawMessages)
if err != nil {
return nil, err
}
rArray := make([]BasicResponse, len(rawMessages))
for index, rawMessage := range rawMessages {
r, err := unmarshalBasicResponse(*rawMessage)
if err != nil {
return nil, err
}
rArray[index] = r
}
return rArray, nil
}
// MarshalJSON is the custom marshaler for Response.
func (r Response) MarshalJSON() ([]byte, error) {
r.Type = TypeResponse
type Alias Response
return json.Marshal(&struct {
Alias
}{
Alias: (Alias)(r),
})
}
// AsSpellCheck is the BasicResponseBase implementation for Response.
func (r Response) AsSpellCheck() (*SpellCheck, bool) {
return nil, false
}
// AsAnswer is the BasicResponseBase implementation for Response.
func (r Response) AsAnswer() (*Answer, bool) {
return nil, false
}
// AsBasicAnswer is the BasicResponseBase implementation for Response.
func (r Response) AsBasicAnswer() (BasicAnswer, bool) {
return nil, false
}
// AsResponse is the BasicResponseBase implementation for Response.
func (r Response) AsResponse() (*Response, bool) {
return &r, true
}
// AsBasicResponse is the BasicResponseBase implementation for Response.
func (r Response) AsBasicResponse() (BasicResponse, bool) {
return &r, true
}
// AsIdentifiable is the BasicResponseBase implementation for Response.
func (r Response) AsIdentifiable() (*Identifiable, bool) {
return nil, false
}
// AsBasicIdentifiable is the BasicResponseBase implementation for Response.
func (r Response) AsBasicIdentifiable() (BasicIdentifiable, bool) {
return &r, true
}
// AsErrorResponse is the BasicResponseBase implementation for Response.
func (r Response) AsErrorResponse() (*ErrorResponse, bool) {
return nil, false
}
// AsResponseBase is the BasicResponseBase implementation for Response.
func (r Response) AsResponseBase() (*ResponseBase, bool) {
return nil, false
}
// AsBasicResponseBase is the BasicResponseBase implementation for Response.
func (r Response) AsBasicResponseBase() (BasicResponseBase, bool) {
return &r, true
}
// BasicResponseBase
type BasicResponseBase interface {
AsSpellCheck() (*SpellCheck, bool)
AsAnswer() (*Answer, bool)
AsBasicAnswer() (BasicAnswer, bool)
AsResponse() (*Response, bool)
AsBasicResponse() (BasicResponse, bool)
AsIdentifiable() (*Identifiable, bool)
AsBasicIdentifiable() (BasicIdentifiable, bool)
AsErrorResponse() (*ErrorResponse, bool)
AsResponseBase() (*ResponseBase, bool)
}
// ResponseBase
type ResponseBase struct {
// Type - Possible values include: 'TypeResponseBase', 'TypeSpellCheck', 'TypeAnswer', 'TypeResponse', 'TypeIdentifiable', 'TypeErrorResponse'
Type Type `json:"_type,omitempty"`
}
func unmarshalBasicResponseBase(body []byte) (BasicResponseBase, error) {
var m map[string]interface{}
err := json.Unmarshal(body, &m)
if err != nil {
return nil, err
}
switch m["_type"] {
case string(TypeSpellCheck):
var sc SpellCheck
err := json.Unmarshal(body, &sc)
return sc, err
case string(TypeAnswer):
var a Answer
err := json.Unmarshal(body, &a)
return a, err
case string(TypeResponse):
var r Response
err := json.Unmarshal(body, &r)
return r, err
case string(TypeIdentifiable):
var i Identifiable
err := json.Unmarshal(body, &i)
return i, err
case string(TypeErrorResponse):
var er ErrorResponse
err := json.Unmarshal(body, &er)
return er, err
default:
var rb ResponseBase
err := json.Unmarshal(body, &rb)
return rb, err
}
}
func unmarshalBasicResponseBaseArray(body []byte) ([]BasicResponseBase, error) {
var rawMessages []*json.RawMessage
err := json.Unmarshal(body, &rawMessages)
if err != nil {
return nil, err
}
rbArray := make([]BasicResponseBase, len(rawMessages))
for index, rawMessage := range rawMessages {
rb, err := unmarshalBasicResponseBase(*rawMessage)
if err != nil {
return nil, err
}
rbArray[index] = rb
}
return rbArray, nil
}
// MarshalJSON is the custom marshaler for ResponseBase.
func (rb ResponseBase) MarshalJSON() ([]byte, error) {
rb.Type = TypeResponseBase
type Alias ResponseBase
return json.Marshal(&struct {
Alias
}{
Alias: (Alias)(rb),
})
}
// AsSpellCheck is the BasicResponseBase implementation for ResponseBase.
func (rb ResponseBase) AsSpellCheck() (*SpellCheck, bool) {
return nil, false
}
// AsAnswer is the BasicResponseBase implementation for ResponseBase.
func (rb ResponseBase) AsAnswer() (*Answer, bool) {
return nil, false
}
// AsBasicAnswer is the BasicResponseBase implementation for ResponseBase.
func (rb ResponseBase) AsBasicAnswer() (BasicAnswer, bool) {
return nil, false
}
// AsResponse is the BasicResponseBase implementation for ResponseBase.
func (rb ResponseBase) AsResponse() (*Response, bool) {
return nil, false
}
// AsBasicResponse is the BasicResponseBase implementation for ResponseBase.
func (rb ResponseBase) AsBasicResponse() (BasicResponse, bool) {
return nil, false
}
// AsIdentifiable is the BasicResponseBase implementation for ResponseBase.
func (rb ResponseBase) AsIdentifiable() (*Identifiable, bool) {
return nil, false
}
// AsBasicIdentifiable is the BasicResponseBase implementation for ResponseBase.
func (rb ResponseBase) AsBasicIdentifiable() (BasicIdentifiable, bool) {
return nil, false
}
// AsErrorResponse is the BasicResponseBase implementation for ResponseBase.
func (rb ResponseBase) AsErrorResponse() (*ErrorResponse, bool) {
return nil, false
}
// AsResponseBase is the BasicResponseBase implementation for ResponseBase.
func (rb ResponseBase) AsResponseBase() (*ResponseBase, bool) {
return &rb, true
}
// AsBasicResponseBase is the BasicResponseBase implementation for ResponseBase.
func (rb ResponseBase) AsBasicResponseBase() (BasicResponseBase, bool) {
return &rb, true
}
// SpellCheck ...
type SpellCheck struct {
autorest.Response `json:"-"`
// Type - Possible values include: 'TypeResponseBase', 'TypeSpellCheck', 'TypeAnswer', 'TypeResponse', 'TypeIdentifiable', 'TypeErrorResponse'
Type Type `json:"_type,omitempty"`
// ID - A String identifier.
ID *string `json:"id,omitempty"`
FlaggedTokens *[]SpellingFlaggedToken `json:"flaggedTokens,omitempty"`
}
// MarshalJSON is the custom marshaler for SpellCheck.
func (sc SpellCheck) MarshalJSON() ([]byte, error) {
sc.Type = TypeSpellCheck
type Alias SpellCheck
return json.Marshal(&struct {
Alias
}{
Alias: (Alias)(sc),
})
}
// AsSpellCheck is the BasicResponseBase implementation for SpellCheck.
func (sc SpellCheck) AsSpellCheck() (*SpellCheck, bool) {
return &sc, true
}
// AsAnswer is the BasicResponseBase implementation for SpellCheck.
func (sc SpellCheck) AsAnswer() (*Answer, bool) {
return nil, false
}
// AsBasicAnswer is the BasicResponseBase implementation for SpellCheck.
func (sc SpellCheck) AsBasicAnswer() (BasicAnswer, bool) {
return &sc, true
}
// AsResponse is the BasicResponseBase implementation for SpellCheck.
func (sc SpellCheck) AsResponse() (*Response, bool) {
return nil, false
}
// AsBasicResponse is the BasicResponseBase implementation for SpellCheck.
func (sc SpellCheck) AsBasicResponse() (BasicResponse, bool) {
return &sc, true
}
// AsIdentifiable is the BasicResponseBase implementation for SpellCheck.
func (sc SpellCheck) AsIdentifiable() (*Identifiable, bool) {
return nil, false
}
// AsBasicIdentifiable is the BasicResponseBase implementation for SpellCheck.
func (sc SpellCheck) AsBasicIdentifiable() (BasicIdentifiable, bool) {
return &sc, true
}
// AsErrorResponse is the BasicResponseBase implementation for SpellCheck.
func (sc SpellCheck) AsErrorResponse() (*ErrorResponse, bool) {
return nil, false
}
// AsResponseBase is the BasicResponseBase implementation for SpellCheck.
func (sc SpellCheck) AsResponseBase() (*ResponseBase, bool) {
return nil, false
}
// AsBasicResponseBase is the BasicResponseBase implementation for SpellCheck.
func (sc SpellCheck) AsBasicResponseBase() (BasicResponseBase, bool) {
return &sc, true
}
// SpellingFlaggedToken ...
type SpellingFlaggedToken struct {
Offset *int32 `json:"offset,omitempty"`
Token *string `json:"token,omitempty"`
// Type - Possible values include: 'UnknownToken', 'RepeatedToken'
Type ErrorType `json:"type,omitempty"`
Suggestions *[]SpellingTokenSuggestion `json:"suggestions,omitempty"`
PingURLSuffix *string `json:"pingUrlSuffix,omitempty"`
}
// SpellingTokenSuggestion ...
type SpellingTokenSuggestion struct {
Suggestion *string `json:"suggestion,omitempty"`
Score *float64 `json:"score,omitempty"`
PingURLSuffix *string `json:"pingUrlSuffix,omitempty"`
}
@@ -0,0 +1,28 @@
package spellcheck
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/v12.2.0-beta services"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v12.2.0-beta"
}
@@ -0,0 +1,53 @@
// Package videosearch implements the Azure ARM Videosearch service API version 1.0.
//
// The Video Search API lets you search on Bing for video that are relevant to the user's search query, for insights
// about a video or for videos that are trending based on search requests made by others. This section provides
// technical details about the query parameters and headers that you use to request videos and the JSON response
// objects that contain them. For examples that show how to make requests, see [Searching the Web for
// Videos](https://docs.microsoft.com/azure/cognitive-services/bing-video-search/search-the-web).
package videosearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
const (
// DefaultBaseURI is the default URI used for the service Videosearch
DefaultBaseURI = "https://api.cognitive.microsoft.com/bing/v7.0"
)
// BaseClient is the base client for Videosearch.
type BaseClient struct {
autorest.Client
BaseURI string
}
// New creates an instance of the BaseClient client.
func New() BaseClient {
return NewWithBaseURI(DefaultBaseURI)
}
// NewWithBaseURI creates an instance of the BaseClient client.
func NewWithBaseURI(baseURI string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,28 @@
package videosearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/v12.2.0-beta services"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v12.2.0-beta"
}
@@ -0,0 +1,771 @@
package videosearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// VideosClient is the the Video Search API lets you search on Bing for video that are relevant to the user's search
// query, for insights about a video or for videos that are trending based on search requests made by others. This
// section provides technical details about the query parameters and headers that you use to request videos and the
// JSON response objects that contain them. For examples that show how to make requests, see [Searching the Web for
// Videos](https://docs.microsoft.com/azure/cognitive-services/bing-video-search/search-the-web).
type VideosClient struct {
BaseClient
}
// NewVideosClient creates an instance of the VideosClient client.
func NewVideosClient() VideosClient {
return NewVideosClientWithBaseURI(DefaultBaseURI)
}
// NewVideosClientWithBaseURI creates an instance of the VideosClient client.
func NewVideosClientWithBaseURI(baseURI string) VideosClient {
return VideosClient{NewWithBaseURI(baseURI)}
}
// Details sends the details request.
//
// xBingApisSDK is activate swagger compliance query is the user's search query string. The query string cannot be
// empty. The query string may contain [Bing Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For
// example, to limit videos to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx)
// operator. Use this parameter only with the Video Search API. Do not specify this parameter when calling the Trending
// Videos API. acceptLanguage is a comma-delimited list of one or more languages to use for user interface strings. The
// list is in decreasing order of preference. For additional information, including expected format, see
// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#setlang) query
// parameter are mutually exclusive; do not specify both. If you set this header, you must also specify the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#cc) query parameter. To
// determine the market to return results for, Bing uses the first supported language it finds from the list and
// combines it with the cc parameter value. If the list does not include a supported language, Bing finds the closest
// language and market that supports the request or it uses an aggregated or default market for the results. To
// determine the market that Bing used, see the BingAPIs-Market header. Use this header and the cc query parameter only
// if you specify multiple languages. Otherwise, use the
// [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#mkt) and
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#setlang) query
// parameters. A user interface string is a string that's used as a label in a user interface. There are few user
// interface strings in the JSON response objects. Any links to Bing.com properties in the response objects apply the
// specified language. userAgent is the user agent originating the request. Bing uses the user agent to provide mobile
// users with an optimized experience. Although optional, you are encouraged to always specify this header. The
// user-agent should be the same string that any commonly used browser sends. For information about user agents, see
// [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The following are examples of user-agent
// strings. Windows Phone: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM;
// Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build / GINGERBREAD)
// AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU
// iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142 iPhone4; 1 BingWeb /
// 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad:
// Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML, like Gecko) Version / 7.0 Mobile /
// 11A465 Safari / 9537.53 clientID is bing uses this header to provide users with consistent behavior across Bing API
// calls. Bing often flights new features and improvements, and it uses the client ID as a key for assigning traffic on
// different flights. If you do not use the same client ID for a user across multiple requests, then Bing may assign
// the user to multiple conflicting flights. Being assigned to multiple conflicting flights can lead to an inconsistent
// user experience. For example, if the second request has a different flight assignment than the first, the experience
// may be unexpected. Also, Bing can use the client ID to tailor web results to that client ID’s search history,
// providing a richer experience for the user. Bing also uses this header to help improve result rankings by analyzing
// the activity generated by a client ID. The relevance improvements help with better quality of results delivered by
// Bing APIs and in turn enables higher click-through rates for the API consumer. IMPORTANT: Although optional, you
// should consider this header required. Persisting the client ID across multiple requests for the same end user and
// device combination enables 1) the API consumer to receive a consistent user experience, and 2) higher click-through
// rates via better quality of results from the Bing APIs. Each user that uses your application on the device must have
// a unique, Bing generated client ID. If you do not include this header in the request, Bing generates an ID and
// returns it in the X-MSEdge-ClientID response header. The only time that you should NOT include this header in a
// request is the first time the user uses your app on that device. Use the client ID for each Bing API request that
// your app makes for this user on the device. Persist the client ID. To persist the ID in a browser app, use a
// persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session cookie. For other apps
// such as mobile apps, use the device's persistent storage to persist the ID. The next time the user uses your app on
// that device, get the client ID that you persisted. Bing responses may or may not include this header. If the
// response includes this header, capture the client ID and use it for all subsequent Bing requests for the user on
// that device. If you include the X-MSEdge-ClientID, you must not include cookies in the request. clientIP is the IPv4
// or IPv6 address of the client device. The IP address is used to discover the user's location. Bing uses the location
// information to determine safe search behavior. Although optional, you are encouraged to always specify this header
// and the X-Search-Location header. Do not obfuscate the address (for example, by changing the last octet to 0).
// Obfuscating the address results in the location not being anywhere near the device's actual location, which may
// result in Bing serving erroneous results. location is a semicolon-delimited list of key/value pairs that describe
// the client's geographical location. Bing uses the location information to determine safe search behavior and to
// return relevant local content. Specify the key/value pair as <key>:<value>. The following are the keys that you use
// to specify the user's location. lat (required): The latitude of the client's location, in degrees. The latitude must
// be greater than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and
// positive values indicate northern latitudes. long (required): The longitude of the client's location, in degrees.
// The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative values indicate
// western longitudes and positive values indicate eastern longitudes. re (required): The radius, in meters, which
// specifies the horizontal accuracy of the coordinates. Pass the value returned by the device's location service.
// Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts
// (optional): The UTC UNIX timestamp of when the client was at the location. (The UNIX timestamp is the number of
// seconds since January 1, 1970.) head (optional): The client's relative heading or direction of travel. Specify the
// direction of travel as degrees from 0 through 360, counting clockwise relative to true north. Specify this key only
// if the sp key is nonzero. sp (optional): The horizontal velocity (speed), in meters per second, that the client
// device is traveling. alt (optional): The altitude of the client device, in meters. are (optional): The radius, in
// meters, that specifies the vertical accuracy of the coordinates. Specify this key only if you specify the alt key.
// Although many of the keys are optional, the more information that you provide, the more accurate the location
// results are. Although optional, you are encouraged to always specify the user's geographical location. Providing the
// location is especially important if the client's IP address does not accurately reflect the user's physical location
// (for example, if the client uses VPN). For optimal results, you should include this header and the X-MSEdge-ClientIP
// header, but at a minimum, you should include this header. countryCode is a 2-character country code of the country
// where the results come from. This API supports only the United States market. If you specify this query parameter,
// it must be set to us. If you set this parameter, you must also specify the Accept-Language header. Bing uses the
// first supported language it finds from the languages list, and combine that language with the country code that you
// specify to determine the market to return results for. If the languages list does not include a supported language,
// Bing finds the closest language and market that supports the request, or it may use an aggregated or default market
// for the results instead of a specified one. You should use this query parameter and the Accept-Language query
// parameter only if you specify multiple languages; otherwise, you should use the mkt and setLang query parameters.
// This parameter and the mkt query parameter are mutually exclusive—do not specify both. ID is an ID that uniquely
// identifies a video. The
// [Video](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#video) object's
// videoId field contains the ID that you set this parameter to. You use this parameter to identify the video to get
// insights of. modules is a comma-delimited list of insights to request. The following are the possible
// case-insensitive values. All: Return all available insights. RelatedVideos: Return a list of videos that are similar
// to the video specified by the id query parameter. VideoResult: Return the video that you're requesting insights of
// (this is the video that you set the id query parameter to in your insights request). If you specify an insight and
// there is no data for it, the response object does not include the related field. For example, if you specify
// RelatedVideos and none exist, the response does not include the relatedVideos field. Although the user's query term
// is not required, you should always include it because it helps to improve relevance and the results. market is the
// market where the results come from. Typically, mkt is the country where the user is making the request from.
// However, it could be a different country if the user is not located in a country where Bing delivers results. The
// market must be in the form <language code>-<country code>. For example, en-US. The string is case insensitive. For a
// list of possible market values, see [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#market-codes). NOTE:
// If known, you are encouraged to always specify the market. Specifying the market helps Bing route the request and
// return an appropriate and optimal response. If you specify a market that is not listed in [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#market-codes), Bing
// uses a best fit market code based on an internal mapping that is subject to change. This parameter and the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#cc) query parameter are
// mutually exclusive—do not specify both. resolution is filter videos by the following resolutions: SD480p: Return
// videos with a 480p or higher resolution. HD720p: Return videos with a 720p or higher resolution. HD1080p: Return
// videos with a 1080p or higher resolution. All: Do not filter by resolution.Specifying this value is the same as not
// specifying the resolution parameter. safeSearch is filter videos for adult content. The following are the possible
// filter values. Off: If the request is through the Video Search API, the response includes adult videos and the
// thumbnail images of the videos are clear (non-fuzzy). If the request is through the Web Search API, the response
// includes adult videos but the thumbnail images of the videos are pixelated (fuzzy). Moderate: If the request is
// through the Video Search API, the response does not include videos with adult content. If the request is through the
// Web Search API, the response may include videos with adult content but the thumbnail images of the videos are
// pixelated (fuzzy). Strict: Does not return videos with adult content. The default is Moderate. If the request comes
// from a market that Bing's adult policy requires that safeSearch is set to Strict, Bing ignores the safeSearch value
// and uses Strict. If you use the site: query operator, there is the chance that the response may contain adult
// content regardless of what the safeSearch query parameter is set to. Use site: only if you are aware of the content
// on the site and your scenario supports the possibility of adult content. setLang is the language to use for user
// interface strings. Specify the language using the ISO 639-1 2-letter language code. For example, the language code
// for English is EN. The default is EN (English). Although optional, you should always specify the language.
// Typically, you set setLang to the same language specified by mkt unless the user wants the user interface strings
// displayed in a different language. This parameter and the
// [Accept-Language](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#acceptlanguage)
// header are mutually exclusive; do not specify both. A user interface string is a string that's used as a label in a
// user interface. There are few user interface strings in the JSON response objects. Also, any links to Bing.com
// properties in the response objects apply the specified language. textDecorations is a Boolean value that determines
// whether display strings contain decoration markers such as hit highlighting characters. If true, the strings may
// include markers. The default is false. To specify whether to use Unicode characters or HTML tags as the markers, see
// the [textFormat](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#textformat)
// query parameter. For information about hit highlighting, see [Hit
// Highlighting](https://docs.microsoft.com/azure/cognitive-services/bing-news-search/hit-highlighting). textFormat is
// the type of markers to use for text decorations (see the textDecorations query parameter). Possible values are
// Raw—Use Unicode characters to mark content that needs special formatting. The Unicode characters are in the range
// E000 through E019. For example, Bing uses E000 and E001 to mark the beginning and end of query terms for hit
// highlighting. HTML—Use HTML tags to mark content that needs special formatting. For example, use <b> tags to
// highlight query terms in display strings. The default is Raw. For display strings that contain escapable HTML
// characters such as <, >, and &, if textFormat is set to HTML, Bing escapes the characters as appropriate (for
// example, < is escaped to &lt;).
func (client VideosClient) Details(ctx context.Context, xBingApisSDK string, query string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, countryCode string, ID string, modules []VideoInsightModule, market string, resolution VideoResolution, safeSearch SafeSearch, setLang string, textDecorations *bool, textFormat TextFormat) (result VideoDetails, err error) {
req, err := client.DetailsPreparer(ctx, xBingApisSDK, query, acceptLanguage, userAgent, clientID, clientIP, location, countryCode, ID, modules, market, resolution, safeSearch, setLang, textDecorations, textFormat)
if err != nil {
err = autorest.NewErrorWithError(err, "videosearch.VideosClient", "Details", nil, "Failure preparing request")
return
}
resp, err := client.DetailsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "videosearch.VideosClient", "Details", resp, "Failure sending request")
return
}
result, err = client.DetailsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "videosearch.VideosClient", "Details", resp, "Failure responding to request")
}
return
}
// DetailsPreparer prepares the Details request.
func (client VideosClient) DetailsPreparer(ctx context.Context, xBingApisSDK string, query string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, countryCode string, ID string, modules []VideoInsightModule, market string, resolution VideoResolution, safeSearch SafeSearch, setLang string, textDecorations *bool, textFormat TextFormat) (*http.Request, error) {
queryParameters := map[string]interface{}{
"q": autorest.Encode("query", query),
}
if len(countryCode) > 0 {
queryParameters["cc"] = autorest.Encode("query", countryCode)
}
if len(ID) > 0 {
queryParameters["id"] = autorest.Encode("query", ID)
}
if modules != nil && len(modules) > 0 {
queryParameters["modules"] = autorest.Encode("query", modules, ",")
}
if len(market) > 0 {
queryParameters["mkt"] = autorest.Encode("query", market)
}
if len(string(resolution)) > 0 {
queryParameters["resolution"] = autorest.Encode("query", resolution)
}
if len(string(safeSearch)) > 0 {
queryParameters["safeSearch"] = autorest.Encode("query", safeSearch)
}
if len(setLang) > 0 {
queryParameters["setLang"] = autorest.Encode("query", setLang)
}
if textDecorations != nil {
queryParameters["textDecorations"] = autorest.Encode("query", *textDecorations)
}
if len(string(textFormat)) > 0 {
queryParameters["textFormat"] = autorest.Encode("query", textFormat)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/videos/details"),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("X-BingApis-SDK", autorest.String(xBingApisSDK)))
if len(acceptLanguage) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
}
if len(userAgent) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("User-Agent", autorest.String(userAgent)))
}
if len(clientID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
}
if len(clientIP) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
}
if len(location) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-Search-Location", autorest.String(location)))
}
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DetailsSender sends the Details request. The method will close the
// http.Response Body if it receives an error.
func (client VideosClient) DetailsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DetailsResponder handles the response to the Details request. The method always
// closes the http.Response Body.
func (client VideosClient) DetailsResponder(resp *http.Response) (result VideoDetails, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Search sends the search request.
//
// xBingApisSDK is activate swagger compliance query is the user's search query string. The query string cannot be
// empty. The query string may contain [Bing Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For
// example, to limit videos to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx)
// operator. Use this parameter only with the Video Search API. Do not specify this parameter when calling the Trending
// Videos API. acceptLanguage is a comma-delimited list of one or more languages to use for user interface strings. The
// list is in decreasing order of preference. For additional information, including expected format, see
// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#setlang) query
// parameter are mutually exclusive; do not specify both. If you set this header, you must also specify the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#cc) query parameter. To
// determine the market to return results for, Bing uses the first supported language it finds from the list and
// combines it with the cc parameter value. If the list does not include a supported language, Bing finds the closest
// language and market that supports the request or it uses an aggregated or default market for the results. To
// determine the market that Bing used, see the BingAPIs-Market header. Use this header and the cc query parameter only
// if you specify multiple languages. Otherwise, use the
// [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#mkt) and
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#setlang) query
// parameters. A user interface string is a string that's used as a label in a user interface. There are few user
// interface strings in the JSON response objects. Any links to Bing.com properties in the response objects apply the
// specified language. userAgent is the user agent originating the request. Bing uses the user agent to provide mobile
// users with an optimized experience. Although optional, you are encouraged to always specify this header. The
// user-agent should be the same string that any commonly used browser sends. For information about user agents, see
// [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The following are examples of user-agent
// strings. Windows Phone: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM;
// Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build / GINGERBREAD)
// AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU
// iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142 iPhone4; 1 BingWeb /
// 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad:
// Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML, like Gecko) Version / 7.0 Mobile /
// 11A465 Safari / 9537.53 clientID is bing uses this header to provide users with consistent behavior across Bing API
// calls. Bing often flights new features and improvements, and it uses the client ID as a key for assigning traffic on
// different flights. If you do not use the same client ID for a user across multiple requests, then Bing may assign
// the user to multiple conflicting flights. Being assigned to multiple conflicting flights can lead to an inconsistent
// user experience. For example, if the second request has a different flight assignment than the first, the experience
// may be unexpected. Also, Bing can use the client ID to tailor web results to that client ID’s search history,
// providing a richer experience for the user. Bing also uses this header to help improve result rankings by analyzing
// the activity generated by a client ID. The relevance improvements help with better quality of results delivered by
// Bing APIs and in turn enables higher click-through rates for the API consumer. IMPORTANT: Although optional, you
// should consider this header required. Persisting the client ID across multiple requests for the same end user and
// device combination enables 1) the API consumer to receive a consistent user experience, and 2) higher click-through
// rates via better quality of results from the Bing APIs. Each user that uses your application on the device must have
// a unique, Bing generated client ID. If you do not include this header in the request, Bing generates an ID and
// returns it in the X-MSEdge-ClientID response header. The only time that you should NOT include this header in a
// request is the first time the user uses your app on that device. Use the client ID for each Bing API request that
// your app makes for this user on the device. Persist the client ID. To persist the ID in a browser app, use a
// persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session cookie. For other apps
// such as mobile apps, use the device's persistent storage to persist the ID. The next time the user uses your app on
// that device, get the client ID that you persisted. Bing responses may or may not include this header. If the
// response includes this header, capture the client ID and use it for all subsequent Bing requests for the user on
// that device. If you include the X-MSEdge-ClientID, you must not include cookies in the request. clientIP is the IPv4
// or IPv6 address of the client device. The IP address is used to discover the user's location. Bing uses the location
// information to determine safe search behavior. Although optional, you are encouraged to always specify this header
// and the X-Search-Location header. Do not obfuscate the address (for example, by changing the last octet to 0).
// Obfuscating the address results in the location not being anywhere near the device's actual location, which may
// result in Bing serving erroneous results. location is a semicolon-delimited list of key/value pairs that describe
// the client's geographical location. Bing uses the location information to determine safe search behavior and to
// return relevant local content. Specify the key/value pair as <key>:<value>. The following are the keys that you use
// to specify the user's location. lat (required): The latitude of the client's location, in degrees. The latitude must
// be greater than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and
// positive values indicate northern latitudes. long (required): The longitude of the client's location, in degrees.
// The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative values indicate
// western longitudes and positive values indicate eastern longitudes. re (required): The radius, in meters, which
// specifies the horizontal accuracy of the coordinates. Pass the value returned by the device's location service.
// Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts
// (optional): The UTC UNIX timestamp of when the client was at the location. (The UNIX timestamp is the number of
// seconds since January 1, 1970.) head (optional): The client's relative heading or direction of travel. Specify the
// direction of travel as degrees from 0 through 360, counting clockwise relative to true north. Specify this key only
// if the sp key is nonzero. sp (optional): The horizontal velocity (speed), in meters per second, that the client
// device is traveling. alt (optional): The altitude of the client device, in meters. are (optional): The radius, in
// meters, that specifies the vertical accuracy of the coordinates. Specify this key only if you specify the alt key.
// Although many of the keys are optional, the more information that you provide, the more accurate the location
// results are. Although optional, you are encouraged to always specify the user's geographical location. Providing the
// location is especially important if the client's IP address does not accurately reflect the user's physical location
// (for example, if the client uses VPN). For optimal results, you should include this header and the X-MSEdge-ClientIP
// header, but at a minimum, you should include this header. countryCode is a 2-character country code of the country
// where the results come from. This API supports only the United States market. If you specify this query parameter,
// it must be set to us. If you set this parameter, you must also specify the Accept-Language header. Bing uses the
// first supported language it finds from the languages list, and combine that language with the country code that you
// specify to determine the market to return results for. If the languages list does not include a supported language,
// Bing finds the closest language and market that supports the request, or it may use an aggregated or default market
// for the results instead of a specified one. You should use this query parameter and the Accept-Language query
// parameter only if you specify multiple languages; otherwise, you should use the mkt and setLang query parameters.
// This parameter and the mkt query parameter are mutually exclusive—do not specify both. count is the number of videos
// to return in the response. The actual number delivered may be less than requested. The default is 35. The maximum is
// 105. You may use this parameter along with the offset parameter to page results. For example, if your user interface
// presents 20 videos per page, set count to 20 and offset to 0 to get the first page of results. For each subsequent
// page, increment offset by 20 (for example, 0, 20, 40). Use this parameter only with the Video Search API. Do not
// specify this parameter when calling the Trending Videos API or the Web Search API. freshness is filter videos by the
// date and time that Bing discovered the video. The following are the possible filter values. Day: Return videos
// discovered within the last 24 hours. Week: Return videos discovered within the last 7 days. Month: Return videos
// discovered within the last 30 days. ID is an ID that uniquely identifies a video. The
// [Video](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#video) object's
// videoId field contains the ID that you set this parameter to. You use this parameter to ensure that the specified
// video is the first video in the list of videos that Bing returns. length is filter videos by the following lengths:
// Short: Return videos that are less than 5 minutes. Medium: Return videos that are between 5 and 20 minutes,
// inclusive. Long: Return videos that are longer than 20 minutes. All: Do not filter by length.Specifying this value
// is the same as not specifying the videoLength parameter. market is the market where the results come from.
// Typically, mkt is the country where the user is making the request from. However, it could be a different country if
// the user is not located in a country where Bing delivers results. The market must be in the form <language
// code>-<country code>. For example, en-US. The string is case insensitive. For a list of possible market values, see
// [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#market-codes). NOTE:
// If known, you are encouraged to always specify the market. Specifying the market helps Bing route the request and
// return an appropriate and optimal response. If you specify a market that is not listed in [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#market-codes), Bing
// uses a best fit market code based on an internal mapping that is subject to change. This parameter and the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#cc) query parameter are
// mutually exclusive—do not specify both. offset is the zero-based offset that indicates the number of videos to skip
// before returning videos. The default is 0. The offset should be less than
// ([totalEstimatedMatches](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#videos-totalmatches)
// - count). Use this parameter along with the count parameter to page results. For example, if your user interface
// displays 20 videos per page, set count to 20 and offset to 0 to get the first page of results. For each subsequent
// page, increment offset by 20 (for example, 0, 20, 40). It is possible for multiple pages to include some overlap in
// results. To prevent duplicates, see
// [nextOffset](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#videos-nextoffset).
// Use this parameter only with the Video Search API. pricing is filter videos by the following pricing options: Free:
// Return videos that are free to view. Paid: Return videos that require a subscription or payment to view. All: Do not
// filter by pricing.Specifying this value is the same as not specifying the pricing parameter. resolution is filter
// videos by the following resolutions: SD480p: Return videos with a 480p or higher resolution. HD720p: Return videos
// with a 720p or higher resolution. HD1080p: Return videos with a 1080p or higher resolution. All: Do not filter by
// resolution.Specifying this value is the same as not specifying the resolution parameter. safeSearch is filter videos
// for adult content. The following are the possible filter values. Off: If the request is through the Video Search
// API, the response includes adult videos and the thumbnail images of the videos are clear (non-fuzzy). If the request
// is through the Web Search API, the response includes adult videos but the thumbnail images of the videos are
// pixelated (fuzzy). Moderate: If the request is through the Video Search API, the response does not include videos
// with adult content. If the request is through the Web Search API, the response may include videos with adult content
// but the thumbnail images of the videos are pixelated (fuzzy). Strict: Does not return videos with adult content. The
// default is Moderate. If the request comes from a market that Bing's adult policy requires that safeSearch is set to
// Strict, Bing ignores the safeSearch value and uses Strict. If you use the site: query operator, there is the chance
// that the response may contain adult content regardless of what the safeSearch query parameter is set to. Use site:
// only if you are aware of the content on the site and your scenario supports the possibility of adult content.
// setLang is the language to use for user interface strings. Specify the language using the ISO 639-1 2-letter
// language code. For example, the language code for English is EN. The default is EN (English). Although optional, you
// should always specify the language. Typically, you set setLang to the same language specified by mkt unless the user
// wants the user interface strings displayed in a different language. This parameter and the
// [Accept-Language](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#acceptlanguage)
// header are mutually exclusive; do not specify both. A user interface string is a string that's used as a label in a
// user interface. There are few user interface strings in the JSON response objects. Also, any links to Bing.com
// properties in the response objects apply the specified language. textDecorations is a Boolean value that determines
// whether display strings contain decoration markers such as hit highlighting characters. If true, the strings may
// include markers. The default is false. To specify whether to use Unicode characters or HTML tags as the markers, see
// the [textFormat](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#textformat)
// query parameter. For information about hit highlighting, see [Hit
// Highlighting](https://docs.microsoft.com/azure/cognitive-services/bing-news-search/hit-highlighting). textFormat is
// the type of markers to use for text decorations (see the textDecorations query parameter). Possible values are
// Raw—Use Unicode characters to mark content that needs special formatting. The Unicode characters are in the range
// E000 through E019. For example, Bing uses E000 and E001 to mark the beginning and end of query terms for hit
// highlighting. HTML—Use HTML tags to mark content that needs special formatting. For example, use <b> tags to
// highlight query terms in display strings. The default is Raw. For display strings that contain escapable HTML
// characters such as <, >, and &, if textFormat is set to HTML, Bing escapes the characters as appropriate (for
// example, < is escaped to &lt;).
func (client VideosClient) Search(ctx context.Context, xBingApisSDK string, query string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, countryCode string, count *int32, freshness Freshness, ID string, length VideoLength, market string, offset *int32, pricing VideoPricing, resolution VideoResolution, safeSearch SafeSearch, setLang string, textDecorations *bool, textFormat TextFormat) (result Videos, err error) {
req, err := client.SearchPreparer(ctx, xBingApisSDK, query, acceptLanguage, userAgent, clientID, clientIP, location, countryCode, count, freshness, ID, length, market, offset, pricing, resolution, safeSearch, setLang, textDecorations, textFormat)
if err != nil {
err = autorest.NewErrorWithError(err, "videosearch.VideosClient", "Search", nil, "Failure preparing request")
return
}
resp, err := client.SearchSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "videosearch.VideosClient", "Search", resp, "Failure sending request")
return
}
result, err = client.SearchResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "videosearch.VideosClient", "Search", resp, "Failure responding to request")
}
return
}
// SearchPreparer prepares the Search request.
func (client VideosClient) SearchPreparer(ctx context.Context, xBingApisSDK string, query string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, countryCode string, count *int32, freshness Freshness, ID string, length VideoLength, market string, offset *int32, pricing VideoPricing, resolution VideoResolution, safeSearch SafeSearch, setLang string, textDecorations *bool, textFormat TextFormat) (*http.Request, error) {
queryParameters := map[string]interface{}{
"q": autorest.Encode("query", query),
}
if len(countryCode) > 0 {
queryParameters["cc"] = autorest.Encode("query", countryCode)
}
if count != nil {
queryParameters["count"] = autorest.Encode("query", *count)
}
if len(string(freshness)) > 0 {
queryParameters["freshness"] = autorest.Encode("query", freshness)
}
if len(ID) > 0 {
queryParameters["id"] = autorest.Encode("query", ID)
}
if len(string(length)) > 0 {
queryParameters["length"] = autorest.Encode("query", length)
}
if len(market) > 0 {
queryParameters["mkt"] = autorest.Encode("query", market)
}
if offset != nil {
queryParameters["offset"] = autorest.Encode("query", *offset)
}
if len(string(pricing)) > 0 {
queryParameters["pricing"] = autorest.Encode("query", pricing)
}
if len(string(resolution)) > 0 {
queryParameters["resolution"] = autorest.Encode("query", resolution)
}
if len(string(safeSearch)) > 0 {
queryParameters["safeSearch"] = autorest.Encode("query", safeSearch)
}
if len(setLang) > 0 {
queryParameters["setLang"] = autorest.Encode("query", setLang)
}
if textDecorations != nil {
queryParameters["textDecorations"] = autorest.Encode("query", *textDecorations)
}
if len(string(textFormat)) > 0 {
queryParameters["textFormat"] = autorest.Encode("query", textFormat)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/videos/search"),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("X-BingApis-SDK", autorest.String(xBingApisSDK)))
if len(acceptLanguage) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
}
if len(userAgent) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("User-Agent", autorest.String(userAgent)))
}
if len(clientID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
}
if len(clientIP) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
}
if len(location) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-Search-Location", autorest.String(location)))
}
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// SearchSender sends the Search request. The method will close the
// http.Response Body if it receives an error.
func (client VideosClient) SearchSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// SearchResponder handles the response to the Search request. The method always
// closes the http.Response Body.
func (client VideosClient) SearchResponder(resp *http.Response) (result Videos, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Trending sends the trending request.
//
// xBingApisSDK is activate swagger compliance acceptLanguage is a comma-delimited list of one or more languages to use
// for user interface strings. The list is in decreasing order of preference. For additional information, including
// expected format, see [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#setlang) query
// parameter are mutually exclusive; do not specify both. If you set this header, you must also specify the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#cc) query parameter. To
// determine the market to return results for, Bing uses the first supported language it finds from the list and
// combines it with the cc parameter value. If the list does not include a supported language, Bing finds the closest
// language and market that supports the request or it uses an aggregated or default market for the results. To
// determine the market that Bing used, see the BingAPIs-Market header. Use this header and the cc query parameter only
// if you specify multiple languages. Otherwise, use the
// [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#mkt) and
// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#setlang) query
// parameters. A user interface string is a string that's used as a label in a user interface. There are few user
// interface strings in the JSON response objects. Any links to Bing.com properties in the response objects apply the
// specified language. userAgent is the user agent originating the request. Bing uses the user agent to provide mobile
// users with an optimized experience. Although optional, you are encouraged to always specify this header. The
// user-agent should be the same string that any commonly used browser sends. For information about user agents, see
// [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The following are examples of user-agent
// strings. Windows Phone: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM;
// Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build / GINGERBREAD)
// AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU
// iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142 iPhone4; 1 BingWeb /
// 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad:
// Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML, like Gecko) Version / 7.0 Mobile /
// 11A465 Safari / 9537.53 clientID is bing uses this header to provide users with consistent behavior across Bing API
// calls. Bing often flights new features and improvements, and it uses the client ID as a key for assigning traffic on
// different flights. If you do not use the same client ID for a user across multiple requests, then Bing may assign
// the user to multiple conflicting flights. Being assigned to multiple conflicting flights can lead to an inconsistent
// user experience. For example, if the second request has a different flight assignment than the first, the experience
// may be unexpected. Also, Bing can use the client ID to tailor web results to that client ID’s search history,
// providing a richer experience for the user. Bing also uses this header to help improve result rankings by analyzing
// the activity generated by a client ID. The relevance improvements help with better quality of results delivered by
// Bing APIs and in turn enables higher click-through rates for the API consumer. IMPORTANT: Although optional, you
// should consider this header required. Persisting the client ID across multiple requests for the same end user and
// device combination enables 1) the API consumer to receive a consistent user experience, and 2) higher click-through
// rates via better quality of results from the Bing APIs. Each user that uses your application on the device must have
// a unique, Bing generated client ID. If you do not include this header in the request, Bing generates an ID and
// returns it in the X-MSEdge-ClientID response header. The only time that you should NOT include this header in a
// request is the first time the user uses your app on that device. Use the client ID for each Bing API request that
// your app makes for this user on the device. Persist the client ID. To persist the ID in a browser app, use a
// persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session cookie. For other apps
// such as mobile apps, use the device's persistent storage to persist the ID. The next time the user uses your app on
// that device, get the client ID that you persisted. Bing responses may or may not include this header. If the
// response includes this header, capture the client ID and use it for all subsequent Bing requests for the user on
// that device. If you include the X-MSEdge-ClientID, you must not include cookies in the request. clientIP is the IPv4
// or IPv6 address of the client device. The IP address is used to discover the user's location. Bing uses the location
// information to determine safe search behavior. Although optional, you are encouraged to always specify this header
// and the X-Search-Location header. Do not obfuscate the address (for example, by changing the last octet to 0).
// Obfuscating the address results in the location not being anywhere near the device's actual location, which may
// result in Bing serving erroneous results. location is a semicolon-delimited list of key/value pairs that describe
// the client's geographical location. Bing uses the location information to determine safe search behavior and to
// return relevant local content. Specify the key/value pair as <key>:<value>. The following are the keys that you use
// to specify the user's location. lat (required): The latitude of the client's location, in degrees. The latitude must
// be greater than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and
// positive values indicate northern latitudes. long (required): The longitude of the client's location, in degrees.
// The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative values indicate
// western longitudes and positive values indicate eastern longitudes. re (required): The radius, in meters, which
// specifies the horizontal accuracy of the coordinates. Pass the value returned by the device's location service.
// Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts
// (optional): The UTC UNIX timestamp of when the client was at the location. (The UNIX timestamp is the number of
// seconds since January 1, 1970.) head (optional): The client's relative heading or direction of travel. Specify the
// direction of travel as degrees from 0 through 360, counting clockwise relative to true north. Specify this key only
// if the sp key is nonzero. sp (optional): The horizontal velocity (speed), in meters per second, that the client
// device is traveling. alt (optional): The altitude of the client device, in meters. are (optional): The radius, in
// meters, that specifies the vertical accuracy of the coordinates. Specify this key only if you specify the alt key.
// Although many of the keys are optional, the more information that you provide, the more accurate the location
// results are. Although optional, you are encouraged to always specify the user's geographical location. Providing the
// location is especially important if the client's IP address does not accurately reflect the user's physical location
// (for example, if the client uses VPN). For optimal results, you should include this header and the X-MSEdge-ClientIP
// header, but at a minimum, you should include this header. countryCode is a 2-character country code of the country
// where the results come from. This API supports only the United States market. If you specify this query parameter,
// it must be set to us. If you set this parameter, you must also specify the Accept-Language header. Bing uses the
// first supported language it finds from the languages list, and combine that language with the country code that you
// specify to determine the market to return results for. If the languages list does not include a supported language,
// Bing finds the closest language and market that supports the request, or it may use an aggregated or default market
// for the results instead of a specified one. You should use this query parameter and the Accept-Language query
// parameter only if you specify multiple languages; otherwise, you should use the mkt and setLang query parameters.
// This parameter and the mkt query parameter are mutually exclusive—do not specify both. market is the market where
// the results come from. Typically, mkt is the country where the user is making the request from. However, it could be
// a different country if the user is not located in a country where Bing delivers results. The market must be in the
// form <language code>-<country code>. For example, en-US. The string is case insensitive. For a list of possible
// market values, see [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#market-codes). NOTE:
// If known, you are encouraged to always specify the market. Specifying the market helps Bing route the request and
// return an appropriate and optimal response. If you specify a market that is not listed in [Market
// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#market-codes), Bing
// uses a best fit market code based on an internal mapping that is subject to change. This parameter and the
// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#cc) query parameter are
// mutually exclusive—do not specify both. safeSearch is filter videos for adult content. The following are the
// possible filter values. Off: If the request is through the Video Search API, the response includes adult videos and
// the thumbnail images of the videos are clear (non-fuzzy). If the request is through the Web Search API, the response
// includes adult videos but the thumbnail images of the videos are pixelated (fuzzy). Moderate: If the request is
// through the Video Search API, the response does not include videos with adult content. If the request is through the
// Web Search API, the response may include videos with adult content but the thumbnail images of the videos are
// pixelated (fuzzy). Strict: Does not return videos with adult content. The default is Moderate. If the request comes
// from a market that Bing's adult policy requires that safeSearch is set to Strict, Bing ignores the safeSearch value
// and uses Strict. If you use the site: query operator, there is the chance that the response may contain adult
// content regardless of what the safeSearch query parameter is set to. Use site: only if you are aware of the content
// on the site and your scenario supports the possibility of adult content. setLang is the language to use for user
// interface strings. Specify the language using the ISO 639-1 2-letter language code. For example, the language code
// for English is EN. The default is EN (English). Although optional, you should always specify the language.
// Typically, you set setLang to the same language specified by mkt unless the user wants the user interface strings
// displayed in a different language. This parameter and the
// [Accept-Language](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#acceptlanguage)
// header are mutually exclusive; do not specify both. A user interface string is a string that's used as a label in a
// user interface. There are few user interface strings in the JSON response objects. Also, any links to Bing.com
// properties in the response objects apply the specified language. textDecorations is a Boolean value that determines
// whether display strings contain decoration markers such as hit highlighting characters. If true, the strings may
// include markers. The default is false. To specify whether to use Unicode characters or HTML tags as the markers, see
// the [textFormat](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference#textformat)
// query parameter. For information about hit highlighting, see [Hit
// Highlighting](https://docs.microsoft.com/azure/cognitive-services/bing-news-search/hit-highlighting). textFormat is
// the type of markers to use for text decorations (see the textDecorations query parameter). Possible values are
// Raw—Use Unicode characters to mark content that needs special formatting. The Unicode characters are in the range
// E000 through E019. For example, Bing uses E000 and E001 to mark the beginning and end of query terms for hit
// highlighting. HTML—Use HTML tags to mark content that needs special formatting. For example, use <b> tags to
// highlight query terms in display strings. The default is Raw. For display strings that contain escapable HTML
// characters such as <, >, and &, if textFormat is set to HTML, Bing escapes the characters as appropriate (for
// example, < is escaped to &lt;).
func (client VideosClient) Trending(ctx context.Context, xBingApisSDK string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, countryCode string, market string, safeSearch SafeSearch, setLang string, textDecorations *bool, textFormat TextFormat) (result TrendingVideos, err error) {
req, err := client.TrendingPreparer(ctx, xBingApisSDK, acceptLanguage, userAgent, clientID, clientIP, location, countryCode, market, safeSearch, setLang, textDecorations, textFormat)
if err != nil {
err = autorest.NewErrorWithError(err, "videosearch.VideosClient", "Trending", nil, "Failure preparing request")
return
}
resp, err := client.TrendingSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "videosearch.VideosClient", "Trending", resp, "Failure sending request")
return
}
result, err = client.TrendingResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "videosearch.VideosClient", "Trending", resp, "Failure responding to request")
}
return
}
// TrendingPreparer prepares the Trending request.
func (client VideosClient) TrendingPreparer(ctx context.Context, xBingApisSDK string, acceptLanguage string, userAgent string, clientID string, clientIP string, location string, countryCode string, market string, safeSearch SafeSearch, setLang string, textDecorations *bool, textFormat TextFormat) (*http.Request, error) {
queryParameters := map[string]interface{}{}
if len(countryCode) > 0 {
queryParameters["cc"] = autorest.Encode("query", countryCode)
}
if len(market) > 0 {
queryParameters["mkt"] = autorest.Encode("query", market)
}
if len(string(safeSearch)) > 0 {
queryParameters["safeSearch"] = autorest.Encode("query", safeSearch)
}
if len(setLang) > 0 {
queryParameters["setLang"] = autorest.Encode("query", setLang)
}
if textDecorations != nil {
queryParameters["textDecorations"] = autorest.Encode("query", *textDecorations)
}
if len(string(textFormat)) > 0 {
queryParameters["textFormat"] = autorest.Encode("query", textFormat)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/videos/trending"),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("X-BingApis-SDK", autorest.String(xBingApisSDK)))
if len(acceptLanguage) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
}
if len(userAgent) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("User-Agent", autorest.String(userAgent)))
}
if len(clientID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
}
if len(clientIP) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
}
if len(location) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-Search-Location", autorest.String(location)))
}
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// TrendingSender sends the Trending request. The method will close the
// http.Response Body if it receives an error.
func (client VideosClient) TrendingSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// TrendingResponder handles the response to the Trending request. The method always
// closes the http.Response Body.
func (client VideosClient) TrendingResponder(resp *http.Response) (result TrendingVideos, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,50 @@
// Package websearch implements the Azure ARM Websearch service API version 1.0.
//
// The Web Search API lets you send a search query to Bing and get back search results that include links to webpages,
// images, and more.
package websearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
const (
// DefaultBaseURI is the default URI used for the service Websearch
DefaultBaseURI = "https://api.cognitive.microsoft.com/bing/v7.0"
)
// BaseClient is the base client for Websearch.
type BaseClient struct {
autorest.Client
BaseURI string
}
// New creates an instance of the BaseClient client.
func New() BaseClient {
return NewWithBaseURI(DefaultBaseURI)
}
// NewWithBaseURI creates an instance of the BaseClient client.
func NewWithBaseURI(baseURI string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,28 @@
package websearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/v12.2.0-beta services"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v12.2.0-beta"
}
@@ -0,0 +1,293 @@
package websearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// WebClient is the the Web Search API lets you send a search query to Bing and get back search results that include
// links to webpages, images, and more.
type WebClient struct {
BaseClient
}
// NewWebClient creates an instance of the WebClient client.
func NewWebClient() WebClient {
return NewWebClientWithBaseURI(DefaultBaseURI)
}
// NewWebClientWithBaseURI creates an instance of the WebClient client.
func NewWebClientWithBaseURI(baseURI string) WebClient {
return WebClient{NewWithBaseURI(baseURI)}
}
// Search sends the search request.
//
// xBingApisSDK is activate swagger compliance query is the user's search query term. The term may not be empty. The
// term may contain Bing Advanced Operators. For example, to limit results to a specific domain, use the site:
// operator. acceptLanguage is a comma-delimited list of one or more languages to use for user interface strings. The
// list is in decreasing order of preference. For additional information, including expected format, see
// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the setLang query parameter are
// mutually exclusive; do not specify both. If you set this header, you must also specify the cc query parameter. Bing
// will use the first supported language it finds from the list, and combine that language with the cc parameter value
// to determine the market to return results for. If the list does not include a supported language, Bing will find the
// closest language and market that supports the request, and may use an aggregated or default market for the results
// instead of a specified one. You should use this header and the cc query parameter only if you specify multiple
// languages; otherwise, you should use the mkt and setLang query parameters. A user interface string is a string
// that's used as a label in a user interface. There are very few user interface strings in the JSON response objects.
// Any links in the response objects to Bing.com properties will apply the specified language. pragma is by default,
// Bing returns cached content, if available. To prevent Bing from returning cached content, set the Pragma header to
// no-cache (for example, Pragma: no-cache). userAgent is the user agent originating the request. Bing uses the user
// agent to provide mobile users with an optimized experience. Although optional, you are strongly encouraged to always
// specify this header. The user-agent should be the same string that any commonly used browser would send. For
// information about user agents, see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). clientID is
// bing uses this header to provide users with consistent behavior across Bing API calls. Bing often flights new
// features and improvements, and it uses the client ID as a key for assigning traffic on different flights. If you do
// not use the same client ID for a user across multiple requests, then Bing may assign the user to multiple
// conflicting flights. Being assigned to multiple conflicting flights can lead to an inconsistent user experience. For
// example, if the second request has a different flight assignment than the first, the experience may be unexpected.
// Also, Bing can use the client ID to tailor web results to that client ID’s search history, providing a richer
// experience for the user. Bing also uses this header to help improve result rankings by analyzing the activity
// generated by a client ID. The relevance improvements help with better quality of results delivered by Bing APIs and
// in turn enables higher click-through rates for the API consumer. IMPORTANT: Although optional, you should consider
// this header required. Persisting the client ID across multiple requests for the same end user and device combination
// enables 1) the API consumer to receive a consistent user experience, and 2) higher click-through rates via better
// quality of results from the Bing APIs. Each user that uses your application on the device must have a unique, Bing
// generated client ID. If you do not include this header in the request, Bing generates an ID and returns it in the
// X-MSEdge-ClientID response header. The only time that you should NOT include this header in a request is the first
// time the user uses your app on that device. Use the client ID for each Bing API request that your app makes for this
// user on the device. Persist the client ID. To persist the ID in a browser app, use a persistent HTTP cookie to
// ensure the ID is used across all sessions. Do not use a session cookie. For other apps such as mobile apps, use the
// device's persistent storage to persist the ID. The next time the user uses your app on that device, get the client
// ID that you persisted. Bing responses may or may not include this header. If the response includes this header,
// capture the client ID and use it for all subsequent Bing requests for the user on that device. If you include the
// X-MSEdge-ClientID, you must not include cookies in the request. clientIP is the IPv4 or IPv6 address of the client
// device. The IP address is used to discover the user's location. Bing uses the location information to determine safe
// search behavior. Although optional, you are encouraged to always specify this header and the X-Search-Location
// header. Do not obfuscate the address (for example, by changing the last octet to 0). Obfuscating the address results
// in the location not being anywhere near the device's actual location, which may result in Bing serving erroneous
// results. location is a semicolon-delimited list of key/value pairs that describe the client's geographical location.
// Bing uses the location information to determine safe search behavior and to return relevant local content. Specify
// the key/value pair as <key>:<value>. The following are the keys that you use to specify the user's location. lat
// (required): The latitude of the client's location, in degrees. The latitude must be greater than or equal to -90.0
// and less than or equal to +90.0. Negative values indicate southern latitudes and positive values indicate northern
// latitudes. long (required): The longitude of the client's location, in degrees. The longitude must be greater than
// or equal to -180.0 and less than or equal to +180.0. Negative values indicate western longitudes and positive values
// indicate eastern longitudes. re (required): The radius, in meters, which specifies the horizontal accuracy of the
// coordinates. Pass the value returned by the device's location service. Typical values might be 22m for GPS/Wi-Fi,
// 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts (optional): The UTC UNIX timestamp of when
// the client was at the location. (The UNIX timestamp is the number of seconds since January 1, 1970.) head
// (optional): The client's relative heading or direction of travel. Specify the direction of travel as degrees from 0
// through 360, counting clockwise relative to true north. Specify this key only if the sp key is nonzero. sp
// (optional): The horizontal velocity (speed), in meters per second, that the client device is traveling. alt
// (optional): The altitude of the client device, in meters. are (optional): The radius, in meters, that specifies the
// vertical accuracy of the coordinates. Specify this key only if you specify the alt key. Although many of the keys
// are optional, the more information that you provide, the more accurate the location results are. Although optional,
// you are encouraged to always specify the user's geographical location. Providing the location is especially
// important if the client's IP address does not accurately reflect the user's physical location (for example, if the
// client uses VPN). For optimal results, you should include this header and the X-MSEdge-ClientIP header, but at a
// minimum, you should include this header. answerCount is the number of answers that you want the response to include.
// The answers that Bing returns are based on ranking. For example, if Bing returns webpages, images, videos, and
// relatedSearches for a request and you set this parameter to two (2), the response includes webpages and images.If
// you included the responseFilter query parameter in the same request and set it to webpages and news, the response
// would include only webpages. countryCode is a 2-character country code of the country where the results come from.
// This API supports only the United States market. If you specify this query parameter, it must be set to us. If you
// set this parameter, you must also specify the Accept-Language header. Bing uses the first supported language it
// finds from the languages list, and combine that language with the country code that you specify to determine the
// market to return results for. If the languages list does not include a supported language, Bing finds the closest
// language and market that supports the request, or it may use an aggregated or default market for the results instead
// of a specified one. You should use this query parameter and the Accept-Language query parameter only if you specify
// multiple languages; otherwise, you should use the mkt and setLang query parameters. This parameter and the mkt query
// parameter are mutually exclusive—do not specify both. count is the number of search results to return in the
// response. The default is 10 and the maximum value is 50. The actual number delivered may be less than requested.Use
// this parameter along with the offset parameter to page results.For example, if your user interface displays 10
// search results per page, set count to 10 and offset to 0 to get the first page of results. For each subsequent page,
// increment offset by 10 (for example, 0, 10, 20). It is possible for multiple pages to include some overlap in
// results. freshness is filter search results by the following age values: Day—Return webpages that Bing discovered
// within the last 24 hours. Week—Return webpages that Bing discovered within the last 7 days. Month—Return webpages
// that discovered within the last 30 days. This filter applies only to webpage results and not to the other results
// such as news and images. market is the market where the results come from. Typically, mkt is the country where the
// user is making the request from. However, it could be a different country if the user is not located in a country
// where Bing delivers results. The market must be in the form <language code>-<country code>. For example, en-US. The
// string is case insensitive. If known, you are encouraged to always specify the market. Specifying the market helps
// Bing route the request and return an appropriate and optimal response. If you specify a market that is not listed in
// Market Codes, Bing uses a best fit market code based on an internal mapping that is subject to change. This
// parameter and the cc query parameter are mutually exclusive—do not specify both. offset is the zero-based offset
// that indicates the number of search results to skip before returning results. The default is 0. The offset should be
// less than (totalEstimatedMatches - count). Use this parameter along with the count parameter to page results. For
// example, if your user interface displays 10 search results per page, set count to 10 and offset to 0 to get the
// first page of results. For each subsequent page, increment offset by 10 (for example, 0, 10, 20). it is possible for
// multiple pages to include some overlap in results. promote is a comma-delimited list of answers that you want the
// response to include regardless of their ranking. For example, if you set answerCount) to two (2) so Bing returns the
// top two ranked answers, but you also want the response to include news, you'd set promote to news. If the top ranked
// answers are webpages, images, videos, and relatedSearches, the response includes webpages and images because news is
// not a ranked answer. But if you set promote to video, Bing would promote the video answer into the response and
// return webpages, images, and videos. The answers that you want to promote do not count against the answerCount
// limit. For example, if the ranked answers are news, images, and videos, and you set answerCount to 1 and promote to
// news, the response contains news and images. Or, if the ranked answers are videos, images, and news, the response
// contains videos and news. Possible values are Computation, Images, News, RelatedSearches, SpellSuggestions,
// TimeZone, Videos, Webpages. Use only if you specify answerCount. responseFilter is a comma-delimited list of answers
// to include in the response. If you do not specify this parameter, the response includes all search answers for which
// there's relevant data. Possible filter values are Computation, Images, News, RelatedSearches, SpellSuggestions,
// TimeZone, Videos, Webpages. Although you may use this filter to get a single answer, you should instead use the
// answer-specific endpoint in order to get richer results. For example, to receive only images, send the request to
// one of the Image Search API endpoints. The RelatedSearches and SpellSuggestions answers do not support a separate
// endpoint like the Image Search API does (only the Web Search API returns them). To include answers that would
// otherwise be excluded because of ranking, see the promote query parameter. safeSearch is a filter used to filter
// adult content. Off: Return webpages with adult text, images, or videos. Moderate: Return webpages with adult text,
// but not adult images or videos. Strict: Do not return webpages with adult text, images, or videos. The default is
// Moderate. If the request comes from a market that Bing's adult policy requires that safeSearch is set to Strict,
// Bing ignores the safeSearch value and uses Strict. If you use the site: query operator, there is the chance that the
// response may contain adult content regardless of what the safeSearch query parameter is set to. Use site: only if
// you are aware of the content on the site and your scenario supports the possibility of adult content. setLang is the
// language to use for user interface strings. Specify the language using the ISO 639-1 2-letter language code. For
// example, the language code for English is EN. The default is EN (English). Although optional, you should always
// specify the language. Typically, you set setLang to the same language specified by mkt unless the user wants the
// user interface strings displayed in a different language. This parameter and the Accept-Language header are mutually
// exclusive; do not specify both. A user interface string is a string that's used as a label in a user interface.
// There are few user interface strings in the JSON response objects. Also, any links to Bing.com properties in the
// response objects apply the specified language. textDecorations is a Boolean value that determines whether display
// strings should contain decoration markers such as hit highlighting characters. If true, the strings may include
// markers. The default is false. To specify whether to use Unicode characters or HTML tags as the markers, see the
// textFormat query parameter. textFormat is the type of markers to use for text decorations (see the textDecorations
// query parameter). Possible values are Raw—Use Unicode characters to mark content that needs special formatting. The
// Unicode characters are in the range E000 through E019. For example, Bing uses E000 and E001 to mark the beginning
// and end of query terms for hit highlighting. HTML—Use HTML tags to mark content that needs special formatting. For
// example, use <b> tags to highlight query terms in display strings. The default is Raw. For display strings that
// contain escapable HTML characters such as <, >, and &, if textFormat is set to HTML, Bing escapes the characters as
// appropriate (for example, < is escaped to &lt;).
func (client WebClient) Search(ctx context.Context, xBingApisSDK string, 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) {
req, err := client.SearchPreparer(ctx, xBingApisSDK, query, acceptLanguage, pragma, userAgent, clientID, clientIP, location, answerCount, countryCode, count, freshness, market, offset, promote, responseFilter, safeSearch, setLang, textDecorations, textFormat)
if err != nil {
err = autorest.NewErrorWithError(err, "websearch.WebClient", "Search", nil, "Failure preparing request")
return
}
resp, err := client.SearchSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "websearch.WebClient", "Search", resp, "Failure sending request")
return
}
result, err = client.SearchResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "websearch.WebClient", "Search", resp, "Failure responding to request")
}
return
}
// SearchPreparer prepares the Search request.
func (client WebClient) SearchPreparer(ctx context.Context, xBingApisSDK string, 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) {
queryParameters := map[string]interface{}{
"q": autorest.Encode("query", query),
}
if answerCount != nil {
queryParameters["answerCount"] = autorest.Encode("query", *answerCount)
}
if len(countryCode) > 0 {
queryParameters["cc"] = autorest.Encode("query", countryCode)
}
if count != nil {
queryParameters["count"] = autorest.Encode("query", *count)
}
if len(string(freshness)) > 0 {
queryParameters["freshness"] = autorest.Encode("query", freshness)
}
if len(market) > 0 {
queryParameters["mkt"] = autorest.Encode("query", market)
}
if offset != nil {
queryParameters["offset"] = autorest.Encode("query", *offset)
}
if promote != nil && len(promote) > 0 {
queryParameters["promote"] = autorest.Encode("query", promote, ",")
}
if responseFilter != nil && len(responseFilter) > 0 {
queryParameters["responseFilter"] = autorest.Encode("query", responseFilter, ",")
}
if len(string(safeSearch)) > 0 {
queryParameters["safeSearch"] = autorest.Encode("query", safeSearch)
}
if len(setLang) > 0 {
queryParameters["setLang"] = autorest.Encode("query", setLang)
}
if textDecorations != nil {
queryParameters["textDecorations"] = autorest.Encode("query", *textDecorations)
}
if len(string(textFormat)) > 0 {
queryParameters["textFormat"] = autorest.Encode("query", textFormat)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/search"),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("X-BingApis-SDK", autorest.String(xBingApisSDK)))
if len(acceptLanguage) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
}
if len(pragma) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Pragma", autorest.String(pragma)))
}
if len(userAgent) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("User-Agent", autorest.String(userAgent)))
}
if len(clientID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
}
if len(clientIP) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
}
if len(location) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("X-Search-Location", autorest.String(location)))
}
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// SearchSender sends the Search request. The method will close the
// http.Response Body if it receives an error.
func (client WebClient) SearchSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// SearchResponder handles the response to the Search request. The method always
// closes the http.Response Body.
func (client WebClient) SearchResponder(resp *http.Response) (result SearchResponse, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,239 @@
// Package textanalytics implements the Azure ARM Textanalytics service API version v2.0.
//
// The Text Analytics API is a suite of text analytics web services built with best-in-class Microsoft machine learning
// algorithms. The API can be used to analyze unstructured text for tasks such as sentiment analysis, key phrase
// extraction and language detection. No training data is needed to use this API; just bring your text data. This API
// uses advanced natural language processing techniques to deliver best in class predictions. Further documentation can
// be found in https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview
package textanalytics
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// BaseClient is the base client for Textanalytics.
type BaseClient struct {
autorest.Client
AzureRegion AzureRegions
}
// New creates an instance of the BaseClient client.
func New(azureRegion AzureRegions) BaseClient {
return NewWithoutDefaults(azureRegion)
}
// NewWithoutDefaults creates an instance of the BaseClient client.
func NewWithoutDefaults(azureRegion AzureRegions) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
AzureRegion: azureRegion,
}
}
// DetectLanguage scores close to 1 indicate 100% certainty that the identified language is true. A total of 120
// languages are supported.
//
// input is collection of documents to analyze.
func (client BaseClient) DetectLanguage(ctx context.Context, input BatchInput) (result LanguageBatchResult, err error) {
req, err := client.DetectLanguagePreparer(ctx, input)
if err != nil {
err = autorest.NewErrorWithError(err, "textanalytics.BaseClient", "DetectLanguage", nil, "Failure preparing request")
return
}
resp, err := client.DetectLanguageSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "textanalytics.BaseClient", "DetectLanguage", resp, "Failure sending request")
return
}
result, err = client.DetectLanguageResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "textanalytics.BaseClient", "DetectLanguage", resp, "Failure responding to request")
}
return
}
// DetectLanguagePreparer prepares the DetectLanguage request.
func (client BaseClient) DetectLanguagePreparer(ctx context.Context, input BatchInput) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/text/analytics", urlParameters),
autorest.WithPath("/v2.0/languages"),
autorest.WithJSON(input))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DetectLanguageSender sends the DetectLanguage request. The method will close the
// http.Response Body if it receives an error.
func (client BaseClient) DetectLanguageSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// DetectLanguageResponder handles the response to the DetectLanguage request. The method always
// closes the http.Response Body.
func (client BaseClient) DetectLanguageResponder(resp *http.Response) (result LanguageBatchResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// KeyPhrases we employ techniques from Microsoft Office's sophisticated Natural Language Processing toolkit. See the
// <a href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
// Analytics Documentation</a> for details about the languages that are supported by key phrase extraction.
//
// input is collection of documents to analyze. Documents can now contain a language field to indicate the text
// language
func (client BaseClient) KeyPhrases(ctx context.Context, input MultiLanguageBatchInput) (result KeyPhraseBatchResult, err error) {
req, err := client.KeyPhrasesPreparer(ctx, input)
if err != nil {
err = autorest.NewErrorWithError(err, "textanalytics.BaseClient", "KeyPhrases", nil, "Failure preparing request")
return
}
resp, err := client.KeyPhrasesSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "textanalytics.BaseClient", "KeyPhrases", resp, "Failure sending request")
return
}
result, err = client.KeyPhrasesResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "textanalytics.BaseClient", "KeyPhrases", resp, "Failure responding to request")
}
return
}
// KeyPhrasesPreparer prepares the KeyPhrases request.
func (client BaseClient) KeyPhrasesPreparer(ctx context.Context, input MultiLanguageBatchInput) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/text/analytics", urlParameters),
autorest.WithPath("/v2.0/keyPhrases"),
autorest.WithJSON(input))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// KeyPhrasesSender sends the KeyPhrases request. The method will close the
// http.Response Body if it receives an error.
func (client BaseClient) KeyPhrasesSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// KeyPhrasesResponder handles the response to the KeyPhrases request. The method always
// closes the http.Response Body.
func (client BaseClient) KeyPhrasesResponder(resp *http.Response) (result KeyPhraseBatchResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Sentiment scores close to 1 indicate positive sentiment, while scores close to 0 indicate negative sentiment.
// Sentiment score is generated using classification techniques. The input features to the classifier include n-grams,
// features generated from part-of-speech tags, and word embeddings. See the <a
// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
// Analytics Documentation</a> for details about the languages that are supported by sentiment analysis.
//
// input is collection of documents to analyze.
func (client BaseClient) Sentiment(ctx context.Context, input MultiLanguageBatchInput) (result SentimentBatchResult, err error) {
req, err := client.SentimentPreparer(ctx, input)
if err != nil {
err = autorest.NewErrorWithError(err, "textanalytics.BaseClient", "Sentiment", nil, "Failure preparing request")
return
}
resp, err := client.SentimentSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "textanalytics.BaseClient", "Sentiment", resp, "Failure sending request")
return
}
result, err = client.SentimentResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "textanalytics.BaseClient", "Sentiment", resp, "Failure responding to request")
}
return
}
// SentimentPreparer prepares the Sentiment request.
func (client BaseClient) SentimentPreparer(ctx context.Context, input MultiLanguageBatchInput) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/text/analytics", urlParameters),
autorest.WithPath("/v2.0/sentiment"),
autorest.WithJSON(input))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// SentimentSender sends the Sentiment request. The method will close the
// http.Response Body if it receives an error.
func (client BaseClient) SentimentSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// SentimentResponder handles the response to the Sentiment request. The method always
// closes the http.Response Body.
func (client BaseClient) SentimentResponder(resp *http.Response) (result SentimentBatchResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
@@ -0,0 +1,156 @@
package textanalytics
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
// AzureRegions enumerates the values for azure regions.
type AzureRegions string
const (
// Australiaeast ...
Australiaeast AzureRegions = "australiaeast"
// Brazilsouth ...
Brazilsouth AzureRegions = "brazilsouth"
// Eastasia ...
Eastasia AzureRegions = "eastasia"
// Eastus ...
Eastus AzureRegions = "eastus"
// Eastus2 ...
Eastus2 AzureRegions = "eastus2"
// Northeurope ...
Northeurope AzureRegions = "northeurope"
// Southcentralus ...
Southcentralus AzureRegions = "southcentralus"
// Southeastasia ...
Southeastasia AzureRegions = "southeastasia"
// Westcentralus ...
Westcentralus AzureRegions = "westcentralus"
// Westeurope ...
Westeurope AzureRegions = "westeurope"
// Westus ...
Westus AzureRegions = "westus"
// Westus2 ...
Westus2 AzureRegions = "westus2"
)
// BatchInput ...
type BatchInput struct {
Documents *[]Input `json:"documents,omitempty"`
}
// DetectedLanguage ...
type DetectedLanguage struct {
// Name - Long name of a detected language (e.g. English, French).
Name *string `json:"name,omitempty"`
// Iso6391Name - A two letter representation of the detected language according to the ISO 639-1 standard (e.g. en, fr).
Iso6391Name *string `json:"iso6391Name,omitempty"`
// Score - A confidence score between 0 and 1. Scores close to 1 indicate 100% certainty that the identified language is true.
Score *float64 `json:"score,omitempty"`
}
// ErrorRecord ...
type ErrorRecord struct {
// ID - Input document unique identifier the error refers to.
ID *string `json:"id,omitempty"`
// Message - Error message.
Message *string `json:"message,omitempty"`
}
// ErrorResponse ...
type ErrorResponse struct {
Code *string `json:"code,omitempty"`
Message *string `json:"message,omitempty"`
Target *string `json:"target,omitempty"`
InnerError *InternalError `json:"innerError,omitempty"`
}
// Input ...
type Input struct {
// ID - Unique, non-empty document identifier.
ID *string `json:"id,omitempty"`
Text *string `json:"text,omitempty"`
}
// InternalError ...
type InternalError struct {
Code *string `json:"code,omitempty"`
Message *string `json:"message,omitempty"`
InnerError *InternalError `json:"innerError,omitempty"`
}
// KeyPhraseBatchResult ...
type KeyPhraseBatchResult struct {
autorest.Response `json:"-"`
Documents *[]KeyPhraseBatchResultItem `json:"documents,omitempty"`
Errors *[]ErrorRecord `json:"errors,omitempty"`
}
// KeyPhraseBatchResultItem ...
type KeyPhraseBatchResultItem struct {
// KeyPhrases - A list of representative words or phrases. The number of key phrases returned is proportional to the number of words in the input document.
KeyPhrases *[]string `json:"keyPhrases,omitempty"`
// ID - Unique document identifier.
ID *string `json:"id,omitempty"`
}
// LanguageBatchResult ...
type LanguageBatchResult struct {
autorest.Response `json:"-"`
Documents *[]LanguageBatchResultItem `json:"documents,omitempty"`
Errors *[]ErrorRecord `json:"errors,omitempty"`
}
// LanguageBatchResultItem ...
type LanguageBatchResultItem struct {
// ID - Unique document identifier.
ID *string `json:"id,omitempty"`
// DetectedLanguages - A list of extracted languages.
DetectedLanguages *[]DetectedLanguage `json:"detectedLanguages,omitempty"`
}
// MultiLanguageBatchInput ...
type MultiLanguageBatchInput struct {
Documents *[]MultiLanguageInput `json:"documents,omitempty"`
}
// MultiLanguageInput ...
type MultiLanguageInput struct {
// Language - This is the 2 letter ISO 639-1 representation of a language. For example, use "en" for English; "es" for Spanish etc.,
Language *string `json:"language,omitempty"`
// ID - Unique, non-empty document identifier.
ID *string `json:"id,omitempty"`
Text *string `json:"text,omitempty"`
}
// SentimentBatchResult ...
type SentimentBatchResult struct {
autorest.Response `json:"-"`
Documents *[]SentimentBatchResultItem `json:"documents,omitempty"`
Errors *[]ErrorRecord `json:"errors,omitempty"`
}
// SentimentBatchResultItem ...
type SentimentBatchResultItem struct {
// Score - A decimal number between 0 and 1 denoting the sentiment of the document. A score above 0.7 usually refers to a positive document while a score below 0.3 normally has a negative connotation. Mid values refer to neutral text.
Score *float64 `json:"score,omitempty"`
// ID - Unique document identifier.
ID *string `json:"id,omitempty"`
}
@@ -0,0 +1,28 @@
package textanalytics
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/v12.2.0-beta services"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v12.2.0-beta"
}