GithubHelp home page GithubHelp logo

azure / go-autorest Goto Github PK

View Code? Open in Web Editor NEW
214.0 93.0 174.0 4.5 MB

This package implements an HTTP request pipeline suitable for use across multiple go-routines and provides the shared routines relied on by AutoRest generated Go code.

Home Page: https://github.com/Azure/autorest.go/

License: Apache License 2.0

Go 99.98% Makefile 0.02%

go-autorest's Introduction

NOTE: The modules in this repo will go out of support by March 31, 2023. Additional information can be found here.

go-autorest

GoDoc Build Status Go Report Card

Package go-autorest provides an HTTP request client for use with Autorest-generated API client packages.

An authentication client tested with Azure Active Directory (AAD) is also provided in this repo in the package github.com/Azure/go-autorest/autorest/adal. Despite its name, this package is maintained only as part of the Azure Go SDK and is not related to other "ADAL" libraries in github.com/AzureAD.

Overview

Package go-autorest implements an HTTP request pipeline suitable for use across multiple goroutines and provides the shared routines used by packages generated by Autorest.

The package breaks sending and responding to HTTP requests into three phases: Preparing, Sending, and Responding. A typical pattern is:

  req, err := Prepare(&http.Request{},
    token.WithAuthorization())

  resp, err := Send(req,
    WithLogging(logger),
    DoErrorIfStatusCode(http.StatusInternalServerError),
    DoCloseIfError(),
    DoRetryForAttempts(5, time.Second))

  err = Respond(resp,
		ByDiscardingBody(),
    ByClosing())

Each phase relies on decorators to modify and / or manage processing. Decorators may first modify and then pass the data along, pass the data first and then modify the result, or wrap themselves around passing the data (such as a logger might do). Decorators run in the order provided. For example, the following:

  req, err := Prepare(&http.Request{},
    WithBaseURL("https://microsoft.com/"),
    WithPath("a"),
    WithPath("b"),
    WithPath("c"))

will set the URL to:

  https://microsoft.com/a/b/c

Preparers and Responders may be shared and re-used (assuming the underlying decorators support sharing and re-use). Performant use is obtained by creating one or more Preparers and Responders shared among multiple go-routines, and a single Sender shared among multiple sending go-routines, all bound together by means of input / output channels.

Decorators hold their passed state within a closure (such as the path components in the example above). Be careful to share Preparers and Responders only in a context where such held state applies. For example, it may not make sense to share a Preparer that applies a query string from a fixed set of values. Similarly, sharing a Responder that reads the response body into a passed struct (e.g., ByUnmarshallingJson) is likely incorrect.

Errors raised by autorest objects and methods will conform to the autorest.Error interface.

See the included examples for more detail. For details on the suggested use of this package by generated clients, see the Client described below.

Helpers

Handling Swagger Dates

The Swagger specification (https://swagger.io) that drives AutoRest (https://github.com/Azure/autorest/) precisely defines two date forms: date and date-time. The github.com/Azure/go-autorest/autorest/date package provides time.Time derivations to ensure correct parsing and formatting.

Handling Empty Values

In JSON, missing values have different semantics than empty values. This is especially true for services using the HTTP PATCH verb. The JSON submitted with a PATCH request generally contains only those values to modify. Missing values are to be left unchanged. Developers, then, require a means to both specify an empty value and to leave the value out of the submitted JSON.

The Go JSON package (encoding/json) supports the omitempty tag. When specified, it omits empty values from the rendered JSON. Since Go defines default values for all base types (such as "" for string and 0 for int) and provides no means to mark a value as actually empty, the JSON package treats default values as meaning empty, omitting them from the rendered JSON. This means that, using the Go base types encoded through the default JSON package, it is not possible to create JSON to clear a value at the server.

The workaround within the Go community is to use pointers to base types in lieu of base types within structures that map to JSON. For example, instead of a value of type string, the workaround uses *string. While this enables distinguishing empty values from those to be unchanged, creating pointers to a base type (notably constant, in-line values) requires additional variables. This, for example,

  s := struct {
    S *string
  }{ S: &"foo" }

fails, while, this

  v := "foo"
  s := struct {
    S *string
  }{ S: &v }

succeeds.

To ease using pointers, the subpackage to contains helpers that convert to and from pointers for Go base types which have Swagger analogs. It also provides a helper that converts between map[string]string and map[string]*string, enabling the JSON to specify that the value associated with a key should be cleared. With the helpers, the previous example becomes

  s := struct {
    S *string
  }{ S: to.StringPtr("foo") }

Install

go get github.com/Azure/go-autorest/autorest
go get github.com/Azure/go-autorest/autorest/azure
go get github.com/Azure/go-autorest/autorest/date
go get github.com/Azure/go-autorest/autorest/to

Using with Go Modules

In v12.0.1, this repository introduced the following modules.

  • autorest/adal
  • autorest/azure/auth
  • autorest/azure/cli
  • autorest/date
  • autorest/mocks
  • autorest/to
  • autorest/validation
  • autorest
  • logger
  • tracing

Tagging cumulative SDK releases as a whole (e.g. v12.3.0) is still enabled to support consumers of this repo that have not yet migrated to modules.

License

See LICENSE file.


This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

go-autorest's People

Contributors

ahmetb avatar alexeldeib avatar allencloud avatar berndverst avatar boumenot avatar brendandixon avatar colemickens avatar dependabot[bot] avatar devigned avatar garimakhulbe02 avatar jhendrixmsft avatar jkapil avatar karataliu avatar marstr avatar mbfrahry avatar mcardosos avatar metacpp avatar nicocesar avatar nirusu avatar paulmey avatar phillebaba avatar radhikagupta5 avatar samkreter avatar scott-the-programmer avatar serbrech avatar seyadava avatar stiviik avatar testwill avatar thajeztah avatar tombuildsstuff avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-autorest's Issues

Store RetryAfter for subsequent requests

While investigating a bug that wound up simply being NRP taking 3 minutes to update a NIC... I noticed a different bug in the Azure SDK for Go:

  1. T=0: PUT operation to update NIC (async response)
  2. T=10: GET on operation status (in progress)
  3. T=70: GET on operation status (in progress)
  4. T=130: GET on operation status (in progress)
  5. T=190: GET on operation status (success)

Problem is, first response includes RetryAfter, but the responses from GET operation status do not include the header.

Proposed: stash the RetryAfter from the initial PUT and use that as a fallback before the Client's DefaultPollingInterval.

cc: @brendandixon for thoughts on if this is okay, or if the polling needs to backoff, even though the API said to retryafter a certain interval.

Add support for AAD v2 in adal package

I am creating this issue to collect your thoughts about AAD v2. The current implementation supports AAD v1, but would be nice to have some support for v2 which implements the OIDC specs.

https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-compare

I am not sure if there are any particularities in AAD v2, or one can use an exiting Go package such as https://github.com/coreos/go-oidc to acquire an id_token.

cc @colemickens @marstr

NewClientWithUserAgent changes DefaultClient

DefaultClient = Client{PollingMode: PollUntilDuration, PollingDuration: DefaultPollingDuration}

and

func NewClientWithUserAgent(ua string) Client {
c := DefaultClient
c.UserAgent = ua
return c
}

I feel like if this method gets called multiple times with different userAgent strings, they will all have the same user agent string. The solution might be GetDefaultClient() that returns a client.

Polling should be case-insensitive

๐Ÿ‘‹

We're provisioning a Search Service through the Azure SDK for Go - and have noticed since ~mid July that the deployment times have been increasing.

Upon further investigation - it appears that AutoRest doesn't handle the provisioningState field being lower-case - as is the case in the Search Service API:

After sending this request:

{
	"location": "westeurope",
	"tags": {
		"database": "test",
		"environment": "staging"
	},
	"properties": {},
	"sku": {
		"name": "standard"
	}
}

and polling:

{
	"id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tharvey-dev2/providers/Microsoft.Search/searchServices/tharveysearch",
	"name": "tharveysearch",
	"type": "Microsoft.Search/searchServices",
	"location": "West Europe",
	"tags": {
		"database": "test",
		"environment": "staging"
	},
	"properties": {
		"replicaCount": 1,
		"partitionCount": 1,
		"status": "provisioning",
		"statusDetails": "",
		"provisioningState": "provisioning",
		"hostingMode": "Default"
	},
	"sku": {
		"name": "standard"
	}
}

which, eventually returns the following:

{
	"id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tharvey-dev2/providers/Microsoft.Search/searchServices/tharveysearch",
	"name": "tharveysearch",
	"type": "Microsoft.Search/searchServices",
	"location": "West Europe",
	"tags": {
		"database": "test",
		"environment": "staging"
	},
	"properties": {
		"replicaCount": 1,
		"partitionCount": 1,
		"status": "running",
		"statusDetails": "",
		"provisioningState": "succeeded",
		"hostingMode": "Default"
	},
	"sku": {
		"name": "standard"
	}
}

However the SDK continues polling indefinitely (see below, the first successful response is highlighted):

screen shot 2017-11-13 at 15 44 51

Upon updating this line to be lower-case and rebuilding - the SDK appears to work as expected.

As such - would it be possible to update AutoRest to allow this field to be case insensitive?

On a related note - it appears the Portal is shying users away from creating new Search Services - is it Deprecated / EOL'd? Screenshot from the Portal - which appears to be applicable in every region:

screen shot 2017-11-13 at 15 13 02

Thanks!

Consolidate default http.Client

I started seeing multiple http.Client{}s around the codebase, it's not immediately clear to me how we can consolidate these.

I just had to add a custom http.Transport setting to 3 different places to change the behavior.

User should be able to set a HTTP client in a single place to be used in all requests.

@brendandixon

USGovernment's Resource Management Endpoint is Wrong

{
    "error": {
        "code": "InvalidAuthenticationTokenAudience",
        "message": "The access token has been obtained from wrong audience or resource 'https://management.usgovcloudapi.net'. It should exactly match (including forward slash) with one of the allowed audiences 'https://management.core.usgovcloudapi.net/','https://management.usgovcloudapi.net/'."
    }
}

The fix is to add a trailing '/'. ๐Ÿ‘ I'll send a PR.

Get rid of hard dependency on access token path

The current implementation of AccessTokensPath in go-autorest have very strong dependency on its path, we want to get rid of hard dependency here. az login might be a good solution here.

azure stack support

Hi,
Have you ever tried adal on azure stack env? I have been using adal in azure stack env, trying to use service principal connecting to azure stack, while I always got below error:
2017/08/04 07:40:17 Error: azure.BearerAuthorizer#WithAuthorization: Failed to refresh the Token for request to https://adminmanagement.local.azurestack.external/subscriptions/a3368291-e427-41b0-b790-66b7be21017b/providers/Microsoft.Storage/checkNameAvailability?api-version=2015-06-15: StatusCode=0 -- Original Error: adal: Refresh request failed. Status Code = '400'

And then If I comment out below line in adal, it would proceed.

https://github.com/Azure/go-autorest/blob/master/autorest/adal/token.go#L373

Unable to acquire new refresh token

I'm unsure if this is the right place to log this issue, but I'm experimenting with the recently announced configurable token lifetimes feature in AAD. The purpose is to enforce an idle timeout for Kubernetes (kubectl) users so that they must re-authenticate to Azure after a given amount of idle time. In our scenario, we have OIDC enabled in Kubernetes and we're finding developers are sharing their config files (despite being told not to). We're looking to (partially) mitigate this by enforcing more frequent authentications.

To achieve this, I'm setting the "Refresh Token Max Inactive Time" property in a custom policy and linking it to the AAD object that represents the k8s API. When this policy is active, kubectl is unable to re-authenticate the user and acquire a new refresh token after the idle timeout period is reached:

E1116 09:51:11.431092 3771 azure.go:126] Failed to acquire a token: refreshing the expired token: refreshing token: adal: Refresh request failed. Status Code = '400' Unable to connect to the server: acquiring a token for authorization header: refreshing the expired token: refreshing token: adal: Refresh request failed. Status Code = '400'

I suppose this could be a issue related to AAD, the ADAL Go library, or even the kubectl plug-in for Azure. I'm looking for guidance as to where this issue would best be reported and what further information I can provide.

Expose authorization response error code for better debugging

We are doing ARM calls with AAD service principal authorization

This could fail with authentication. Right now the returned error has information like below:
autorest#WithErrorUnlessStatusCode: POST https://login.microsoftonline.com/xxxxxxxxx/oauth2/token?api-version=1.0 failed with 400 Bad Request: StatusCode=400

autorest#WithErrorUnlessStatusCode: POST https://login.microsoftonline.com/xxxxxxxxx/oauth2/token?api-version=1.0 failed with 401 Unauthorized: StatusCode=401

However there are many reasons that Graph API can give you 400. Is it possible to expose the additional error code from the response?

azure: Request inspection missing for polling requests

I have a request/response inspector set on the client that prints every request/response. For Azure long-running operations the inspection for the polling "requests" is missing (but their response is inspected just fine):

so the request of the last response is missing.

What does the 'dev' branch mean exactly?

Or is it just to stage up breaking changes so they can be released together to avoid churn?

I ask, because I'm adding MSI because I need it for Kubernetes. I can't consume a non-master branch of go-autorest in Kubernetes so I need to be able to reason about when 'dev' will get merged into 'master'.

Thanks!

Install for azure-sdk-for-go fails

many of the packages that are for azure-sdk-for-go fail because it's trying to send 2 arguments to a func that receives only one.

Azure/azure-sdk-for-go/arm/network/applicationgateways.go:103: too many arguments in call to azure.DoPollForAsynchronous

applicationgateways.go: 103:
azure.DoPollForAsynchronous(autorest.DefaultPollingDuration,
autorest.DefaultPollingDelay))

async.go:
func DoPollForAsynchronous(delay time.Duration) autorest.SendDecorator {

Recent Refactoring to Long Running Operations

๐Ÿ‘‹

I've seen this recent PR which changes the way that Long Running Operations are handled, such that it effectively removes the polling support from the SDK and instead pushed that onto consumers of the SDK.

Within Terraform, we rely pretty heavily on the automatic polling available within the Go SDK - as such I'm concerned that removing these methods will lead to a considerable increase in code (and thus complexity) for us - when currently this is one of the major benefits of using the Go SDK over when we used to use the Riviera SDK.

As such - are there any plans around to expose a polling method available within the SDK to preserve the current behaviour? I can certainly see the desire for the SDK to return the current state - however polling until the resource is ready is also a really handy function of the SDK at this point :)

Thanks!

JSON unmarshaling does not cope with byte-order mark

I sometimes see an error like this:

error response cannot be parsed: "\ufeff{\"odata.error\":{\"code\":\"Request_MultipleObjectsWithSameKeyValue\",\"message\":{\"lang\":\"en\",\"value\":\"Another object with the same value for property servicePrincipalNames already exists.\"},\"requestId\":\"46a97035-e286-4d41-8eee-ae33de2f0288\",\"date\":\"2017-01-18T12:31:21\"}}" error: invalid character 'รฏ' looking for beginning of value

It looks like the error response from Azure sometimes contains a byte-order mark that Go's JSON decoder does not like. It should probably be trimmed before parsing.

make DefaultPollingDelay non-const

autorest/client.go:

image

Some RPs (for some endpoints) drop the Retry-After header and they actually return an Azure-AsyncOperation header even though the operation was completed (response body actually has field "provisioningStatus": "succeeded").

Just because they return the header anyway and omit Retry-After we wait full 60 seconds doing nothing. This especially impacts docker-machine user experience and puts us behind. During a docker-machine creation, we wait full 60 seconds about 3-4 times (so losing 3-4 minutes for nothing). I'd love to set this to 10 or 15 seconds if it was possible.

@brendandixon is it ok to make this field a var, not a const?

Add support for OAuth2 authorization flow

I need to authorize clients with standard OAuth2 authorization flow. It seems that only secret, certificate and device flows are supported now. For example, other SDKs have
AcquireTokenWithAuthorizationCode method. Any plans to support it?

New release tag?

Any chance we could get a newer release tag with some of the updates that have hit master since v0.1-alpha? ๐Ÿ˜„

German vs. Germany vs. China vs. Chinese

There's a disagreement on naming style for the various clouds.

We have AzureGermanCloud and AzureChinaCloud. It seems more appropriate for German to be Germany.

The Azure XPlat CLI does the same thing.

error format seems to have changed

When I make a request to the Azure API that returns an error,
I see a response like this:

{"odata.error":{"code":"Request_ResourceNotFound","message":{"lang":"en","value":"Resource not found for the segment 'me'."}}}

This ends up producing an error like:

graphrbac.ObjectsClient#GetCurrentUser: Failure responding to request: StatusCode=404 -- Original Error: autorest/azure: Service returned an error. Status=404 Code="Unknown" Message="Unknown service error"

because azure.ServiceError does not define the correct response type.

Validation is overly strict and causing problems

See here: Azure/acs-engine#194 (comment)

We got new validation code in the latest version of the SDK. When we upgraded in Kubernetes, it broke a core scenario - being able to create load balancers.

Error message:
servicecontroller.go:760] Failed to process service. Retrying in 1m20s: Failed to create load balancer for service default/nginx: network.SecurityGroupsClient#CreateOrUpdate: Invalid input: autorest/validation: validation failed: parameter=parameters.SecurityGroupPropertiesFormat.Subnets constraint=ReadOnly value=[]network.Subnet{network.Subnet{Response:autorest.Response{Response:(*http.Response)(nil)}, ID:(*string)(0xc4228be160), SubnetPropertiesFormat:(*network.SubnetPropertiesFormat)(nil), Name:(*string)(nil), Etag:(*string)(nil)}} details: readonly parameter; must send as nil or empty in request

Not sure what the recommended course of action here is. I'm not 100% up on what these validations do... but I know they're blocking a scenario that was perfectly functional before.

Further, discussion of PUT semantics today imply that such fields must be submitted, but simply shouldn't be changed (which is not something client SDK validation should be checking).

cc: @brendandburns

Polling seems broken for group template deployments

I'm getting azure:newPollingRequest 0 Azure Polling Error - Unable to obtain polling URI for GET.

The initial PUT get's a response that includes the Azure-AsyncOperation header. It waits for the next poll. On the next poll, it does a GET to the url specified in Azure-AsyncOperation header returned from the PUT.

The response to the GET for the operation status looks like this. There are no relevant async headers.

{
    "status": "Running"
}

go-autorest: 55fe4db
azure-sdk-for-go: be84778f55e21fa9fa5e6964de5332d8f04d3df1

Fedora 25 - go test: FAIL: TestVersion

cat /etc/redhat-release  
#Fedora release 25 (Twenty Five)
dnf -y install "compiler(go-compiler)"

go version
#go version go1.7.5 linux/amd64

dnf -y install "golang(github.com/Masterminds/semver)"
dnf -y install "golang(github.com/dgrijalva/jwt-go)"
dnf -y install "golang(github.com/stretchr/testify/require)"

mkdir -p /tmp/go/src
export GOPATH=/tmp/go:/usr/share/gocode
cd /tmp/go/src
mkdir -p github.com/Azure
cd github.com/Azure
git clone http://github.com/Azure/go-autorest
cd go-autorest/autorest
git rev-parse HEAD
# ec5f4903f77ed9927ac95b19ab8e44ada64c1356
go test 
#--- FAIL: TestVersion (0.00s)
#       version_test.go:22: Declared Version: 7.3.0
#       version_test.go:31: Current Release Version: 7.3.0
#       version_test.go:34: autorest: Assertion that the Declared version is greater than Current Release Version failed 7.3.0 7.3.0
#FAIL
#exit status 1

Broke the cookie jar

And ate the cookies.
A new client and cookie jar are created everytime the autorest.Client Do() implementation is executed. However, as the retries have been moved out of Do(), they no longer benefit from the cookie jar.
Some acceptance tests in https://github.com/Azure/autorest.go depend on cookies.

Generalized Support for Azure Stack

@colemickens - I would like your opinion on this.

We've had a request from the Packer community to support Azure Stack. My thinking is that the user of Packer creates a JSON document detailing their Environment. Packer can then deserializes the JSON, and the code has an Environment instance appropriate to them. I think the only change I have to on make is to add the appropriate annotations on the existing Environment type. Does this make sense? If so, I will prepare a PR with the change.

adal.NewServicePrincipalToken fails when PublicCloud.KeyVaultEndpoint is used as scope

Hi azure sdk team

I found an issue when using the keyvault client. I created a service principal with this line

spToken, err := adal.NewServicePrincipalToken(*oauthConfig, sp.ID, sp.Password, env.KeyVaultEndpoint)

Note that when env is PublicCloud, it would resolve to https://vault.azure.net/

KeyVaultEndpoint: "https://vault.azure.net/",

The back slash at the end of the URL is causing trouble and will cause an error like this when the code is run

keyvault.ManagementClient#GetKey: Failure responding to request: StatusCode=401 -- Original Error: autorest/azure: error response cannot be parsed: "" error: EOF

Removing the back slash as the end like this https://vault.azure.net works

How is token auth working right now?

I realize there's some irony in me having written some of this, but I'm confused how cert auth is working at all. Or at least in any scenario that requires refreshing...

As far as I can tell, in refreshInternal it always sets the grant_type to client_credentials even if a cert is used... I'm shocked this is working for cert cases (but it is because @jkapil uses it...)

We should probably set the grant_type inside SetAuthValues as we do for the other fields... But still... how is this working?

cc: @jkapil @Cosmincojocar

move ./autorest/** to .

The extra /autorest/ segment in the go import path hierarchy does not make sense, if we do not any use case for that we should probably eventually get rid of it.

It will be a breaking change but customers must be using some vending solution by now.

Unable to use KeyVaultEndpoint as AAD auth resource endpoint

As of

KeyVaultEndpoint: "https://vault.azure.net/",

The KeyVaultEndpoint is https://vault.azure.net/

If using that KeyVaultEndpoint as AAD's resource, following https://github.com/Azure/go-autorest/blob/master/autorest/azure/example/main.go#L86

It result in 401 response with following header:

Www-Authenticate:[Bearer authorization="https://login.windows.net/xxx", resource="https://vault.azure.net"]

If manually specify https://vault.azure.net (no tailing slash), the request will succeed.

See also:
https://github.com/Azure/azure-sdk-for-python/blob/5e51e1f4a404f8c1d87227da14a68ca924bc180c/doc/sample_azure-keyvault.rst

Adding the tailing slash makes the endpoints consistent, but then the SDK it's not usable. User has to manually tune those endpoints, and it does not make sense for multi-cloud environments.

Shall we ask the service to accept the ending slash, or change the SDK?

Test tries to access the network

Hi!

While all other tests use mocks correctly to avoid depending on DNS or connectivity to the internet, TestClientDoSetsUserAgent is missing such mock, and triggers a DNS query (this is a bug in Debian). This small patch fixes that:

--- a/autorest/client_test.go
+++ b/autorest/client_test.go
@@ -151,6 +151,8 @@
    ua := "UserAgent"
    c := Client{UserAgent: ua}
    r := mocks.NewRequest()
+   s := mocks.NewSender()
+   c.Sender = s

    c.Do(r)

Should WithPathParameters Automatically Handle Encoding?

The code today expects the called to encode any path parameters ahead of time. Is it more reasonable for the WithPathParameters to do so. I tend to think so, but there may be valid reasons not to.

Thoughts?

       p := map[string]interface{}{
        "secret-name": autorest.Encode("path", secretName),
    }
    q := map[string]interface{}{
        "api-version": AzureVaultApiVersion,
    }

    req, err := autorest.Prepare(
        &http.Request{},
        autorest.AsGet(),
        autorest.WithBaseURL(client.getVaultUrl(vaultName)),
        autorest.WithPathParameters("/secrets/{secret-name}", p),
        autorest.WithQueryParameters(q))

cc: @paulmey source issue

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.