本文整理汇总了Golang中github.com/Azure/go-autorest/autorest.SendWithSender函数的典型用法代码示例。如果您正苦于以下问题:Golang SendWithSender函数的具体用法?Golang SendWithSender怎么用?Golang SendWithSender使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了SendWithSender函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestDoPollForAsynchronous_ReturnsErrorForLastErrorResponse
func TestDoPollForAsynchronous_ReturnsErrorForLastErrorResponse(t *testing.T) {
// Return error code and message if error present in last response
r1 := newAsynchronousResponse()
r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
r2 := newProvisioningStatusResponse("busy")
r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
r3 := newAsynchronousResponseWithError()
r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
client := mocks.NewSender()
client.AppendResponse(r1)
client.AppendAndRepeatResponse(r2, 2)
client.AppendAndRepeatResponse(r3, 1)
r, err := autorest.SendWithSender(client, mocks.NewRequest(),
DoPollForAsynchronous(time.Millisecond))
expected := makeLongRunningOperationErrorString("InvalidParameter", "tom-service-DISCOVERY-server-base-v1.core.local' is not a valid captured VHD blob name prefix.")
if err.Error() != expected {
t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error message for an unknown error. \n expected=%q \n got=%q",
expected, err.Error())
}
autorest.Respond(r,
autorest.ByClosing())
}
示例2: DoPollForAsynchronous
// DoPollForAsynchronous returns a SendDecorator that polls if the http.Response is for an Azure
// long-running operation. It will delay between requests for the duration specified in the
// RetryAfter header or, if the header is absent, the passed delay. Polling may be canceled by
// closing the optional channel on the http.Request.
func DoPollForAsynchronous(delay time.Duration) autorest.SendDecorator {
return func(s autorest.Sender) autorest.Sender {
return autorest.SenderFunc(func(r *http.Request) (resp *http.Response, err error) {
resp, err = s.Do(r)
if err != nil {
return resp, err
}
ps := pollingState{}
for err == nil {
err = updatePollingState(resp, &ps)
if err != nil {
break
}
if ps.hasTerminated() {
if !ps.hasSucceeded() {
err = ps
}
break
}
r, err = newPollingRequest(resp, ps)
if err != nil {
return resp, err
}
resp, err = autorest.SendWithSender(s, r,
autorest.AfterDelay(autorest.GetRetryAfter(resp, delay)))
}
return resp, err
})
}
}
示例3: TestDoPollForAsynchronous_StopsPollingIfItReceivesAnInvalidOperationResource
func TestDoPollForAsynchronous_StopsPollingIfItReceivesAnInvalidOperationResource(t *testing.T) {
r1 := newAsynchronousResponse()
r2 := newOperationResourceResponse("busy")
r3 := newOperationResourceResponse("busy")
r3.Body = mocks.NewBody(operationResourceIllegal)
r4 := newOperationResourceResponse(operationSucceeded)
client := mocks.NewSender()
client.AppendResponse(r1)
client.AppendAndRepeatResponse(r2, 2)
client.AppendAndRepeatResponse(r3, 1)
client.AppendAndRepeatResponse(r4, 1)
r, err := autorest.SendWithSender(client, mocks.NewRequest(),
DoPollForAsynchronous(time.Millisecond))
if client.Attempts() > 4 {
t.Fatalf("azure: DoPollForAsynchronous failed to stop polling after receiving an invalid OperationResource")
}
if err == nil {
t.Fatalf("azure: DoPollForAsynchronous failed to return an error after receving an invalid OperationResource")
}
autorest.Respond(r,
autorest.ByClosing())
}
示例4: InitiateDeviceAuth
// InitiateDeviceAuth initiates a device auth flow. It returns a DeviceCode
// that can be used with CheckForUserCompletion or WaitForUserCompletion.
func InitiateDeviceAuth(client *autorest.Client, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) {
req, _ := autorest.Prepare(
&http.Request{},
autorest.AsPost(),
autorest.AsFormURLEncoded(),
autorest.WithBaseURL(oauthConfig.DeviceCodeEndpoint.String()),
autorest.WithFormData(url.Values{
"client_id": []string{clientID},
"resource": []string{resource},
}),
)
resp, err := autorest.SendWithSender(client, req)
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err)
}
var code DeviceCode
err = autorest.Respond(
resp,
autorest.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&code),
autorest.ByClosing())
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err)
}
code.ClientID = clientID
code.Resource = resource
code.OAuthConfig = oauthConfig
return &code, nil
}
示例5: TestDoPollForAsynchronous_CanBeCanceled
func TestDoPollForAsynchronous_CanBeCanceled(t *testing.T) {
cancel := make(chan struct{})
delay := 5 * time.Second
r1 := newAsynchronousResponse()
client := mocks.NewSender()
client.AppendResponse(r1)
client.AppendAndRepeatResponse(newOperationResourceResponse("Busy"), -1)
var wg sync.WaitGroup
wg.Add(1)
start := time.Now()
go func() {
req := mocks.NewRequest()
req.Cancel = cancel
wg.Done()
r, _ := autorest.SendWithSender(client, req,
DoPollForAsynchronous(10*time.Second))
autorest.Respond(r,
autorest.ByClosing())
}()
wg.Wait()
close(cancel)
time.Sleep(5 * time.Millisecond)
if time.Since(start) >= delay {
t.Fatalf("azure: DoPollForAsynchronous failed to cancel")
}
}
示例6: TestDoPollForAsynchronous_ReturnsAnUnknownErrorForFailedOperations
func TestDoPollForAsynchronous_ReturnsAnUnknownErrorForFailedOperations(t *testing.T) {
// Return unknown error if error not present in last response
r1 := newAsynchronousResponse()
r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
r2 := newProvisioningStatusResponse("busy")
r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
r3 := newProvisioningStatusResponse(operationFailed)
r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
client := mocks.NewSender()
client.AppendResponse(r1)
client.AppendAndRepeatResponse(r2, 2)
client.AppendAndRepeatResponse(r3, 1)
r, err := autorest.SendWithSender(client, mocks.NewRequest(),
DoPollForAsynchronous(time.Millisecond))
expected := makeLongRunningOperationErrorString("Unknown", "None")
if err.Error() != expected {
t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error message for an unknown error. \n expected=%q \n got=%q",
expected, err.Error())
}
autorest.Respond(r,
autorest.ByClosing())
}
示例7: TestDoPollForAsynchronous_IgnoresUnspecifiedStatusCodes
func TestDoPollForAsynchronous_IgnoresUnspecifiedStatusCodes(t *testing.T) {
client := mocks.NewSender()
r, _ := autorest.SendWithSender(client, mocks.NewRequest(),
DoPollForAsynchronous(time.Duration(0)))
if client.Attempts() != 1 {
t.Fatalf("azure: DoPollForAsynchronous polled for unspecified status code")
}
autorest.Respond(r,
autorest.ByClosing())
}
示例8: TestDoPollForAsynchronous_PollsForSpecifiedStatusCodes
func TestDoPollForAsynchronous_PollsForSpecifiedStatusCodes(t *testing.T) {
client := mocks.NewSender()
client.AppendResponse(newAsynchronousResponse())
r, _ := autorest.SendWithSender(client, mocks.NewRequest(),
DoPollForAsynchronous(time.Millisecond))
if client.Attempts() != 2 {
t.Fatalf("azure: DoPollForAsynchronous failed to poll for specified status code")
}
autorest.Respond(r,
autorest.ByClosing())
}
示例9: refreshInternal
func (spt *ServicePrincipalToken) refreshInternal(resource string) error {
v := url.Values{}
v.Set("client_id", spt.clientID)
v.Set("resource", resource)
if spt.RefreshToken != "" {
v.Set("grant_type", OAuthGrantTypeRefreshToken)
v.Set("refresh_token", spt.RefreshToken)
} else {
v.Set("grant_type", OAuthGrantTypeClientCredentials)
err := spt.secret.SetAuthenticationValues(spt, &v)
if err != nil {
return err
}
}
req, _ := autorest.Prepare(&http.Request{},
autorest.AsPost(),
autorest.AsFormURLEncoded(),
autorest.WithBaseURL(spt.oauthConfig.TokenEndpoint.String()),
autorest.WithFormData(v))
resp, err := autorest.SendWithSender(spt.sender, req)
if err != nil {
return autorest.NewErrorWithError(err,
"azure.ServicePrincipalToken", "Refresh", resp, "Failure sending request for Service Principal %s",
spt.clientID)
}
var newToken Token
err = autorest.Respond(resp,
autorest.WithErrorUnlessOK(),
autorest.ByUnmarshallingJSON(&newToken),
autorest.ByClosing())
if err != nil {
return autorest.NewErrorWithError(err,
"azure.ServicePrincipalToken", "Refresh", resp, "Failure handling response to Service Principal %s request",
spt.clientID)
}
spt.Token = newToken
err = spt.InvokeRefreshCallbacks(newToken)
if err != nil {
// its already wrapped inside InvokeRefreshCallbacks
return err
}
return nil
}
示例10: Refresh
// Refresh obtains a fresh token for the Service Principal.
func (spt *ServicePrincipalToken) Refresh() error {
p := map[string]interface{}{
"tenantID": spt.tenantID,
"requestType": "token",
}
v := url.Values{}
v.Set("client_id", spt.clientID)
v.Set("grant_type", "client_credentials")
v.Set("resource", spt.resource)
err := spt.secret.SetAuthenticationValues(spt, &v)
if err != nil {
return err
}
req, err := autorest.Prepare(&http.Request{},
autorest.AsPost(),
autorest.AsFormURLEncoded(),
autorest.WithBaseURL(oauthURL),
autorest.WithPathParameters(p),
autorest.WithFormData(v))
if err != nil {
return err
}
resp, err := autorest.SendWithSender(spt.sender, req)
if err != nil {
return autorest.NewErrorWithError(err,
"azure.ServicePrincipalToken", "Refresh", "Failure sending request for Service Principal %s",
spt.clientID)
}
var newToken Token
err = autorest.Respond(resp,
autorest.WithErrorUnlessOK(),
autorest.ByUnmarshallingJSON(&newToken),
autorest.ByClosing())
if err != nil {
return autorest.NewErrorWithError(err,
"azure.ServicePrincipalToken", "Refresh", "Failure handling response to Service Principal %s request",
spt.clientID)
}
spt.Token = newToken
return nil
}
示例11: TestDoPollForAsynchronous_ReturnsPollingError
func TestDoPollForAsynchronous_ReturnsPollingError(t *testing.T) {
client := mocks.NewSender()
client.AppendAndRepeatResponse(newAsynchronousResponse(), 5)
client.SetError(fmt.Errorf("Faux Error"))
client.SetEmitErrorAfter(1)
r, err := autorest.SendWithSender(client, mocks.NewRequest(),
DoPollForAsynchronous(time.Millisecond))
if err == nil {
t.Fatalf("azure: DoPollForAsynchronous failed to return error from polling")
}
autorest.Respond(r,
autorest.ByClosing())
}
示例12: CheckForUserCompletion
// CheckForUserCompletion takes a DeviceCode and checks with the Azure AD OAuth endpoint
// to see if the device flow has: been completed, timed out, or otherwise failed
func CheckForUserCompletion(client *autorest.Client, code *DeviceCode) (*Token, error) {
req, _ := autorest.Prepare(
&http.Request{},
autorest.AsPost(),
autorest.AsFormURLEncoded(),
autorest.WithBaseURL(code.OAuthConfig.TokenEndpoint.String()),
autorest.WithFormData(url.Values{
"client_id": []string{code.ClientID},
"code": []string{*code.DeviceCode},
"grant_type": []string{OAuthGrantTypeDeviceCode},
"resource": []string{code.Resource},
}),
)
resp, err := autorest.SendWithSender(client, req)
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err)
}
var token deviceToken
err = autorest.Respond(
resp,
autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusBadRequest),
autorest.ByUnmarshallingJSON(&token),
autorest.ByClosing())
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err)
}
if token.Error == nil {
return &token.Token, nil
}
switch *token.Error {
case "authorization_pending":
return nil, ErrDeviceAuthorizationPending
case "slow_down":
return nil, ErrDeviceSlowDown
case "access_denied":
return nil, ErrDeviceAccessDenied
case "code_expired":
return nil, ErrDeviceCodeExpired
default:
return nil, ErrDeviceGeneric
}
}
示例13: TestDoPollForAsynchronous_ReturnsErrorForFirstPutRequest
func TestDoPollForAsynchronous_ReturnsErrorForFirstPutRequest(t *testing.T) {
// Return 400 bad response with error code and message in first put
r1 := newAsynchronousResponseWithError()
client := mocks.NewSender()
client.AppendResponse(r1)
res, err := autorest.SendWithSender(client, mocks.NewRequest(),
DoPollForAsynchronous(time.Millisecond))
if err != nil {
t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error message for a failed Operations. \n expected=%q \n got=%q",
errorResponse, err.Error())
}
err = autorest.Respond(res,
WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusCreated, http.StatusOK),
autorest.ByClosing())
reqError, ok := err.(*RequestError)
if !ok {
t.Fatalf("azure: returned error is not azure.RequestError: %T", err)
}
expected := &RequestError{
ServiceError: &ServiceError{
Code: "InvalidParameter",
Message: "tom-service-DISCOVERY-server-base-v1.core.local' is not a valid captured VHD blob name prefix.",
},
DetailedError: autorest.DetailedError{
StatusCode: 400,
},
}
if !reflect.DeepEqual(reqError, expected) {
t.Fatalf("azure: wrong error. expected=%q\ngot=%q", expected, reqError)
}
defer res.Body.Close()
b, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
if string(b) != errorResponse {
t.Fatalf("azure: Response body is wrong. got=%q expected=%q", string(b), errorResponse)
}
}
示例14: GetSecret
func (client *VaultClient) GetSecret(vaultName, secretName string) (*Secret, error) {
p := map[string]interface{}{
"secret-name": secretName,
}
q := map[string]interface{}{
"api-version": AzureVaultApiVersion,
}
secretURL := strings.Replace(AzureVaultSecretTemplate, "{vault-name}", vaultName, -1)
req, err := autorest.Prepare(&http.Request{},
autorest.AsGet(),
autorest.WithBaseURL(secretURL),
autorest.WithPathParameters(p),
autorest.WithQueryParameters(q))
if err != nil {
return nil, err
}
resp, err := autorest.SendWithSender(client, req)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf(
"Failed to fetch secret from %s/%s, HTTP status code=%d (%s)",
vaultName,
secretName,
resp.StatusCode,
http.StatusText(resp.StatusCode))
}
var secret Secret
err = autorest.Respond(
resp,
autorest.ByUnmarshallingJSON(&secret))
if err != nil {
return nil, err
}
return &secret, nil
}
示例15: ExampleWithClientID
// Use a Client Inspector to set the request identifier.
func ExampleWithClientID() {
uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6"
req, _ := autorest.Prepare(&http.Request{},
autorest.AsGet(),
autorest.WithBaseURL("https://microsoft.com/a/b/c/"))
c := autorest.Client{Sender: mocks.NewSender()}
c.RequestInspector = WithReturningClientID(uuid)
autorest.SendWithSender(c, req)
fmt.Printf("Inspector added the %s header with the value %s\n",
HeaderClientID, req.Header.Get(HeaderClientID))
fmt.Printf("Inspector added the %s header with the value %s\n",
HeaderReturnClientID, req.Header.Get(HeaderReturnClientID))
// Output:
// Inspector added the x-ms-client-request-id header with the value 71FDB9F4-5E49-4C12-B266-DE7B4FD999A6
// Inspector added the x-ms-return-client-request-id header with the value true
}