From f26409ddd8ab8626e8b8af74e4e786c219d088eb Mon Sep 17 00:00:00 2001 From: buglloc Date: Wed, 6 Mar 2024 11:51:34 +0300 Subject: [PATCH] Revert commit rXXXXXX, bump github.com/go-resty/resty/v2 to v2.11.1-0.20240219012510-97187c431cf6 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Отломился клиент(?) к облачному соломону, откатываем как минимум до фикса https://github.com/go-resty/resty/pull/782 c781336fe418f46d4bdcc18f806f21abfb00aeee --- vendor/github.com/go-resty/resty/v2/client.go | 289 +---- .../go-resty/resty/v2/client_test.go | 240 +--- .../go-resty/resty/v2/context_test.go | 2 +- vendor/github.com/go-resty/resty/v2/digest.go | 295 ----- .../go-resty/resty/v2/example_test.go | 6 +- .../go-resty/resty/v2/gotest/ya.make | 5 +- .../go-resty/resty/v2/middleware.go | 332 +++--- .../go-resty/resty/v2/middleware_test.go | 1061 ----------------- .../github.com/go-resty/resty/v2/redirect.go | 13 +- .../github.com/go-resty/resty/v2/request.go | 188 +-- .../go-resty/resty/v2/request_test.go | 245 +--- .../github.com/go-resty/resty/v2/response.go | 18 +- vendor/github.com/go-resty/resty/v2/resty.go | 4 +- .../go-resty/resty/v2/resty_test.go | 185 +-- vendor/github.com/go-resty/resty/v2/retry.go | 5 +- .../go-resty/resty/v2/retry_test.go | 28 +- vendor/github.com/go-resty/resty/v2/trace.go | 2 +- .../github.com/go-resty/resty/v2/transport.go | 5 +- .../go-resty/resty/v2/transport_other.go | 17 - vendor/github.com/go-resty/resty/v2/util.go | 33 +- .../github.com/go-resty/resty/v2/util_test.go | 46 +- vendor/github.com/go-resty/resty/v2/ya.make | 7 +- 22 files changed, 368 insertions(+), 2658 deletions(-) delete mode 100644 vendor/github.com/go-resty/resty/v2/digest.go delete mode 100644 vendor/github.com/go-resty/resty/v2/middleware_test.go delete mode 100644 vendor/github.com/go-resty/resty/v2/transport_other.go diff --git a/vendor/github.com/go-resty/resty/v2/client.go b/vendor/github.com/go-resty/resty/v2/client.go index 446ba8517527..326a4a578d47 100644 --- a/vendor/github.com/go-resty/resty/v2/client.go +++ b/vendor/github.com/go-resty/resty/v2/client.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -14,10 +14,10 @@ import ( "errors" "fmt" "io" + "io/ioutil" "math" "net/http" "net/url" - "os" "reflect" "regexp" "strings" @@ -55,15 +55,13 @@ var ( hdrContentLengthKey = http.CanonicalHeaderKey("Content-Length") hdrContentEncodingKey = http.CanonicalHeaderKey("Content-Encoding") hdrLocationKey = http.CanonicalHeaderKey("Location") - hdrAuthorizationKey = http.CanonicalHeaderKey("Authorization") - hdrWwwAuthenticateKey = http.CanonicalHeaderKey("WWW-Authenticate") plainTextType = "text/plain; charset=utf-8" jsonContentType = "application/json" formContentType = "application/x-www-form-urlencoded" - jsonCheck = regexp.MustCompile(`(?i:(application|text)/(.*json.*)(;|$))`) - xmlCheck = regexp.MustCompile(`(?i:(application|text)/(.*xml.*)(;|$))`) + jsonCheck = regexp.MustCompile(`(?i:(application|text)/(json|.*\+json|json\-.*)(;|$))`) + xmlCheck = regexp.MustCompile(`(?i:(application|text)/(xml|.*\+xml)(;|$))`) hdrUserAgentValue = "go-resty/" + Version + " (https://github.com/go-resty/resty)" bufPool = &sync.Pool{New: func() interface{} { return &bytes.Buffer{} }} @@ -103,7 +101,6 @@ type Client struct { QueryParam url.Values FormData url.Values PathParams map[string]string - RawPathParams map[string]string Header http.Header UserInfo *User Token string @@ -129,30 +126,27 @@ type Client struct { // value when `SetAuthToken` option is used. HeaderAuthorizationKey string - jsonEscapeHTML bool - setContentLength bool - closeConnection bool - notParseResponse bool - trace bool - debugBodySizeLimit int64 - outputDirectory string - scheme string - log Logger - httpClient *http.Client - proxyURL *url.URL - beforeRequest []RequestMiddleware - udBeforeRequest []RequestMiddleware - udBeforeRequestLock sync.RWMutex - preReqHook PreRequestHook - successHooks []SuccessHook - afterResponse []ResponseMiddleware - afterResponseLock sync.RWMutex - requestLog RequestLogCallback - responseLog ResponseLogCallback - errorHooks []ErrorHook - invalidHooks []ErrorHook - panicHooks []ErrorHook - rateLimiter RateLimiter + jsonEscapeHTML bool + setContentLength bool + closeConnection bool + notParseResponse bool + trace bool + debugBodySizeLimit int64 + outputDirectory string + scheme string + log Logger + httpClient *http.Client + proxyURL *url.URL + beforeRequest []RequestMiddleware + udBeforeRequest []RequestMiddleware + preReqHook PreRequestHook + successHooks []SuccessHook + afterResponse []ResponseMiddleware + requestLog RequestLogCallback + responseLog ResponseLogCallback + errorHooks []ErrorHook + invalidHooks []ErrorHook + panicHooks []ErrorHook } // User type is to hold an username and password information @@ -328,7 +322,7 @@ func (c *Client) SetQueryParams(params map[string]string) *Client { } // SetFormData method sets Form parameters and their values in the client instance. -// It's applicable only HTTP method `POST` and `PUT` and request content type would be set as +// It's applicable only HTTP method `POST` and `PUT` and requets content type would be set as // `application/x-www-form-urlencoded`. These form data will be added to all the request raised from // this client instance. Also it can be overridden at request level form data. // @@ -353,7 +347,7 @@ func (c *Client) SetFormData(data map[string]string) *Client { // // client.SetBasicAuth("go-resty", "welcome") // -// This basic auth information gets added to all the request raised from this client instance. +// This basic auth information gets added to all the request rasied from this client instance. // Also it can be overridden or set one at the request level is supported. // // See `Request.SetBasicAuth`. @@ -371,7 +365,7 @@ func (c *Client) SetBasicAuth(username, password string) *Client { // // client.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") // -// This auth token gets added to all the requests raised from this client instance. +// This auth token gets added to all the requests rasied from this client instance. // Also it can be overridden or set one at the request level is supported. // // See `Request.SetAuthToken`. @@ -388,7 +382,7 @@ func (c *Client) SetAuthToken(token string) *Client { // // client.SetAuthScheme("OAuth") // -// This auth scheme gets added to all the requests raised from this client instance. +// This auth scheme gets added to all the requests rasied from this client instance. // Also it can be overridden or set one at the request level is supported. // // Information about auth schemes can be found in RFC7235 which is linked to below @@ -403,49 +397,19 @@ func (c *Client) SetAuthScheme(scheme string) *Client { return c } -// SetDigestAuth method sets the Digest Access auth scheme for the client. If a server responds with 401 and sends -// a Digest challenge in the WWW-Authenticate Header, requests will be resent with the appropriate Authorization Header. -// -// For Example: To set the Digest scheme with user "Mufasa" and password "Circle Of Life" -// -// client.SetDigestAuth("Mufasa", "Circle Of Life") -// -// Information about Digest Access Authentication can be found in RFC7616: -// -// https://datatracker.ietf.org/doc/html/rfc7616 -// -// See `Request.SetDigestAuth`. -func (c *Client) SetDigestAuth(username, password string) *Client { - oldTransport := c.httpClient.Transport - c.OnBeforeRequest(func(c *Client, _ *Request) error { - c.httpClient.Transport = &digestTransport{ - digestCredentials: digestCredentials{username, password}, - transport: oldTransport, - } - return nil - }) - c.OnAfterResponse(func(c *Client, _ *Response) error { - c.httpClient.Transport = oldTransport - return nil - }) - return c -} - // R method creates a new request instance, its used for Get, Post, Put, Delete, Patch, Head, Options, etc. func (c *Client) R() *Request { r := &Request{ - QueryParam: url.Values{}, - FormData: url.Values{}, - Header: http.Header{}, - Cookies: make([]*http.Cookie, 0), - PathParams: map[string]string{}, - RawPathParams: map[string]string{}, - Debug: c.Debug, + QueryParam: url.Values{}, + FormData: url.Values{}, + Header: http.Header{}, + Cookies: make([]*http.Cookie, 0), client: c, multipartFiles: []*File{}, multipartFields: []*MultipartField{}, - jsonEscapeHTML: c.jsonEscapeHTML, + PathParams: map[string]string{}, + jsonEscapeHTML: true, log: c.log, } return r @@ -457,9 +421,9 @@ func (c *Client) NewRequest() *Request { return c.R() } -// OnBeforeRequest method appends a request middleware into the before request chain. -// The user defined middlewares get applied before the default Resty request middlewares. -// After all middlewares have been applied, the request is sent from Resty to the host server. +// OnBeforeRequest method appends request middleware into the before request chain. +// Its gets applied after default Resty request middlewares and before request +// been sent from Resty to host server. // // client.OnBeforeRequest(func(c *resty.Client, r *resty.Request) error { // // Now you have access to Client and Request instance @@ -468,17 +432,13 @@ func (c *Client) NewRequest() *Request { // return nil // if its success otherwise return error // }) func (c *Client) OnBeforeRequest(m RequestMiddleware) *Client { - c.udBeforeRequestLock.Lock() - defer c.udBeforeRequestLock.Unlock() - c.udBeforeRequest = append(c.udBeforeRequest, m) - return c } // OnAfterResponse method appends response middleware into the after response chain. // Once we receive response from host server, default Resty response middleware -// gets applied and then user assigned response middlewares applied. +// gets applied and then user assigened response middlewares applied. // // client.OnAfterResponse(func(c *resty.Client, r *resty.Response) error { // // Now you have access to Client and Response instance @@ -487,11 +447,7 @@ func (c *Client) OnBeforeRequest(m RequestMiddleware) *Client { // return nil // if its success otherwise return error // }) func (c *Client) OnAfterResponse(m ResponseMiddleware) *Client { - c.afterResponseLock.Lock() - defer c.afterResponseLock.Unlock() - c.afterResponse = append(c.afterResponse, m) - return c } @@ -508,7 +464,7 @@ func (c *Client) OnAfterResponse(m ResponseMiddleware) *Client { // }) // // Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one -// set will be invoked for each call to Request.Execute() that completes. +// set will be invoked for each call to Request.Execute() that comletes. func (c *Client) OnError(h ErrorHook) *Client { c.errorHooks = append(c.errorHooks, h) return c @@ -518,35 +474,29 @@ func (c *Client) OnError(h ErrorHook) *Client { // succeeds. This is called after all retries have been attempted (if any). // // Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one -// set will be invoked for each call to Request.Execute() that completes. -// -// Since v2.8.0 +// set will be invoked for each call to Request.Execute() that comletes. func (c *Client) OnSuccess(h SuccessHook) *Client { c.successHooks = append(c.successHooks, h) return c } -// OnInvalid method adds a callback that will be run whenever a request execution +// OnInvalid method adds a callback that will be run whever a request execution // fails before it starts because the request is invalid. // // Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one -// set will be invoked for each call to Request.Execute() that completes. -// -// Since v2.8.0 +// set will be invoked for each call to Request.Execute() that comletes. func (c *Client) OnInvalid(h ErrorHook) *Client { c.invalidHooks = append(c.invalidHooks, h) return c } -// OnPanic method adds a callback that will be run whenever a request execution +// OnPanic method adds a callback that will be run whever a request execution // panics. // // Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one // set will be invoked for each call to Request.Execute() that completes. // If an OnSuccess, OnError, or OnInvalid callback panics, then the exactly // one rule can be violated. -// -// Since v2.8.0 func (c *Client) OnPanic(h ErrorHook) *Client { c.panicHooks = append(c.panicHooks, h) return c @@ -555,7 +505,7 @@ func (c *Client) OnPanic(h ErrorHook) *Client { // SetPreRequestHook method sets the given pre-request function into resty client. // It is called right before the request is fired. // -// Note: Only one pre-request hook can be registered. Use `client.OnBeforeRequest` for multiple. +// Note: Only one pre-request hook can be registered. Use `client.OnBeforeRequest` for mutilple. func (c *Client) SetPreRequestHook(h PreRequestHook) *Client { if c.preReqHook != nil { c.log.Warnf("Overwriting an existing pre-request hook: %s", functionName(h)) @@ -569,8 +519,6 @@ func (c *Client) SetPreRequestHook(h PreRequestHook) *Client { // For `Response` it logs information such as Status, Response Time, Headers, Body if it has one. // // client.SetDebug(true) -// -// Also it can be enabled at request level for particular request, see `Request.SetDebug`. func (c *Client) SetDebug(d bool) *Client { c.Debug = d return c @@ -665,7 +613,7 @@ func (c *Client) SetError(err interface{}) *Client { return c } -// SetRedirectPolicy method sets the client redirect policy. Resty provides ready to use +// SetRedirectPolicy method sets the client redirect poilicy. Resty provides ready to use // redirect policies. Wanna create one for yourself refer to `redirect.go`. // // client.SetRedirectPolicy(FlexibleRedirectPolicy(20)) @@ -724,42 +672,6 @@ func (c *Client) SetRetryAfter(callback RetryAfterFunc) *Client { return c } -// SetJSONMarshaler method sets the JSON marshaler function to marshal the request body. -// By default, Resty uses `encoding/json` package to marshal the request body. -// -// Since v2.8.0 -func (c *Client) SetJSONMarshaler(marshaler func(v interface{}) ([]byte, error)) *Client { - c.JSONMarshal = marshaler - return c -} - -// SetJSONUnmarshaler method sets the JSON unmarshaler function to unmarshal the response body. -// By default, Resty uses `encoding/json` package to unmarshal the response body. -// -// Since v2.8.0 -func (c *Client) SetJSONUnmarshaler(unmarshaler func(data []byte, v interface{}) error) *Client { - c.JSONUnmarshal = unmarshaler - return c -} - -// SetXMLMarshaler method sets the XML marshaler function to marshal the request body. -// By default, Resty uses `encoding/xml` package to marshal the request body. -// -// Since v2.8.0 -func (c *Client) SetXMLMarshaler(marshaler func(v interface{}) ([]byte, error)) *Client { - c.XMLMarshal = marshaler - return c -} - -// SetXMLUnmarshaler method sets the XML unmarshaler function to unmarshal the response body. -// By default, Resty uses `encoding/xml` package to unmarshal the response body. -// -// Since v2.8.0 -func (c *Client) SetXMLUnmarshaler(unmarshaler func(data []byte, v interface{}) error) *Client { - c.XMLUnmarshal = unmarshaler - return c -} - // AddRetryCondition method adds a retry condition function to array of functions // that are checked to determine if the request is retried. The request will // retry if any of the functions return true and error is nil. @@ -812,7 +724,7 @@ func (c *Client) SetRetryResetReaders(b bool) *Client { // // Note: This method overwrites existing `TLSClientConfig`. func (c *Client) SetTLSClientConfig(config *tls.Config) *Client { - transport, err := c.Transport() + transport, err := c.transport() if err != nil { c.log.Errorf("%v", err) return c @@ -829,7 +741,7 @@ func (c *Client) SetTLSClientConfig(config *tls.Config) *Client { // // Refer to godoc `http.ProxyFromEnvironment`. func (c *Client) SetProxy(proxyURL string) *Client { - transport, err := c.Transport() + transport, err := c.transport() if err != nil { c.log.Errorf("%v", err) return c @@ -850,7 +762,7 @@ func (c *Client) SetProxy(proxyURL string) *Client { // // client.RemoveProxy() func (c *Client) RemoveProxy() *Client { - transport, err := c.Transport() + transport, err := c.transport() if err != nil { c.log.Errorf("%v", err) return c @@ -875,7 +787,7 @@ func (c *Client) SetCertificates(certs ...tls.Certificate) *Client { // // client.SetRootCertificate("/path/to/root/pemFile.pem") func (c *Client) SetRootCertificate(pemFilePath string) *Client { - rootPemData, err := os.ReadFile(pemFilePath) + rootPemData, err := ioutil.ReadFile(pemFilePath) if err != nil { c.log.Errorf("%v", err) return c @@ -921,15 +833,6 @@ func (c *Client) SetOutputDirectory(dirPath string) *Client { return c } -// SetRateLimiter sets an optional `RateLimiter`. If set the rate limiter will control -// all requests made with this client. -// -// Since v2.9.0 -func (c *Client) SetRateLimiter(rl RateLimiter) *Client { - c.rateLimiter = rl - return c -} - // SetTransport method sets custom `*http.Transport` or any `http.RoundTripper` // compatible interface implementation in the resty client. // @@ -941,7 +844,7 @@ func (c *Client) SetRateLimiter(rl RateLimiter) *Client { // - It overwrites the Resty client transport instance and it's configurations. // // transport := &http.Transport{ -// // something like Proxying to httptest.Server, etc... +// // somthing like Proxying to httptest.Server, etc... // Proxy: func(req *http.Request) (*url.URL, error) { // return url.Parse(server.URL) // }, @@ -993,7 +896,6 @@ func (c *Client) SetDoNotParseResponse(parse bool) *Client { // Composed URL - /v1/users/sample@sample.com/details // // It replaces the value of the key while composing the request URL. -// The value will be escaped using `url.PathEscape` function. // // Also it can be overridden at request level Path Params options, // see `Request.SetPathParam` or `Request.SetPathParams`. @@ -1006,17 +908,15 @@ func (c *Client) SetPathParam(param, value string) *Client { // Resty client instance. // // client.SetPathParams(map[string]string{ -// "userId": "sample@sample.com", -// "subAccountId": "100002", -// "path": "groups/developers", +// "userId": "sample@sample.com", +// "subAccountId": "100002", // }) // // Result: -// URL - /v1/users/{userId}/{subAccountId}/{path}/details -// Composed URL - /v1/users/sample@sample.com/100002/groups%2Fdevelopers/details +// URL - /v1/users/{userId}/{subAccountId}/details +// Composed URL - /v1/users/sample@sample.com/100002/details // // It replaces the value of the key while composing the request URL. -// The values will be escaped using `url.PathEscape` function. // // Also it can be overridden at request level Path Params options, // see `Request.SetPathParam` or `Request.SetPathParams`. @@ -1027,60 +927,6 @@ func (c *Client) SetPathParams(params map[string]string) *Client { return c } -// SetRawPathParam method sets single URL path key-value pair in the -// Resty client instance. -// -// client.SetPathParam("userId", "sample@sample.com") -// -// Result: -// URL - /v1/users/{userId}/details -// Composed URL - /v1/users/sample@sample.com/details -// -// client.SetPathParam("path", "groups/developers") -// -// Result: -// URL - /v1/users/{userId}/details -// Composed URL - /v1/users/groups%2Fdevelopers/details -// -// It replaces the value of the key while composing the request URL. -// The value will be used as it is and will not be escaped. -// -// Also it can be overridden at request level Path Params options, -// see `Request.SetPathParam` or `Request.SetPathParams`. -// -// Since v2.8.0 -func (c *Client) SetRawPathParam(param, value string) *Client { - c.RawPathParams[param] = value - return c -} - -// SetRawPathParams method sets multiple URL path key-value pairs at one go in the -// Resty client instance. -// -// client.SetPathParams(map[string]string{ -// "userId": "sample@sample.com", -// "subAccountId": "100002", -// "path": "groups/developers", -// }) -// -// Result: -// URL - /v1/users/{userId}/{subAccountId}/{path}/details -// Composed URL - /v1/users/sample@sample.com/100002/groups/developers/details -// -// It replaces the value of the key while composing the request URL. -// The values will be used as they are and will not be escaped. -// -// Also it can be overridden at request level Path Params options, -// see `Request.SetPathParam` or `Request.SetPathParams`. -// -// Since v2.8.0 -func (c *Client) SetRawPathParams(params map[string]string) *Client { - for p, v := range params { - c.SetRawPathParam(p, v) - } - return c -} - // SetJSONEscapeHTML method is to enable/disable the HTML escape on JSON marshal. // // Note: This option only applicable to standard JSON Marshaller. @@ -1132,14 +978,6 @@ func (c *Client) GetClient() *http.Client { // Executes method executes the given `Request` object and returns response // error. func (c *Client) execute(req *Request) (*Response, error) { - // Lock the user-defined pre-request hooks. - c.udBeforeRequestLock.RLock() - defer c.udBeforeRequestLock.RUnlock() - - // Lock the post-request hooks. - c.afterResponseLock.RLock() - defer c.afterResponseLock.RUnlock() - // Apply Request middleware var err error @@ -1151,14 +989,6 @@ func (c *Client) execute(req *Request) (*Response, error) { } } - // If there is a rate limiter set for this client, the Execute call - // will return an error if the rate limit is exceeded. - if req.client.rateLimiter != nil { - if !req.client.rateLimiter.Allow() { - return nil, wrapNoRetryErr(ErrRateLimitExceeded) - } - } - // resty middlewares for _, f := range c.beforeRequest { if err = f(c, req); err != nil { @@ -1212,7 +1042,7 @@ func (c *Client) execute(req *Request) (*Response, error) { } } - if response.body, err = io.ReadAll(body); err != nil { + if response.body, err = ioutil.ReadAll(body); err != nil { response.setReceivedAt() return response, err } @@ -1234,7 +1064,7 @@ func (c *Client) execute(req *Request) (*Response, error) { // getting TLS client config if not exists then create one func (c *Client) tlsConfig() (*tls.Config, error) { - transport, err := c.Transport() + transport, err := c.transport() if err != nil { return nil, err } @@ -1246,9 +1076,7 @@ func (c *Client) tlsConfig() (*tls.Config, error) { // Transport method returns `*http.Transport` currently in use or error // in case currently used `transport` is not a `*http.Transport`. -// -// Since v2.8.0 become exported method. -func (c *Client) Transport() (*http.Transport, error) { +func (c *Client) transport() (*http.Transport, error) { if transport, ok := c.httpClient.Transport.(*http.Transport); ok { return transport, nil } @@ -1353,7 +1181,6 @@ func createClient(hc *http.Client) *Client { RetryWaitTime: defaultWaitTime, RetryMaxWaitTime: defaultMaxWaitTime, PathParams: make(map[string]string), - RawPathParams: make(map[string]string), JSONMarshal: json.Marshal, JSONUnmarshal: json.Unmarshal, XMLMarshal: xml.Marshal, diff --git a/vendor/github.com/go-resty/resty/v2/client_test.go b/vendor/github.com/go-resty/resty/v2/client_test.go index 1f291d120522..b64074752b42 100644 --- a/vendor/github.com/go-resty/resty/v2/client_test.go +++ b/vendor/github.com/go-resty/resty/v2/client_test.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -9,11 +9,10 @@ import ( "crypto/tls" "errors" "fmt" - "io" + "io/ioutil" "net" "net/http" "net/url" - "os" "path/filepath" "reflect" "strconv" @@ -82,77 +81,6 @@ func TestClientAuthScheme(t *testing.T) { } -func TestClientDigestAuth(t *testing.T) { - conf := defaultDigestServerConf() - ts := createDigestServer(t, conf) - defer ts.Close() - - c := dc(). - SetBaseURL(ts.URL+"/"). - SetDigestAuth(conf.username, conf.password) - - resp, err := c.R(). - SetResult(&AuthSuccess{}). - Get(conf.uri) - assertError(t, err) - assertEqual(t, http.StatusOK, resp.StatusCode()) - - t.Logf("Result Success: %q", resp.Result().(*AuthSuccess)) - logResponse(t, resp) -} - -func TestClientDigestSession(t *testing.T) { - conf := defaultDigestServerConf() - conf.algo = "MD5-sess" - ts := createDigestServer(t, conf) - defer ts.Close() - - c := dc(). - SetBaseURL(ts.URL+"/"). - SetDigestAuth(conf.username, conf.password) - - resp, err := c.R(). - SetResult(&AuthSuccess{}). - Get(conf.uri) - assertError(t, err) - assertEqual(t, http.StatusOK, resp.StatusCode()) - - t.Logf("Result Success: %q", resp.Result().(*AuthSuccess)) - logResponse(t, resp) -} - -func TestClientDigestErrors(t *testing.T) { - type test struct { - mutateConf func(*digestServerConfig) - expect error - } - tests := []test{ - {mutateConf: func(c *digestServerConfig) { c.algo = "BAD_ALGO" }, expect: ErrDigestAlgNotSupported}, - {mutateConf: func(c *digestServerConfig) { c.qop = "bad-qop" }, expect: ErrDigestQopNotSupported}, - {mutateConf: func(c *digestServerConfig) { c.qop = "" }, expect: ErrDigestNoQop}, - {mutateConf: func(c *digestServerConfig) { c.charset = "utf-16" }, expect: ErrDigestCharset}, - {mutateConf: func(c *digestServerConfig) { c.uri = "/bad" }, expect: ErrDigestBadChallenge}, - {mutateConf: func(c *digestServerConfig) { c.uri = "/unknown_param" }, expect: ErrDigestBadChallenge}, - {mutateConf: func(c *digestServerConfig) { c.uri = "/missing_value" }, expect: ErrDigestBadChallenge}, - {mutateConf: func(c *digestServerConfig) { c.uri = "/no_challenge" }, expect: ErrDigestBadChallenge}, - {mutateConf: func(c *digestServerConfig) { c.uri = "/status_500" }, expect: nil}, - } - - for _, tc := range tests { - conf := defaultDigestServerConf() - tc.mutateConf(conf) - ts := createDigestServer(t, conf) - - c := dc(). - SetBaseURL(ts.URL+"/"). - SetDigestAuth(conf.username, conf.password) - - _, err := c.R().Get(conf.uri) - assertErrorIs(t, tc.expect, err) - ts.Close() - } -} - func TestOnAfterMiddleware(t *testing.T) { ts := createGenServer(t) defer ts.Close() @@ -181,13 +109,13 @@ func TestClientRedirectPolicy(t *testing.T) { c := dc().SetRedirectPolicy(FlexibleRedirectPolicy(20)) _, err := c.R().Get(ts.URL + "/redirect-1") - assertEqual(t, true, (err.Error() == "Get /redirect-21: stopped after 20 redirects" || - err.Error() == "Get \"/redirect-21\": stopped after 20 redirects")) + assertEqual(t, true, ("Get /redirect-21: stopped after 20 redirects" == err.Error() || + "Get \"/redirect-21\": stopped after 20 redirects" == err.Error())) c.SetRedirectPolicy(NoRedirectPolicy()) _, err = c.R().Get(ts.URL + "/redirect-1") - assertEqual(t, true, (err.Error() == "Get /redirect-2: auto redirect is disabled" || - err.Error() == "Get \"/redirect-2\": auto redirect is disabled")) + assertEqual(t, true, ("Get /redirect-2: auto redirect is disabled" == err.Error() || + "Get \"/redirect-2\": auto redirect is disabled" == err.Error())) } func TestClientTimeout(t *testing.T) { @@ -249,7 +177,7 @@ func TestClientSetCertificates(t *testing.T) { client := dc() client.SetCertificates(tls.Certificate{}) - transport, err := client.Transport() + transport, err := client.transport() assertNil(t, err) assertEqual(t, 1, len(transport.TLSClientConfig.Certificates)) @@ -259,7 +187,7 @@ func TestClientSetRootCertificate(t *testing.T) { client := dc() client.SetRootCertificate(filepath.Join(getTestDataPath(), "sample-root.pem")) - transport, err := client.Transport() + transport, err := client.transport() assertNil(t, err) assertNotNil(t, transport.TLSClientConfig.RootCAs) @@ -269,7 +197,7 @@ func TestClientSetRootCertificateNotExists(t *testing.T) { client := dc() client.SetRootCertificate(filepath.Join(getTestDataPath(), "not-exists-sample-root.pem")) - transport, err := client.Transport() + transport, err := client.transport() assertNil(t, err) assertNil(t, transport.TLSClientConfig) @@ -277,12 +205,12 @@ func TestClientSetRootCertificateNotExists(t *testing.T) { func TestClientSetRootCertificateFromString(t *testing.T) { client := dc() - rootPemData, err := os.ReadFile(filepath.Join(getTestDataPath(), "sample-root.pem")) + rootPemData, err := ioutil.ReadFile(filepath.Join(getTestDataPath(), "sample-root.pem")) assertNil(t, err) client.SetRootCertificateFromString(string(rootPemData)) - transport, err := client.Transport() + transport, err := client.transport() assertNil(t, err) assertNotNil(t, transport.TLSClientConfig.RootCAs) @@ -290,13 +218,13 @@ func TestClientSetRootCertificateFromString(t *testing.T) { func TestClientSetRootCertificateFromStringErrorTls(t *testing.T) { client := NewWithClient(&http.Client{}) - client.outputLogTo(io.Discard) + client.outputLogTo(ioutil.Discard) - rootPemData, err := os.ReadFile(filepath.Join(getTestDataPath(), "sample-root.pem")) + rootPemData, err := ioutil.ReadFile(filepath.Join(getTestDataPath(), "sample-root.pem")) assertNil(t, err) rt := &CustomRoundTripper{} client.SetTransport(rt) - transport, err := client.Transport() + transport, err := client.transport() client.SetRootCertificateFromString(string(rootPemData)) @@ -334,9 +262,7 @@ func TestClientSetHeaderVerbatim(t *testing.T) { SetHeaderVerbatim("header-lowercase", "value_lowercase"). SetHeader("header-lowercase", "value_standard") - //lint:ignore SA1008 valid one, so ignore this! - unConventionHdrValue := strings.Join(c.Header["header-lowercase"], "") - assertEqual(t, "value_lowercase", unConventionHdrValue) + assertEqual(t, "value_lowercase", strings.Join(c.Header["header-lowercase"], "")) //nolint assertEqual(t, "value_standard", c.Header.Get("Header-Lowercase")) } @@ -352,7 +278,7 @@ func TestClientSetTransport(t *testing.T) { }, } client.SetTransport(transport) - transportInUse, err := client.Transport() + transportInUse, err := client.transport() assertNil(t, err) assertEqual(t, true, transport == transportInUse) @@ -451,7 +377,7 @@ func TestClientOptions(t *testing.T) { } client.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}) - transport, transportErr := client.Transport() + transport, transportErr := client.transport() assertNil(t, transportErr) assertEqual(t, true, transport.TLSClientConfig.InsecureSkipVerify) @@ -488,17 +414,6 @@ func TestClientOptions(t *testing.T) { assertEqual(t, client.closeConnection, true) } -func TestContentLengthWhenBodyIsNil(t *testing.T) { - client := dc() - - client.SetPreRequestHook(func(c *Client, r *http.Request) error { - assertEqual(t, "0", r.Header.Get(hdrContentLengthKey)) - return nil - }) - - client.R().SetContentLength(true).SetBody(nil).Get("http://localhost") -} - func TestClientPreRequestHook(t *testing.T) { client := dc() client.SetPreRequestHook(func(c *Client, r *http.Request) error { @@ -512,7 +427,7 @@ func TestClientPreRequestHook(t *testing.T) { // Reading Request `N` no of times for i := 0; i < 5; i++ { b, _ := r.GetBody() - rb, _ := io.ReadAll(b) + rb, _ := ioutil.ReadAll(b) c.log.Debugf("%s %v", string(rb), len(rb)) assertEqual(t, true, len(rb) >= 45) } @@ -554,22 +469,6 @@ func TestClientAllowsGetMethodPayload(t *testing.T) { assertEqual(t, payload, resp.String()) } -func TestClientAllowsGetMethodPayloadIoReader(t *testing.T) { - ts := createGetServer(t) - defer ts.Close() - - c := dc() - c.SetAllowGetMethodPayload(true) - - payload := "test-payload" - body := bytes.NewReader([]byte(payload)) - resp, err := c.R().SetBody(body).Get(ts.URL + "/get-method-payload-test") - - assertError(t, err) - assertEqual(t, http.StatusOK, resp.StatusCode()) - assertEqual(t, payload, resp.String()) -} - func TestClientAllowsGetMethodPayloadDisabled(t *testing.T) { ts := createGetServer(t) defer ts.Close() @@ -587,12 +486,12 @@ func TestClientAllowsGetMethodPayloadDisabled(t *testing.T) { func TestClientRoundTripper(t *testing.T) { c := NewWithClient(&http.Client{}) - c.outputLogTo(io.Discard) + c.outputLogTo(ioutil.Discard) rt := &CustomRoundTripper{} c.SetTransport(rt) - ct, err := c.Transport() + ct, err := c.transport() assertNotNil(t, err) assertNil(t, ct) assertEqual(t, "current transport is not an *http.Transport instance", err.Error()) @@ -610,38 +509,6 @@ func TestClientNewRequest(t *testing.T) { assertNotNil(t, request) } -func TestClientSetJSONMarshaler(t *testing.T) { - m := func(v interface{}) ([]byte, error) { return nil, nil } - c := New().SetJSONMarshaler(m) - p1 := fmt.Sprintf("%p", c.JSONMarshal) - p2 := fmt.Sprintf("%p", m) - assertEqual(t, p1, p2) // functions can not be compared, we only can compare pointers -} - -func TestClientSetJSONUnmarshaler(t *testing.T) { - m := func([]byte, interface{}) error { return nil } - c := New().SetJSONUnmarshaler(m) - p1 := fmt.Sprintf("%p", c.JSONUnmarshal) - p2 := fmt.Sprintf("%p", m) - assertEqual(t, p1, p2) // functions can not be compared, we only can compare pointers -} - -func TestClientSetXMLMarshaler(t *testing.T) { - m := func(v interface{}) ([]byte, error) { return nil, nil } - c := New().SetXMLMarshaler(m) - p1 := fmt.Sprintf("%p", c.XMLMarshal) - p2 := fmt.Sprintf("%p", m) - assertEqual(t, p1, p2) // functions can not be compared, we only can compare pointers -} - -func TestClientSetXMLUnmarshaler(t *testing.T) { - m := func([]byte, interface{}) error { return nil } - c := New().SetXMLUnmarshaler(m) - p1 := fmt.Sprintf("%p", c.XMLUnmarshal) - p2 := fmt.Sprintf("%p", m) - assertEqual(t, p1, p2) // functions can not be compared, we only can compare pointers -} - func TestDebugBodySizeLimit(t *testing.T) { ts := createGetServer(t) defer ts.Close() @@ -722,12 +589,12 @@ func TestLogCallbacks(t *testing.T) { c.outputLogTo(&lgr) c.OnRequestLog(func(r *RequestLog) error { - // masking authorization header + // masking authorzation header r.Header.Set("Authorization", "Bearer *******************************") return nil }) c.OnResponseLog(func(r *ResponseLog) error { - r.Header.Add("X-Debug-Response-Log", "Modified :)") + r.Header.Add("X-Debug-Resposne-Log", "Modified :)") r.Body += "\nModified the response body content" return nil }) @@ -745,7 +612,7 @@ func TestLogCallbacks(t *testing.T) { // Validating debug log updates logInfo := lgr.String() assertEqual(t, true, strings.Contains(logInfo, "Bearer *******************************")) - assertEqual(t, true, strings.Contains(logInfo, "X-Debug-Response-Log")) + assertEqual(t, true, strings.Contains(logInfo, "X-Debug-Resposne-Log")) assertEqual(t, true, strings.Contains(logInfo, "Modified the response body content")) // Error scenario @@ -766,29 +633,6 @@ func TestLogCallbacks(t *testing.T) { assertNotNil(t, resp) } -func TestDebugLogSimultaneously(t *testing.T) { - ts := createGetServer(t) - - c := New(). - SetDebug(true). - SetBaseURL(ts.URL). - outputLogTo(io.Discard) - - t.Cleanup(ts.Close) - for i := 0; i < 50; i++ { - t.Run(fmt.Sprint(i), func(t *testing.T) { - t.Parallel() - resp, err := c.R(). - SetBody([]int{1, 2, 3}). - SetHeader(hdrContentTypeKey, "application/json; charset=utf-8"). - Post("/") - - assertError(t, err) - assertEqual(t, http.StatusOK, resp.StatusCode()) - }) - } -} - func TestNewWithLocalAddr(t *testing.T) { ts := createGetServer(t) defer ts.Close() @@ -803,6 +647,9 @@ func TestNewWithLocalAddr(t *testing.T) { } func TestClientOnResponseError(t *testing.T) { + ts := createAuthServer(t) + defer ts.Close() + tests := []struct { name string setup func(*Client) @@ -882,12 +729,7 @@ func TestClientOnResponseError(t *testing.T) { } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { - t.Parallel() - ts := createAuthServer(t) - defer ts.Close() - var assertErrorHook = func(r *Request, err error) { assertNotNil(t, r) v, ok := err.(*ResponseError) @@ -907,7 +749,7 @@ func TestClientOnResponseError(t *testing.T) { assertEqual(t, 1, hook6) } }() - c := New().outputLogTo(io.Discard). + c := New().outputLogTo(ioutil.Discard). SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}). SetAuthToken("004DDB79-6801-4587-B976-F093E6AC44FF"). SetRetryCount(0). @@ -1041,31 +883,3 @@ func TestPostRedirectWithBody(t *testing.T) { } wg.Wait() } - -func TestUnixSocket(t *testing.T) { - unixSocketAddr := createUnixSocketEchoServer(t) - defer os.Remove(unixSocketAddr) - - // Create a Go's http.Transport so we can set it in resty. - transport := http.Transport{ - Dial: func(_, _ string) (net.Conn, error) { - return net.Dial("unix", unixSocketAddr) - }, - } - - // Create a Resty Client - client := New() - - // Set the previous transport that we created, set the scheme of the communication to the - // socket and set the unixSocket as the HostURL. - client.SetTransport(&transport).SetScheme("http").SetHostURL(unixSocketAddr) - - // No need to write the host's URL on the request, just the path. - res, err := client.R().Get("http://localhost/") - assertNil(t, err) - assertEqual(t, "Hi resty client from a server running on Unix domain socket!", res.String()) - - res, err = client.R().Get("http://localhost/hello") - assertNil(t, err) - assertEqual(t, "Hello resty client from a server running on endpoint /hello!", res.String()) -} diff --git a/vendor/github.com/go-resty/resty/v2/context_test.go b/vendor/github.com/go-resty/resty/v2/context_test.go index f3c53450a3e0..5da51fa314c4 100644 --- a/vendor/github.com/go-resty/resty/v2/context_test.go +++ b/vendor/github.com/go-resty/resty/v2/context_test.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com) +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com) // 2016 Andrew Grigorev (https://github.com/ei-grad) // All rights reserved. // resty source code and usage is governed by a MIT style diff --git a/vendor/github.com/go-resty/resty/v2/digest.go b/vendor/github.com/go-resty/resty/v2/digest.go deleted file mode 100644 index 9dd3a13b578a..000000000000 --- a/vendor/github.com/go-resty/resty/v2/digest.go +++ /dev/null @@ -1,295 +0,0 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com) -// 2023 Segev Dagan (https://github.com/segevda) -// All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "crypto/md5" - "crypto/rand" - "crypto/sha256" - "crypto/sha512" - "errors" - "fmt" - "hash" - "io" - "net/http" - "strings" -) - -var ( - ErrDigestBadChallenge = errors.New("digest: challenge is bad") - ErrDigestCharset = errors.New("digest: unsupported charset") - ErrDigestAlgNotSupported = errors.New("digest: algorithm is not supported") - ErrDigestQopNotSupported = errors.New("digest: no supported qop in list") - ErrDigestNoQop = errors.New("digest: qop must be specified") -) - -var hashFuncs = map[string]func() hash.Hash{ - "": md5.New, - "MD5": md5.New, - "MD5-sess": md5.New, - "SHA-256": sha256.New, - "SHA-256-sess": sha256.New, - "SHA-512-256": sha512.New, - "SHA-512-256-sess": sha512.New, -} - -type digestCredentials struct { - username, password string -} - -type digestTransport struct { - digestCredentials - transport http.RoundTripper -} - -func (dt *digestTransport) RoundTrip(req *http.Request) (*http.Response, error) { - // Copy the request, so we don't modify the input. - req2 := new(http.Request) - *req2 = *req - req2.Header = make(http.Header) - for k, s := range req.Header { - req2.Header[k] = s - } - - // Fix http: ContentLength=xxx with Body length 0 - if req2.Body == nil { - req2.ContentLength = 0 - } else if req2.GetBody != nil { - var err error - req2.Body, err = req2.GetBody() - if err != nil { - return nil, err - } - } - - // Make a request to get the 401 that contains the challenge. - resp, err := dt.transport.RoundTrip(req) - if err != nil || resp.StatusCode != http.StatusUnauthorized { - return resp, err - } - chal := resp.Header.Get(hdrWwwAuthenticateKey) - if chal == "" { - return resp, ErrDigestBadChallenge - } - - c, err := parseChallenge(chal) - if err != nil { - return resp, err - } - - // Form credentials based on the challenge - cr := dt.newCredentials(req2, c) - auth, err := cr.authorize() - if err != nil { - return resp, err - } - err = resp.Body.Close() - if err != nil { - return nil, err - } - - // Make authenticated request - req2.Header.Set(hdrAuthorizationKey, auth) - return dt.transport.RoundTrip(req2) -} - -func (dt *digestTransport) newCredentials(req *http.Request, c *challenge) *credentials { - return &credentials{ - username: dt.username, - userhash: c.userhash, - realm: c.realm, - nonce: c.nonce, - digestURI: req.URL.RequestURI(), - algorithm: c.algorithm, - sessionAlg: strings.HasSuffix(c.algorithm, "-sess"), - opaque: c.opaque, - messageQop: c.qop, - nc: 0, - method: req.Method, - password: dt.password, - } -} - -type challenge struct { - realm string - domain string - nonce string - opaque string - stale string - algorithm string - qop string - userhash string -} - -func parseChallenge(input string) (*challenge, error) { - const ws = " \n\r\t" - const qs = `"` - s := strings.Trim(input, ws) - if !strings.HasPrefix(s, "Digest ") { - return nil, ErrDigestBadChallenge - } - s = strings.Trim(s[7:], ws) - sl := strings.Split(s, ",") - c := &challenge{} - var r []string - for i := range sl { - sl[i] = strings.TrimSpace(sl[i]) - r = strings.SplitN(sl[i], "=", 2) - if len(r) != 2 { - return nil, ErrDigestBadChallenge - } - r[0] = strings.TrimSpace(r[0]) - r[1] = strings.TrimSpace(r[1]) - switch r[0] { - case "realm": - c.realm = strings.Trim(r[1], qs) - case "domain": - c.domain = strings.Trim(r[1], qs) - case "nonce": - c.nonce = strings.Trim(r[1], qs) - case "opaque": - c.opaque = strings.Trim(r[1], qs) - case "stale": - c.stale = strings.Trim(r[1], qs) - case "algorithm": - c.algorithm = strings.Trim(r[1], qs) - case "qop": - c.qop = strings.Trim(r[1], qs) - case "charset": - if strings.ToUpper(strings.Trim(r[1], qs)) != "UTF-8" { - return nil, ErrDigestCharset - } - case "userhash": - c.userhash = strings.Trim(r[1], qs) - default: - return nil, ErrDigestBadChallenge - } - } - return c, nil -} - -type credentials struct { - username string - userhash string - realm string - nonce string - digestURI string - algorithm string - sessionAlg bool - cNonce string - opaque string - messageQop string - nc int - method string - password string -} - -func (c *credentials) authorize() (string, error) { - if _, ok := hashFuncs[c.algorithm]; !ok { - return "", ErrDigestAlgNotSupported - } - - if err := c.validateQop(); err != nil { - return "", err - } - - resp, err := c.resp() - if err != nil { - return "", err - } - - sl := make([]string, 0, 10) - if c.userhash == "true" { - // RFC 7616 3.4.4 - c.username = c.h(fmt.Sprintf("%s:%s", c.username, c.realm)) - sl = append(sl, fmt.Sprintf(`userhash=%s`, c.userhash)) - } - sl = append(sl, fmt.Sprintf(`username="%s"`, c.username)) - sl = append(sl, fmt.Sprintf(`realm="%s"`, c.realm)) - sl = append(sl, fmt.Sprintf(`nonce="%s"`, c.nonce)) - sl = append(sl, fmt.Sprintf(`uri="%s"`, c.digestURI)) - sl = append(sl, fmt.Sprintf(`response="%s"`, resp)) - sl = append(sl, fmt.Sprintf(`algorithm=%s`, c.algorithm)) - if c.opaque != "" { - sl = append(sl, fmt.Sprintf(`opaque="%s"`, c.opaque)) - } - if c.messageQop != "" { - sl = append(sl, fmt.Sprintf("qop=%s", c.messageQop)) - sl = append(sl, fmt.Sprintf("nc=%08x", c.nc)) - sl = append(sl, fmt.Sprintf(`cnonce="%s"`, c.cNonce)) - } - - return fmt.Sprintf("Digest %s", strings.Join(sl, ", ")), nil -} - -func (c *credentials) validateQop() error { - // Currently only supporting auth quality of protection. TODO: add auth-int support - // NOTE: cURL support auth-int qop for requests other than POST and PUT (i.e. w/o body) by hashing an empty string - // is this applicable for resty? see: https://github.com/curl/curl/blob/307b7543ea1e73ab04e062bdbe4b5bb409eaba3a/lib/vauth/digest.c#L774 - if c.messageQop == "" { - return ErrDigestNoQop - } - possibleQops := strings.Split(c.messageQop, ", ") - var authSupport bool - for _, qop := range possibleQops { - if qop == "auth" { - authSupport = true - break - } - } - if !authSupport { - return ErrDigestQopNotSupported - } - - c.messageQop = "auth" - - return nil -} - -func (c *credentials) h(data string) string { - hfCtor := hashFuncs[c.algorithm] - hf := hfCtor() - _, _ = hf.Write([]byte(data)) // Hash.Write never returns an error - return fmt.Sprintf("%x", hf.Sum(nil)) -} - -func (c *credentials) resp() (string, error) { - c.nc++ - - b := make([]byte, 16) - _, err := io.ReadFull(rand.Reader, b) - if err != nil { - return "", err - } - c.cNonce = fmt.Sprintf("%x", b)[:32] - - ha1 := c.ha1() - ha2 := c.ha2() - - return c.kd(ha1, fmt.Sprintf("%s:%08x:%s:%s:%s", - c.nonce, c.nc, c.cNonce, c.messageQop, ha2)), nil -} - -func (c *credentials) kd(secret, data string) string { - return c.h(fmt.Sprintf("%s:%s", secret, data)) -} - -// RFC 7616 3.4.2 -func (c *credentials) ha1() string { - ret := c.h(fmt.Sprintf("%s:%s:%s", c.username, c.realm, c.password)) - if c.sessionAlg { - return c.h(fmt.Sprintf("%s:%s:%s", ret, c.nonce, c.cNonce)) - } - - return ret -} - -// RFC 7616 3.4.3 -func (c *credentials) ha2() string { - // currently no auth-int support - return c.h(fmt.Sprintf("%s:%s", c.method, c.digestURI)) -} diff --git a/vendor/github.com/go-resty/resty/v2/example_test.go b/vendor/github.com/go-resty/resty/v2/example_test.go index 7608f1dfc57f..2d8d3f745c50 100644 --- a/vendor/github.com/go-resty/resty/v2/example_test.go +++ b/vendor/github.com/go-resty/resty/v2/example_test.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M. (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M. (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -7,6 +7,7 @@ package resty_test import ( "crypto/tls" "fmt" + "io/ioutil" "log" "net/http" "os" @@ -120,7 +121,8 @@ func Example_post() { func Example_dropboxUpload() { // For example: upload file to Dropbox // POST of raw bytes for file upload. - fileBytes, _ := os.ReadFile("/Users/jeeva/mydocument.pdf") + file, _ := os.Open("/Users/jeeva/mydocument.pdf") + fileBytes, _ := ioutil.ReadAll(file) // Create a resty client client := resty.New() diff --git a/vendor/github.com/go-resty/resty/v2/gotest/ya.make b/vendor/github.com/go-resty/resty/v2/gotest/ya.make index d09b708cca16..b4bdb47f1927 100644 --- a/vendor/github.com/go-resty/resty/v2/gotest/ya.make +++ b/vendor/github.com/go-resty/resty/v2/gotest/ya.make @@ -8,10 +8,7 @@ SIZE(MEDIUM) IF (NOT OPENSOURCE) # Removing the dependency on recipes - - DATA( - arcadia/vendor/github.com/go-resty/resty/v2 - ) + DATA(arcadia/vendor/github.com/go-resty/resty/v2) DEPENDS(library/go/test/mutable_testdata) diff --git a/vendor/github.com/go-resty/resty/v2/middleware.go b/vendor/github.com/go-resty/resty/v2/middleware.go index 1fccbb726c3e..4c5cb3c78ddc 100644 --- a/vendor/github.com/go-resty/resty/v2/middleware.go +++ b/vendor/github.com/go-resty/resty/v2/middleware.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -9,13 +9,13 @@ import ( "errors" "fmt" "io" + "io/ioutil" "mime/multipart" "net/http" "net/url" "os" "path/filepath" "reflect" - "strconv" "strings" "time" ) @@ -27,76 +27,15 @@ const debugRequestLogKey = "__restyDebugRequestLog" //_______________________________________________________________________ func parseRequestURL(c *Client, r *Request) error { - if l := len(c.PathParams) + len(c.RawPathParams) + len(r.PathParams) + len(r.RawPathParams); l > 0 { - params := make(map[string]string, l) - - // GitHub #103 Path Params + // GitHub #103 Path Params + if len(r.PathParams) > 0 { for p, v := range r.PathParams { - params[p] = url.PathEscape(v) + r.URL = strings.Replace(r.URL, "{"+p+"}", url.PathEscape(v), -1) } + } + if len(c.PathParams) > 0 { for p, v := range c.PathParams { - if _, ok := params[p]; !ok { - params[p] = url.PathEscape(v) - } - } - - // GitHub #663 Raw Path Params - for p, v := range r.RawPathParams { - if _, ok := params[p]; !ok { - params[p] = v - } - } - for p, v := range c.RawPathParams { - if _, ok := params[p]; !ok { - params[p] = v - } - } - - if len(params) > 0 { - var prev int - buf := acquireBuffer() - defer releaseBuffer(buf) - // search for the next or first opened curly bracket - for curr := strings.Index(r.URL, "{"); curr > prev; curr = prev + strings.Index(r.URL[prev:], "{") { - // write everything from the previous position up to the current - if curr > prev { - buf.WriteString(r.URL[prev:curr]) - } - // search for the closed curly bracket from current position - next := curr + strings.Index(r.URL[curr:], "}") - // if not found, then write the remainder and exit - if next < curr { - buf.WriteString(r.URL[curr:]) - prev = len(r.URL) - break - } - // special case for {}, without parameter's name - if next == curr+1 { - buf.WriteString("{}") - } else { - // check for the replacement - key := r.URL[curr+1 : next] - value, ok := params[key] - /// keep the original string if the replacement not found - if !ok { - value = r.URL[curr : next+1] - } - buf.WriteString(value) - } - - // set the previous position after the closed curly bracket - prev = next + 1 - if prev >= len(r.URL) { - break - } - } - if buf.Len() > 0 { - // write remainder - if prev < len(r.URL) { - buf.WriteString(r.URL[prev:]) - } - r.URL = buf.String() - } + r.URL = strings.Replace(r.URL, "{"+p+"}", url.PathEscape(v), -1) } } @@ -114,12 +53,7 @@ func parseRequestURL(c *Client, r *Request) error { r.URL = "/" + r.URL } - // TODO: change to use c.BaseURL only in v3.0.0 - baseURL := c.BaseURL - if len(baseURL) == 0 { - baseURL = c.HostURL - } - reqURL, err = url.Parse(baseURL + r.URL) + reqURL, err = url.Parse(c.HostURL + r.URL) if err != nil { return err } @@ -131,26 +65,32 @@ func parseRequestURL(c *Client, r *Request) error { } // Adding Query Param - if len(c.QueryParam)+len(r.QueryParam) > 0 { - for k, v := range c.QueryParam { - // skip query parameter if it was set in request - if _, ok := r.QueryParam[k]; ok { - continue - } + query := make(url.Values) + for k, v := range c.QueryParam { + for _, iv := range v { + query.Add(k, iv) + } + } + + for k, v := range r.QueryParam { + // remove query param from client level by key + // since overrides happens for that key in the request + query.Del(k) - r.QueryParam[k] = v[:] + for _, iv := range v { + query.Add(k, iv) } + } - // GitHub #123 Preserve query string order partially. - // Since not feasible in `SetQuery*` resty methods, because - // standard package `url.Encode(...)` sorts the query params - // alphabetically - if len(r.QueryParam) > 0 { - if IsStringEmpty(reqURL.RawQuery) { - reqURL.RawQuery = r.QueryParam.Encode() - } else { - reqURL.RawQuery = reqURL.RawQuery + "&" + r.QueryParam.Encode() - } + // GitHub #123 Preserve query string order partially. + // Since not feasible in `SetQuery*` resty methods, because + // standard package `url.Encode(...)` sorts the query params + // alphabetically + if len(query) > 0 { + if IsStringEmpty(reqURL.RawQuery) { + reqURL.RawQuery = query.Encode() + } else { + reqURL.RawQuery = reqURL.RawQuery + "&" + query.Encode() } } @@ -160,67 +100,77 @@ func parseRequestURL(c *Client, r *Request) error { } func parseRequestHeader(c *Client, r *Request) error { - for k, v := range c.Header { - if _, ok := r.Header[k]; ok { - continue - } - r.Header[k] = v[:] + hdr := make(http.Header) + for k := range c.Header { + hdr[k] = append(hdr[k], c.Header[k]...) + } + + for k := range r.Header { + hdr.Del(k) + hdr[k] = append(hdr[k], r.Header[k]...) } - if IsStringEmpty(r.Header.Get(hdrUserAgentKey)) { - r.Header.Set(hdrUserAgentKey, hdrUserAgentValue) + if IsStringEmpty(hdr.Get(hdrUserAgentKey)) { + hdr.Set(hdrUserAgentKey, hdrUserAgentValue) } - if ct := r.Header.Get(hdrContentTypeKey); IsStringEmpty(r.Header.Get(hdrAcceptKey)) && !IsStringEmpty(ct) && (IsJSONType(ct) || IsXMLType(ct)) { - r.Header.Set(hdrAcceptKey, r.Header.Get(hdrContentTypeKey)) + ct := hdr.Get(hdrContentTypeKey) + if IsStringEmpty(hdr.Get(hdrAcceptKey)) && !IsStringEmpty(ct) && + (IsJSONType(ct) || IsXMLType(ct)) { + hdr.Set(hdrAcceptKey, hdr.Get(hdrContentTypeKey)) } + r.Header = hdr + return nil } -func parseRequestBody(c *Client, r *Request) error { +func parseRequestBody(c *Client, r *Request) (err error) { if isPayloadSupported(r.Method, c.AllowGetMethodPayload) { - switch { - case r.isMultiPart: // Handling Multipart - if err := handleMultipart(c, r); err != nil { - return err + // Handling Multipart + if r.isMultiPart { + if err = handleMultipart(c, r); err != nil { + return } - case len(c.FormData) > 0 || len(r.FormData) > 0: // Handling Form Data + + goto CL + } + + // Handling Form Data + if len(c.FormData) > 0 || len(r.FormData) > 0 { handleFormData(c, r) - case r.Body != nil: // Handling Request body + + goto CL + } + + // Handling Request body + if r.Body != nil { handleContentType(c, r) - if err := handleRequestBody(c, r); err != nil { - return err + if err = handleRequestBody(c, r); err != nil { + return } } } +CL: // by default resty won't set content length, you can if you want to :) - if c.setContentLength || r.setContentLength { - if r.bodyBuf == nil { - r.Header.Set(hdrContentLengthKey, "0") - } else { - r.Header.Set(hdrContentLengthKey, strconv.Itoa(r.bodyBuf.Len())) - } + if (c.setContentLength || r.setContentLength) && r.bodyBuf != nil { + r.Header.Set(hdrContentLengthKey, fmt.Sprintf("%d", r.bodyBuf.Len())) } - return nil + return } func createHTTPRequest(c *Client, r *Request) (err error) { if r.bodyBuf == nil { - if reader, ok := r.Body.(io.Reader); ok && isPayloadSupported(r.Method, c.AllowGetMethodPayload) { - r.RawRequest, err = http.NewRequest(r.Method, r.URL, reader) - } else if c.setContentLength || r.setContentLength { + if c.setContentLength || r.setContentLength { r.RawRequest, err = http.NewRequest(r.Method, r.URL, http.NoBody) } else { r.RawRequest, err = http.NewRequest(r.Method, r.URL, nil) } } else { - // fix data race: must deep copy. - bodyBuf := bytes.NewBuffer(append([]byte{}, r.bodyBuf.Bytes()...)) - r.RawRequest, err = http.NewRequest(r.Method, r.URL, bodyBuf) + r.RawRequest, err = http.NewRequest(r.Method, r.URL, r.bodyBuf) } if err != nil { @@ -262,7 +212,7 @@ func createHTTPRequest(c *Client, r *Request) (err error) { // assign get body func for the underlying raw request instance r.RawRequest.GetBody = func() (io.ReadCloser, error) { if bodyCopy != nil { - return io.NopCloser(bytes.NewReader(bodyCopy.Bytes())), nil + return ioutil.NopCloser(bytes.NewReader(bodyCopy.Bytes())), nil } return nil, nil } @@ -308,25 +258,15 @@ func addCredentials(c *Client, r *Request) error { } func requestLogger(c *Client, r *Request) error { - if r.Debug { + if c.Debug { rr := r.RawRequest - rh := copyHeaders(rr.Header) - if c.GetClient().Jar != nil { - for _, cookie := range c.GetClient().Jar.Cookies(r.RawRequest.URL) { - s := fmt.Sprintf("%s=%s", cookie.Name, cookie.Value) - if c := rh.Get("Cookie"); c != "" { - rh.Set("Cookie", c+"; "+s) - } else { - rh.Set("Cookie", s) - } - } - } - rl := &RequestLog{Header: rh, Body: r.fmtBodyString(c.debugBodySizeLimit)} + rl := &RequestLog{Header: copyHeaders(rr.Header), Body: r.fmtBodyString(c.debugBodySizeLimit)} if c.requestLog != nil { if err := c.requestLog(rl); err != nil { return err } } + // fmt.Sprintf("COOKIES:\n%s\n", composeCookies(c.GetClient().Jar, *rr.URL)) + reqLog := "\n==============================================================================\n" + "~~~ REQUEST ~~~\n" + @@ -348,7 +288,7 @@ func requestLogger(c *Client, r *Request) error { //_______________________________________________________________________ func responseLogger(c *Client, res *Response) error { - if res.Request.Debug { + if c.Debug { rl := &ResponseLog{Header: copyHeaders(res.Header()), Body: res.fmtBodyString(c.debugBodySizeLimit)} if c.responseLog != nil { if err := c.responseLog(rl); err != nil { @@ -379,7 +319,6 @@ func responseLogger(c *Client, res *Response) error { func parseResponseBody(c *Client, res *Response) (err error) { if res.StatusCode() == http.StatusNoContent { - res.Request.Error = nil return } // Handles only JSON or XML content type @@ -402,10 +341,7 @@ func parseResponseBody(c *Client, res *Response) (err error) { } if res.Request.Error != nil { - unmarshalErr := Unmarshalc(c, ct, res.body, res.Request.Error) - if unmarshalErr != nil { - c.log.Warnf("Cannot unmarshal response body: %s", unmarshalErr) - } + err = Unmarshalc(c, ct, res.body, res.Request.Error) } } } @@ -413,13 +349,13 @@ func parseResponseBody(c *Client, res *Response) (err error) { return } -func handleMultipart(c *Client, r *Request) error { +func handleMultipart(c *Client, r *Request) (err error) { r.bodyBuf = acquireBuffer() w := multipart.NewWriter(r.bodyBuf) for k, v := range c.FormData { for _, iv := range v { - if err := w.WriteField(k, iv); err != nil { + if err = w.WriteField(k, iv); err != nil { return err } } @@ -428,11 +364,12 @@ func handleMultipart(c *Client, r *Request) error { for k, v := range r.FormData { for _, iv := range v { if strings.HasPrefix(k, "@") { // file - if err := addFile(w, k[1:], iv); err != nil { - return err + err = addFile(w, k[1:], iv) + if err != nil { + return } } else { // form value - if err := w.WriteField(k, iv); err != nil { + if err = w.WriteField(k, iv); err != nil { return err } } @@ -440,33 +377,50 @@ func handleMultipart(c *Client, r *Request) error { } // #21 - adding io.Reader support - for _, f := range r.multipartFiles { - if err := addFileReader(w, f); err != nil { - return err + if len(r.multipartFiles) > 0 { + for _, f := range r.multipartFiles { + err = addFileReader(w, f) + if err != nil { + return + } } } // GitHub #130 adding multipart field support with content type - for _, mf := range r.multipartFields { - if err := addMultipartFormField(w, mf); err != nil { - return err + if len(r.multipartFields) > 0 { + for _, mf := range r.multipartFields { + if err = addMultipartFormField(w, mf); err != nil { + return + } } } r.Header.Set(hdrContentTypeKey, w.FormDataContentType()) - return w.Close() + err = w.Close() + + return } func handleFormData(c *Client, r *Request) { + formData := url.Values{} + for k, v := range c.FormData { - if _, ok := r.FormData[k]; ok { - continue + for _, iv := range v { + formData.Add(k, iv) } - r.FormData[k] = v[:] } - r.bodyBuf = acquireBuffer() - r.bodyBuf.WriteString(r.FormData.Encode()) + for k, v := range r.FormData { + // remove form data field from client level by key + // since overrides happens for that key in the request + formData.Del(k) + + for _, iv := range v { + formData.Add(k, iv) + } + } + + r.bodyBuf = bytes.NewBuffer([]byte(formData.Encode())) r.Header.Set(hdrContentTypeKey, formContentType) r.isFormData = true } @@ -479,42 +433,40 @@ func handleContentType(c *Client, r *Request) { } } -func handleRequestBody(c *Client, r *Request) error { +func handleRequestBody(c *Client, r *Request) (err error) { var bodyBytes []byte + contentType := r.Header.Get(hdrContentTypeKey) + kind := kindOf(r.Body) r.bodyBuf = nil - switch body := r.Body.(type) { - case io.Reader: - if c.setContentLength || r.setContentLength { // keep backward compatibility - r.bodyBuf = acquireBuffer() - if _, err := r.bodyBuf.ReadFrom(body); err != nil { - return err - } - r.Body = nil - } else { - // Otherwise buffer less processing for `io.Reader`, sounds good. - return nil - } - case []byte: - bodyBytes = body - case string: - bodyBytes = []byte(body) - default: - contentType := r.Header.Get(hdrContentTypeKey) - kind := kindOf(r.Body) - var err error - if IsJSONType(contentType) && (kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice) { - r.bodyBuf, err = jsonMarshal(c, r, r.Body) - } else if IsXMLType(contentType) && (kind == reflect.Struct) { - bodyBytes, err = c.XMLMarshal(r.Body) + if reader, ok := r.Body.(io.Reader); ok { + r.bodyBuf = acquireBuffer() + _, err = r.bodyBuf.ReadFrom(reader) + r.Body = nil + } else if b, ok := r.Body.([]byte); ok { + bodyBytes = b + } else if s, ok := r.Body.(string); ok { + bodyBytes = []byte(s) + } else if IsJSONType(contentType) && + (kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice) { + r.bodyBuf, err = jsonMarshal(c, r, r.Body) + if err != nil { + return } + } else if IsXMLType(contentType) && (kind == reflect.Struct) { + bodyBytes, err = c.XMLMarshal(r.Body) if err != nil { - return err + return } } if bodyBytes == nil && r.bodyBuf == nil { - return errors.New("unsupported 'Body' type/value") + err = errors.New("unsupported 'Body' type/value") + } + + // if any errors during body bytes handling, return it + if err != nil { + return } // []byte into Buffer @@ -523,7 +475,7 @@ func handleRequestBody(c *Client, r *Request) error { _, _ = r.bodyBuf.Write(bodyBytes) } - return nil + return } func saveResponseIntoFile(c *Client, res *Response) error { @@ -573,14 +525,14 @@ func getBodyCopy(r *Request) (*bytes.Buffer, error) { // Maybe body is `io.Reader`. // Note: Resty user have to watchout for large body size of `io.Reader` if r.RawRequest.Body != nil { - b, err := io.ReadAll(r.RawRequest.Body) + b, err := ioutil.ReadAll(r.RawRequest.Body) if err != nil { return nil, err } // Restore the Body closeq(r.RawRequest.Body) - r.RawRequest.Body = io.NopCloser(bytes.NewBuffer(b)) + r.RawRequest.Body = ioutil.NopCloser(bytes.NewBuffer(b)) // Return the Body bytes return bytes.NewBuffer(b), nil diff --git a/vendor/github.com/go-resty/resty/v2/middleware_test.go b/vendor/github.com/go-resty/resty/v2/middleware_test.go deleted file mode 100644 index f4e5c6985ddb..000000000000 --- a/vendor/github.com/go-resty/resty/v2/middleware_test.go +++ /dev/null @@ -1,1061 +0,0 @@ -package resty - -import ( - "bytes" - "encoding/json" - "errors" - "io" - "mime" - "mime/multipart" - "net/http" - "net/url" - "reflect" - "strings" - "testing" -) - -func Test_parseRequestURL(t *testing.T) { - for _, tt := range []struct { - name string - init func(c *Client, r *Request) - expectedURL string - }{ - { - name: "apply client path parameters", - init: func(c *Client, r *Request) { - c.SetPathParams(map[string]string{ - "foo": "1", - "bar": "2/3", - }) - r.URL = "https://example.com/{foo}/{bar}" - }, - expectedURL: "https://example.com/1/2%2F3", - }, - { - name: "apply request path parameters", - init: func(c *Client, r *Request) { - r.SetPathParams(map[string]string{ - "foo": "4", - "bar": "5/6", - }) - r.URL = "https://example.com/{foo}/{bar}" - }, - expectedURL: "https://example.com/4/5%2F6", - }, - { - name: "apply request and client path parameters", - init: func(c *Client, r *Request) { - c.SetPathParams(map[string]string{ - "foo": "1", // ignored, because of the request's "foo" - "bar": "2/3", - }) - r.SetPathParams(map[string]string{ - "foo": "4/5", - }) - r.URL = "https://example.com/{foo}/{bar}" - }, - expectedURL: "https://example.com/4%2F5/2%2F3", - }, - { - name: "apply client raw path parameters", - init: func(c *Client, r *Request) { - c.SetRawPathParams(map[string]string{ - "foo": "1/2", - "bar": "3", - }) - r.URL = "https://example.com/{foo}/{bar}" - }, - expectedURL: "https://example.com/1/2/3", - }, - { - name: "apply request raw path parameters", - init: func(c *Client, r *Request) { - r.SetRawPathParams(map[string]string{ - "foo": "4", - "bar": "5/6", - }) - r.URL = "https://example.com/{foo}/{bar}" - }, - expectedURL: "https://example.com/4/5/6", - }, - { - name: "apply request and client raw path parameters", - init: func(c *Client, r *Request) { - c.SetRawPathParams(map[string]string{ - "foo": "1", // ignored, because of the request's "foo" - "bar": "2/3", - }) - r.SetRawPathParams(map[string]string{ - "foo": "4/5", - }) - r.URL = "https://example.com/{foo}/{bar}" - }, - expectedURL: "https://example.com/4/5/2/3", - }, - { - name: "apply request path and raw path parameters", - init: func(c *Client, r *Request) { - r.SetPathParams(map[string]string{ - "foo": "4/5", - }).SetRawPathParams(map[string]string{ - "foo": "4/5", // ignored, because the PathParams takes precedence over the RawPathParams - "bar": "6/7", - }) - r.URL = "https://example.com/{foo}/{bar}" - }, - expectedURL: "https://example.com/4%2F5/6/7", - }, - { - name: "empty path parameter in URL", - init: func(c *Client, r *Request) { - r.SetPathParams(map[string]string{ - "bar": "4", - }) - r.URL = "https://example.com/{}/{bar}" - }, - expectedURL: "https://example.com/%7B%7D/4", - }, - { - name: "not closed path parameter in URL", - init: func(c *Client, r *Request) { - r.SetPathParams(map[string]string{ - "foo": "4", - }) - r.URL = "https://example.com/{foo}/{bar/1" - }, - expectedURL: "https://example.com/4/%7Bbar/1", - }, - { - name: "extra path parameter in URL", - init: func(c *Client, r *Request) { - r.SetPathParams(map[string]string{ - "foo": "1", - }) - r.URL = "https://example.com/{foo}/{bar}" - }, - expectedURL: "https://example.com/1/%7Bbar%7D", - }, - { - name: " path parameter with remainder", - init: func(c *Client, r *Request) { - r.SetPathParams(map[string]string{ - "foo": "1", - }) - r.URL = "https://example.com/{foo}/2" - }, - expectedURL: "https://example.com/1/2", - }, - { - name: "using BaseURL with absolute URL in request", - init: func(c *Client, r *Request) { - c.SetBaseURL("https://foo.bar") // ignored - r.URL = "https://example.com/" - }, - expectedURL: "https://example.com/", - }, - { - name: "using BaseURL with relative path in request URL without leading slash", - init: func(c *Client, r *Request) { - c.SetBaseURL("https://example.com") - r.URL = "foo/bar" - }, - expectedURL: "https://example.com/foo/bar", - }, - { - name: "using BaseURL with relative path in request URL wit leading slash", - init: func(c *Client, r *Request) { - c.SetBaseURL("https://example.com") - r.URL = "/foo/bar" - }, - expectedURL: "https://example.com/foo/bar", - }, - { - name: "using deprecated HostURL with relative path in request URL", - init: func(c *Client, r *Request) { - c.HostURL = "https://example.com" - r.URL = "foo/bar" - }, - expectedURL: "https://example.com/foo/bar", - }, - { - name: "request URL without scheme", - init: func(c *Client, r *Request) { - r.URL = "example.com/foo/bar" - }, - expectedURL: "/example.com/foo/bar", - }, - { - name: "BaseURL without scheme", - init: func(c *Client, r *Request) { - c.SetBaseURL("example.com") - r.URL = "foo/bar" - }, - expectedURL: "example.com/foo/bar", - }, - { - name: "using SetScheme and BaseURL without scheme", - init: func(c *Client, r *Request) { - c.SetBaseURL("example.com").SetScheme("https") - r.URL = "foo/bar" - }, - expectedURL: "https://example.com/foo/bar", - }, - { - name: "adding query parameters by client", - init: func(c *Client, r *Request) { - c.SetQueryParams(map[string]string{ - "foo": "1", - "bar": "2", - }) - r.URL = "https://example.com/" - }, - expectedURL: "https://example.com/?foo=1&bar=2", - }, - { - name: "adding query parameters by request", - init: func(c *Client, r *Request) { - r.SetQueryParams(map[string]string{ - "foo": "1", - "bar": "2", - }) - r.URL = "https://example.com/" - }, - expectedURL: "https://example.com/?foo=1&bar=2", - }, - { - name: "adding query parameters by client and request", - init: func(c *Client, r *Request) { - c.SetQueryParams(map[string]string{ - "foo": "1", // ignored, because of the "foo" parameter in request - "bar": "2", - }) - r.SetQueryParams(map[string]string{ - "foo": "3", - }) - r.URL = "https://example.com/" - }, - expectedURL: "https://example.com/?foo=3&bar=2", - }, - { - name: "adding query parameters by request to URL with existent", - init: func(c *Client, r *Request) { - r.SetQueryParams(map[string]string{ - "bar": "2", - }) - r.URL = "https://example.com/?foo=1" - }, - expectedURL: "https://example.com/?foo=1&bar=2", - }, - { - name: "adding query parameters by request with multiple values", - init: func(c *Client, r *Request) { - r.QueryParam.Add("foo", "1") - r.QueryParam.Add("foo", "2") - r.URL = "https://example.com/" - }, - expectedURL: "https://example.com/?foo=1&foo=2", - }, - } { - t.Run(tt.name, func(t *testing.T) { - c := New() - r := c.R() - tt.init(c, r) - if err := parseRequestURL(c, r); err != nil { - t.Errorf("parseRequestURL() error = %v", err) - } - - // compare URLs without query parameters first - // then compare query parameters, because the order of the items in a map is not guarantied - expectedURL, _ := url.Parse(tt.expectedURL) - expectedQuery := expectedURL.Query() - expectedURL.RawQuery = "" - actualURL, _ := url.Parse(r.URL) - actualQuery := actualURL.Query() - actualURL.RawQuery = "" - if expectedURL.String() != actualURL.String() { - t.Errorf("r.URL = %q does not match expected %q", r.URL, tt.expectedURL) - } - if !reflect.DeepEqual(expectedQuery, actualQuery) { - t.Errorf("r.URL = %q does not match expected %q", r.URL, tt.expectedURL) - } - }) - } -} - -func Benchmark_parseRequestURL_PathParams(b *testing.B) { - c := New().SetPathParams(map[string]string{ - "foo": "1", - "bar": "2", - }).SetRawPathParams(map[string]string{ - "foo": "3", - "xyz": "4", - }) - r := c.R().SetPathParams(map[string]string{ - "foo": "5", - "qwe": "6", - }).SetRawPathParams(map[string]string{ - "foo": "7", - "asd": "8", - }) - b.ResetTimer() - for i := 0; i < b.N; i++ { - r.URL = "https://example.com/{foo}/{bar}/{xyz}/{qwe}/{asd}" - if err := parseRequestURL(c, r); err != nil { - b.Errorf("parseRequestURL() error = %v", err) - } - } -} - -func Benchmark_parseRequestURL_QueryParams(b *testing.B) { - c := New().SetQueryParams(map[string]string{ - "foo": "1", - "bar": "2", - }) - r := c.R().SetQueryParams(map[string]string{ - "foo": "5", - "qwe": "6", - }) - b.ResetTimer() - for i := 0; i < b.N; i++ { - r.URL = "https://example.com/" - if err := parseRequestURL(c, r); err != nil { - b.Errorf("parseRequestURL() error = %v", err) - } - } -} - -func Test_parseRequestHeader(t *testing.T) { - for _, tt := range []struct { - name string - init func(c *Client, r *Request) - expectedHeader http.Header - }{ - { - name: "headers in request", - init: func(c *Client, r *Request) { - r.SetHeaders(map[string]string{ - "foo": "1", - "bar": "2", - }) - }, - expectedHeader: http.Header{ - http.CanonicalHeaderKey("foo"): []string{"1"}, - http.CanonicalHeaderKey("bar"): []string{"2"}, - http.CanonicalHeaderKey(hdrUserAgentKey): []string{hdrUserAgentValue}, - }, - }, - { - name: "headers in client", - init: func(c *Client, r *Request) { - c.SetHeaders(map[string]string{ - "foo": "1", - "bar": "2", - }) - }, - expectedHeader: http.Header{ - http.CanonicalHeaderKey("foo"): []string{"1"}, - http.CanonicalHeaderKey("bar"): []string{"2"}, - http.CanonicalHeaderKey(hdrUserAgentKey): []string{hdrUserAgentValue}, - }, - }, - { - name: "headers in client and request", - init: func(c *Client, r *Request) { - c.SetHeaders(map[string]string{ - "foo": "1", // ignored, because of the same header in the request - "bar": "2", - }) - r.SetHeaders(map[string]string{ - "foo": "3", - "xyz": "4", - }) - }, - expectedHeader: http.Header{ - http.CanonicalHeaderKey("foo"): []string{"3"}, - http.CanonicalHeaderKey("bar"): []string{"2"}, - http.CanonicalHeaderKey("xyz"): []string{"4"}, - http.CanonicalHeaderKey(hdrUserAgentKey): []string{hdrUserAgentValue}, - }, - }, - { - name: "no headers", - init: func(c *Client, r *Request) {}, - expectedHeader: http.Header{ - http.CanonicalHeaderKey(hdrUserAgentKey): []string{hdrUserAgentValue}, - }, - }, - { - name: "user agent", - init: func(c *Client, r *Request) { - c.SetHeader(hdrUserAgentKey, "foo bar") - }, - expectedHeader: http.Header{ - http.CanonicalHeaderKey(hdrUserAgentKey): []string{"foo bar"}, - }, - }, - { - name: "json content type", - init: func(c *Client, r *Request) { - c.SetHeader(hdrContentTypeKey, "application/json") - }, - expectedHeader: http.Header{ - http.CanonicalHeaderKey(hdrContentTypeKey): []string{"application/json"}, - http.CanonicalHeaderKey(hdrAcceptKey): []string{"application/json"}, - http.CanonicalHeaderKey(hdrUserAgentKey): []string{hdrUserAgentValue}, - }, - }, - } { - t.Run(tt.name, func(t *testing.T) { - c := New() - r := c.R() - tt.init(c, r) - if err := parseRequestHeader(c, r); err != nil { - t.Errorf("parseRequestHeader() error = %v", err) - } - if !reflect.DeepEqual(tt.expectedHeader, r.Header) { - t.Errorf("r.Header = %#+v does not match expected %#+v", r.Header, tt.expectedHeader) - } - }) - } -} - -func Benchmark_parseRequestHeader(b *testing.B) { - c := New() - r := c.R() - c.SetHeaders(map[string]string{ - "foo": "1", // ignored, because of the same header in the request - "bar": "2", - }) - r.SetHeaders(map[string]string{ - "foo": "3", - "xyz": "4", - }) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := parseRequestHeader(c, r); err != nil { - b.Errorf("parseRequestHeader() error = %v", err) - } - } -} - -type errorReader struct{} - -func (errorReader) Read(p []byte) (n int, err error) { - return 0, errors.New("fake") -} - -func Test_parseRequestBody(t *testing.T) { - for _, tt := range []struct { - name string - init func(c *Client, r *Request) - expectedBodyBuf []byte - expectedContentLength string - expectedContentType string - wantErr bool - }{ - { - name: "empty body", - init: func(c *Client, r *Request) {}, - }, - { - name: "empty body with SetContentLength by request", - init: func(c *Client, r *Request) { - r.SetContentLength(true) - }, - expectedContentLength: "0", - }, - { - name: "empty body with SetContentLength by client", - init: func(c *Client, r *Request) { - c.SetContentLength(true) - }, - expectedContentLength: "0", - }, - { - name: "string body", - init: func(c *Client, r *Request) { - r.SetBody("foo") - }, - expectedBodyBuf: []byte("foo"), - expectedContentType: plainTextType, - }, - { - name: "string body with GET method", - init: func(c *Client, r *Request) { - r.SetBody("foo") - r.Method = http.MethodGet - }, - }, - { - name: "string body with GET method and AllowGetMethodPayload", - init: func(c *Client, r *Request) { - c.SetAllowGetMethodPayload(true) - r.SetBody("foo") - r.Method = http.MethodGet - }, - expectedBodyBuf: []byte("foo"), - expectedContentType: plainTextType, - }, - { - name: "string body with HEAD method", - init: func(c *Client, r *Request) { - r.SetBody("foo") - r.Method = http.MethodHead - }, - }, - { - name: "string body with OPTIONS method", - init: func(c *Client, r *Request) { - r.SetBody("foo") - r.Method = http.MethodOptions - }, - }, - { - name: "string body with POST method", - init: func(c *Client, r *Request) { - r.SetBody("foo") - r.Method = http.MethodPost - }, - expectedBodyBuf: []byte("foo"), - expectedContentType: plainTextType, - }, - { - name: "string body with PATCH method", - init: func(c *Client, r *Request) { - r.SetBody("foo") - r.Method = http.MethodPatch - }, - expectedBodyBuf: []byte("foo"), - expectedContentType: plainTextType, - }, - { - name: "string body with PUT method", - init: func(c *Client, r *Request) { - r.SetBody("foo") - r.Method = http.MethodPut - }, - expectedBodyBuf: []byte("foo"), - expectedContentType: plainTextType, - }, - { - name: "string body with DELETE method", - init: func(c *Client, r *Request) { - r.SetBody("foo") - r.Method = http.MethodDelete - }, - expectedBodyBuf: []byte("foo"), - expectedContentType: plainTextType, - }, - { - name: "string body with CONNECT method", - init: func(c *Client, r *Request) { - r.SetBody("foo") - r.Method = http.MethodConnect - }, - expectedBodyBuf: []byte("foo"), - expectedContentType: plainTextType, - }, - { - name: "string body with TRACE method", - init: func(c *Client, r *Request) { - r.SetBody("foo") - r.Method = http.MethodTrace - }, - expectedBodyBuf: []byte("foo"), - expectedContentType: plainTextType, - }, - { - name: "string body with BAR method", - init: func(c *Client, r *Request) { - r.SetBody("foo") - r.Method = "BAR" - }, - expectedBodyBuf: []byte("foo"), - expectedContentType: plainTextType, - }, - { - name: "byte body", - init: func(c *Client, r *Request) { - r.SetBody([]byte("foo")) - }, - expectedBodyBuf: []byte("foo"), - expectedContentType: plainTextType, - }, - { - name: "io.Reader body, no bodyBuf", - init: func(c *Client, r *Request) { - r.SetBody(bytes.NewBufferString("foo")) - }, - expectedContentType: jsonContentType, - }, - { - name: "io.Reader body with SetContentLength by request", - init: func(c *Client, r *Request) { - r.SetBody(bytes.NewBufferString("foo")). - SetContentLength(true) - }, - expectedBodyBuf: []byte("foo"), - expectedContentLength: "3", - expectedContentType: jsonContentType, - }, - { - name: "io.Reader body with SetContentLength by client", - init: func(c *Client, r *Request) { - c.SetContentLength(true) - r.SetBody(bytes.NewBufferString("foo")) - }, - expectedBodyBuf: []byte("foo"), - expectedContentLength: "3", - expectedContentType: jsonContentType, - }, - { - name: "form data by request", - init: func(c *Client, r *Request) { - r.SetFormData(map[string]string{ - "foo": "1", - "bar": "2", - }) - }, - expectedBodyBuf: []byte("foo=1&bar=2"), - expectedContentType: formContentType, - }, - { - name: "form data by client", - init: func(c *Client, r *Request) { - c.SetFormData(map[string]string{ - "foo": "1", - "bar": "2", - }) - }, - expectedBodyBuf: []byte("foo=1&bar=2"), - expectedContentType: formContentType, - }, - { - name: "form data by client and request", - init: func(c *Client, r *Request) { - c.SetFormData(map[string]string{ - "foo": "1", - "bar": "2", - }) - r.SetFormData(map[string]string{ - "foo": "3", - "baz": "4", - }) - }, - expectedBodyBuf: []byte("foo=3&bar=2&baz=4"), - expectedContentType: formContentType, - }, - { - name: "json from struct", - init: func(c *Client, r *Request) { - r.SetBody(struct { - Foo string `json:"foo"` - Bar string `json:"bar"` - }{ - Foo: "1", - Bar: "2", - }).SetContentLength(true) - }, - expectedBodyBuf: []byte(`{"foo":"1","bar":"2"}`), - expectedContentType: jsonContentType, - expectedContentLength: "21", - }, - { - name: "json from slice", - init: func(c *Client, r *Request) { - r.SetBody([]string{"foo", "bar"}).SetContentLength(true) - }, - expectedBodyBuf: []byte(`["foo","bar"]`), - expectedContentType: jsonContentType, - expectedContentLength: "13", - }, - { - name: "json from map", - init: func(c *Client, r *Request) { - r.SetBody(map[string]interface{}{ - "foo": "1", - "bar": []int{1, 2, 3}, - "baz": map[string]string{ - "qux": "4", - }, - "xyz": nil, - }).SetContentLength(true) - }, - expectedBodyBuf: []byte(`{"bar":[1,2,3],"baz":{"qux":"4"},"foo":"1","xyz":null}`), - expectedContentType: jsonContentType, - expectedContentLength: "54", - }, - { - name: "json from map", - init: func(c *Client, r *Request) { - r.SetBody(map[string]interface{}{ - "foo": "1", - "bar": []int{1, 2, 3}, - "baz": map[string]string{ - "qux": "4", - }, - "xyz": nil, - }).SetContentLength(true) - }, - expectedBodyBuf: []byte(`{"bar":[1,2,3],"baz":{"qux":"4"},"foo":"1","xyz":null}`), - expectedContentType: jsonContentType, - expectedContentLength: "54", - }, - { - name: "json from map", - init: func(c *Client, r *Request) { - r.SetBody(map[string]interface{}{ - "foo": "1", - "bar": []int{1, 2, 3}, - "baz": map[string]string{ - "qux": "4", - }, - "xyz": nil, - }).SetContentLength(true) - }, - expectedBodyBuf: []byte(`{"bar":[1,2,3],"baz":{"qux":"4"},"foo":"1","xyz":null}`), - expectedContentType: jsonContentType, - expectedContentLength: "54", - }, - { - name: "xml from struct", - init: func(c *Client, r *Request) { - type FooBar struct { - Foo string `xml:"foo"` - Bar string `xml:"bar"` - } - r.SetBody(FooBar{ - Foo: "1", - Bar: "2", - }). - SetContentLength(true). - SetHeader(hdrContentTypeKey, "text/xml") - }, - expectedBodyBuf: []byte(`12`), - expectedContentType: "text/xml", - expectedContentLength: "41", - }, - { - name: "mulipart form data", - init: func(c *Client, r *Request) { - c.SetFormData(map[string]string{ - "foo": "1", - "bar": "2", - }) - r.SetFormData(map[string]string{ - "foo": "3", - "baz": "4", - }) - r.SetMultipartFormData(map[string]string{ - "foo": "5", - "xyz": "6", - }).SetContentLength(true) - }, - expectedBodyBuf: []byte(`{"bar":"2", "baz":"4", "foo":"5", "xyz":"6"}`), - expectedContentType: "multipart/form-data; boundary=", - expectedContentLength: "744", - }, - { - name: "mulipart fields", - init: func(c *Client, r *Request) { - r.SetMultipartFields( - &MultipartField{ - Param: "foo", - ContentType: "text/plain", - Reader: strings.NewReader("1"), - }, - &MultipartField{ - Param: "bar", - ContentType: "text/plain", - Reader: strings.NewReader("2"), - }, - ).SetContentLength(true) - }, - expectedBodyBuf: []byte(`{"bar":"2","foo":"1"}`), - expectedContentType: "multipart/form-data; boundary=", - expectedContentLength: "344", - }, - { - name: "mulipart files", - init: func(c *Client, r *Request) { - r.SetFileReader("foo", "foo.txt", strings.NewReader("1")). - SetFileReader("bar", "bar.txt", strings.NewReader("2")). - SetContentLength(true) - }, - expectedBodyBuf: []byte(`{"bar":"2","foo":"1"}`), - expectedContentType: "multipart/form-data; boundary=", - expectedContentLength: "412", - }, - { - name: "body with errorReader", - init: func(c *Client, r *Request) { - r.SetBody(&errorReader{}).SetContentLength(true) - }, - wantErr: true, - }, - { - name: "unsupported type", - init: func(c *Client, r *Request) { - r.SetBody(1) - }, - wantErr: true, - }, - { - name: "unsupported xml", - init: func(c *Client, r *Request) { - r.SetBody(struct { - Foo string `xml:"foo"` - Bar string `xml:"bar"` - }{ - Foo: "1", - Bar: "2", - }).Header.Set(hdrContentTypeKey, "text/xml") - }, - wantErr: true, - }, - { - name: "multipart fields with errorReader", - init: func(c *Client, r *Request) { - r.SetMultipartFields(&MultipartField{ - Param: "foo", - ContentType: "text/plain", - Reader: &errorReader{}, - }) - }, - wantErr: true, - }, - { - name: "multipart files with errorReader", - init: func(c *Client, r *Request) { - r.SetFileReader("foo", "foo.txt", &errorReader{}) - }, - wantErr: true, - }, - { - name: "multipart with file not found", - init: func(c *Client, r *Request) { - r.SetFormData(map[string]string{ - "@foo": "foo.txt", - }) - r.isMultiPart = true - }, - wantErr: true, - }, - } { - t.Run(tt.name, func(t *testing.T) { - c := New() - r := c.R() - tt.init(c, r) - if err := parseRequestBody(c, r); err != nil { - if tt.wantErr { - return - } - t.Errorf("parseRequestBody() error = %v", err) - } else if tt.wantErr { - t.Errorf("wanted error, but got nil") - } - switch { - case r.bodyBuf == nil && tt.expectedBodyBuf != nil: - t.Errorf("bodyBuf is nil, but expected: %s", string(tt.expectedBodyBuf)) - case r.bodyBuf != nil && tt.expectedBodyBuf == nil: - t.Errorf("bodyBuf is not nil, but expected nil: %s", r.bodyBuf.String()) - case r.bodyBuf != nil && tt.expectedBodyBuf != nil: - var actual, expected interface{} = r.bodyBuf.Bytes(), tt.expectedBodyBuf - if r.isFormData { - var err error - actual, err = url.ParseQuery(r.bodyBuf.String()) - if err != nil { - t.Errorf("ParseQuery(r.bodyBuf) error = %v", err) - } - expected, err = url.ParseQuery(string(tt.expectedBodyBuf)) - if err != nil { - t.Errorf("ParseQuery(tt.expectedBodyBuf) error = %v", err) - } - } else if r.isMultiPart { - _, params, err := mime.ParseMediaType(r.Header.Get(hdrContentTypeKey)) - if err != nil { - t.Errorf("ParseMediaType(hdrContentTypeKey) error = %v", err) - } - boundary, ok := params["boundary"] - if !ok { - t.Errorf("boundary not found in Content-Type header") - } - reader := multipart.NewReader(r.bodyBuf, boundary) - body := make(map[string]interface{}) - for part, perr := reader.NextPart(); perr != io.EOF; part, perr = reader.NextPart() { - if perr != nil { - t.Errorf("NextPart() error = %v", perr) - } - name := part.FormName() - if name == "" { - name = part.FileName() - } - data, err := io.ReadAll(part) - if err != nil { - t.Errorf("ReadAll(part) error = %v", err) - } - body[name] = string(data) - } - actual = body - expected = nil - if err := json.Unmarshal(tt.expectedBodyBuf, &expected); err != nil { - t.Errorf("json.Unmarshal(tt.expectedBodyBuf) error = %v", err) - } - t.Logf(`in case of an error, the expected body should be set as json for object: %#+v`, actual) - } - if !reflect.DeepEqual(actual, expected) { - t.Errorf("bodyBuf = %q does not match expected %q", r.bodyBuf.String(), string(tt.expectedBodyBuf)) - } - } - if tt.expectedContentLength != r.Header.Get(hdrContentLengthKey) { - t.Errorf("Content-Length header = %q does not match expected %q", r.Header.Get(hdrContentLengthKey), tt.expectedContentLength) - } - if ct := r.Header.Get(hdrContentTypeKey); !((tt.expectedContentType == "" && ct != "") || strings.Contains(ct, tt.expectedContentType)) { - t.Errorf("Content-Type header = %q does not match expected %q", r.Header.Get(hdrContentTypeKey), tt.expectedContentType) - } - }) - } -} - -func Benchmark_parseRequestBody_string(b *testing.B) { - c := New() - r := c.R() - r.SetBody("foo").SetContentLength(true) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := parseRequestBody(c, r); err != nil { - b.Errorf("parseRequestBody() error = %v", err) - } - } -} - -func Benchmark_parseRequestBody_byte(b *testing.B) { - c := New() - r := c.R() - r.SetBody([]byte("foo")).SetContentLength(true) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := parseRequestBody(c, r); err != nil { - b.Errorf("parseRequestBody() error = %v", err) - } - } -} - -func Benchmark_parseRequestBody_reader_with_SetContentLength(b *testing.B) { - c := New() - r := c.R() - r.SetBody(bytes.NewBufferString("foo")).SetContentLength(true) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := parseRequestBody(c, r); err != nil { - b.Errorf("parseRequestBody() error = %v", err) - } - } -} - -func Benchmark_parseRequestBody_reader_without_SetContentLength(b *testing.B) { - c := New() - r := c.R() - r.SetBody(bytes.NewBufferString("foo")) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := parseRequestBody(c, r); err != nil { - b.Errorf("parseRequestBody() error = %v", err) - } - } -} - -func Benchmark_parseRequestBody_struct(b *testing.B) { - type FooBar struct { - Foo string `json:"foo"` - Bar string `json:"bar"` - } - c := New() - r := c.R() - r.SetBody(FooBar{Foo: "1", Bar: "2"}).SetContentLength(true).SetHeader(hdrContentTypeKey, jsonContentType) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := parseRequestBody(c, r); err != nil { - b.Errorf("parseRequestBody() error = %v", err) - } - } -} - -func Benchmark_parseRequestBody_struct_xml(b *testing.B) { - type FooBar struct { - Foo string `xml:"foo"` - Bar string `xml:"bar"` - } - c := New() - r := c.R() - r.SetBody(FooBar{Foo: "1", Bar: "2"}).SetContentLength(true).SetHeader(hdrContentTypeKey, "text/xml") - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := parseRequestBody(c, r); err != nil { - b.Errorf("parseRequestBody() error = %v", err) - } - } -} - -func Benchmark_parseRequestBody_map(b *testing.B) { - c := New() - r := c.R() - r.SetBody(map[string]string{ - "foo": "1", - "bar": "2", - }).SetContentLength(true).SetHeader(hdrContentTypeKey, jsonContentType) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := parseRequestBody(c, r); err != nil { - b.Errorf("parseRequestBody() error = %v", err) - } - } -} - -func Benchmark_parseRequestBody_slice(b *testing.B) { - c := New() - r := c.R() - r.SetBody([]string{"1", "2"}).SetContentLength(true).SetHeader(hdrContentTypeKey, jsonContentType) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := parseRequestBody(c, r); err != nil { - b.Errorf("parseRequestBody() error = %v", err) - } - } -} - -func Benchmark_parseRequestBody_FormData(b *testing.B) { - c := New() - r := c.R() - c.SetFormData(map[string]string{"foo": "1", "bar": "2"}) - r.SetFormData(map[string]string{"foo": "3", "baz": "4"}).SetContentLength(true) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := parseRequestBody(c, r); err != nil { - b.Errorf("parseRequestBody() error = %v", err) - } - } -} - -func Benchmark_parseRequestBody_MultiPart(b *testing.B) { - c := New() - r := c.R() - c.SetFormData(map[string]string{"foo": "1", "bar": "2"}) - r.SetFormData(map[string]string{"foo": "3", "baz": "4"}). - SetMultipartFormData(map[string]string{"foo": "5", "xyz": "6"}). - SetFileReader("qwe", "qwe.txt", strings.NewReader("7")). - SetMultipartFields( - &MultipartField{ - Param: "sdj", - ContentType: "text/plain", - Reader: strings.NewReader("8"), - }, - ). - SetContentLength(true) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := parseRequestBody(c, r); err != nil { - b.Errorf("parseRequestBody() error = %v", err) - } - } -} diff --git a/vendor/github.com/go-resty/resty/v2/redirect.go b/vendor/github.com/go-resty/resty/v2/redirect.go index ed58d7352c02..dfc4f4237f05 100644 --- a/vendor/github.com/go-resty/resty/v2/redirect.go +++ b/vendor/github.com/go-resty/resty/v2/redirect.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -12,16 +12,11 @@ import ( "strings" ) -var ( - // Since v2.8.0 - ErrAutoRedirectDisabled = errors.New("auto redirect is disabled") -) - type ( // RedirectPolicy to regulate the redirects in the resty client. // Objects implementing the RedirectPolicy interface can be registered as // - // Apply function should return nil to continue the redirect journey, otherwise + // Apply function should return nil to continue the redirect jounery, otherwise // return error to stop the redirect. RedirectPolicy interface { Apply(req *http.Request, via []*http.Request) error @@ -42,7 +37,7 @@ func (f RedirectPolicyFunc) Apply(req *http.Request, via []*http.Request) error // resty.SetRedirectPolicy(NoRedirectPolicy()) func NoRedirectPolicy() RedirectPolicy { return RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error { - return ErrAutoRedirectDisabled + return errors.New("auto redirect is disabled") }) } @@ -93,7 +88,7 @@ func getHostname(host string) (hostname string) { } // By default Golang will not redirect request headers -// after go throwing various discussion comments from thread +// after go throughing various discussion comments from thread // https://github.com/golang/go/issues/4800 // Resty will add all the headers during a redirect for the same host func checkHostAndAddHeaders(cur *http.Request, pre *http.Request) { diff --git a/vendor/github.com/go-resty/resty/v2/request.go b/vendor/github.com/go-resty/resty/v2/request.go index 4e13ff094a7b..adb129e334bc 100644 --- a/vendor/github.com/go-resty/resty/v2/request.go +++ b/vendor/github.com/go-resty/resty/v2/request.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -27,24 +27,22 @@ import ( // resty client. Request provides an options to override client level // settings and also an options for the request composition. type Request struct { - URL string - Method string - Token string - AuthScheme string - QueryParam url.Values - FormData url.Values - PathParams map[string]string - RawPathParams map[string]string - Header http.Header - Time time.Time - Body interface{} - Result interface{} - Error interface{} - RawRequest *http.Request - SRV *SRVRecord - UserInfo *User - Cookies []*http.Cookie - Debug bool + URL string + Method string + Token string + AuthScheme string + QueryParam url.Values + FormData url.Values + PathParams map[string]string + Header http.Header + Time time.Time + Body interface{} + Result interface{} + Error interface{} + RawRequest *http.Request + SRV *SRVRecord + UserInfo *User + Cookies []*http.Cookie // Attempt is to represent the request attempt made during a Resty // request execution flow, including retry count. @@ -489,7 +487,7 @@ func (r *Request) SetAuthToken(token string) *Request { // // client.R().SetAuthScheme("OAuth") // -// This auth header scheme gets added to all the request raised from this client instance. +// This auth header scheme gets added to all the request rasied from this client instance. // Also it can be overridden or set one at the request level is supported. // // Information about Auth schemes can be found in RFC7235 which is linked to below along with the page containing @@ -504,35 +502,6 @@ func (r *Request) SetAuthScheme(scheme string) *Request { return r } -// SetDigestAuth method sets the Digest Access auth scheme for the HTTP request. If a server responds with 401 and sends -// a Digest challenge in the WWW-Authenticate Header, the request will be resent with the appropriate Authorization Header. -// -// For Example: To set the Digest scheme with username "Mufasa" and password "Circle Of Life" -// -// client.R().SetDigestAuth("Mufasa", "Circle Of Life") -// -// Information about Digest Access Authentication can be found in RFC7616: -// -// https://datatracker.ietf.org/doc/html/rfc7616 -// -// This method overrides the username and password set by method `Client.SetDigestAuth`. -func (r *Request) SetDigestAuth(username, password string) *Request { - oldTransport := r.client.httpClient.Transport - r.client.OnBeforeRequest(func(c *Client, _ *Request) error { - c.httpClient.Transport = &digestTransport{ - digestCredentials: digestCredentials{username, password}, - transport: oldTransport, - } - return nil - }) - r.client.OnAfterResponse(func(c *Client, _ *Response) error { - c.httpClient.Transport = oldTransport - return nil - }) - - return r -} - // SetOutput method sets the output file for current HTTP request. Current HTTP response will be // saved into given file. It is similar to `curl -o` flag. Absolute path or relative path can be used. // If is it relative path then output file goes under the output directory, as mentioned @@ -580,17 +549,8 @@ func (r *Request) SetDoNotParseResponse(parse bool) *Request { // URL - /v1/users/{userId}/details // Composed URL - /v1/users/sample@sample.com/details // -// client.R().SetPathParam("path", "groups/developers") -// -// Result: -// URL - /v1/users/{userId}/details -// Composed URL - /v1/users/groups%2Fdevelopers/details -// -// It replaces the value of the key while composing the request URL. -// The values will be escaped using `url.PathEscape` function. -// -// Also you can override Path Params value, which was set at client instance -// level. +// It replaces the value of the key while composing the request URL. Also you can +// override Path Params value, which was set at client instance level. func (r *Request) SetPathParam(param, value string) *Request { r.PathParams[param] = value return r @@ -600,20 +560,16 @@ func (r *Request) SetPathParam(param, value string) *Request { // Resty current request instance. // // client.R().SetPathParams(map[string]string{ -// "userId": "sample@sample.com", -// "subAccountId": "100002", -// "path": "groups/developers", +// "userId": "sample@sample.com", +// "subAccountId": "100002", // }) // // Result: -// URL - /v1/users/{userId}/{subAccountId}/{path}/details -// Composed URL - /v1/users/sample@sample.com/100002/groups%2Fdevelopers/details -// -// It replaces the value of the key while composing request URL. -// The value will be used as it is and will not be escaped. +// URL - /v1/users/{userId}/{subAccountId}/details +// Composed URL - /v1/users/sample@sample.com/100002/details // -// Also you can override Path Params value, which was set at client instance -// level. +// It replaces the value of the key while composing request URL. Also you can +// override Path Params value, which was set at client instance level. func (r *Request) SetPathParams(params map[string]string) *Request { for p, v := range params { r.SetPathParam(p, v) @@ -621,60 +577,6 @@ func (r *Request) SetPathParams(params map[string]string) *Request { return r } -// SetRawPathParam method sets single URL path key-value pair in the -// Resty current request instance. -// -// client.R().SetPathParam("userId", "sample@sample.com") -// -// Result: -// URL - /v1/users/{userId}/details -// Composed URL - /v1/users/sample@sample.com/details -// -// client.R().SetPathParam("path", "groups/developers") -// -// Result: -// URL - /v1/users/{userId}/details -// Composed URL - /v1/users/groups/developers/details -// -// It replaces the value of the key while composing the request URL. -// The value will be used as it is and will not be escaped. -// -// Also you can override Path Params value, which was set at client instance -// level. -// -// Since v2.8.0 -func (r *Request) SetRawPathParam(param, value string) *Request { - r.RawPathParams[param] = value - return r -} - -// SetRawPathParams method sets multiple URL path key-value pairs at one go in the -// Resty current request instance. -// -// client.R().SetPathParams(map[string]string{ -// "userId": "sample@sample.com", -// "subAccountId": "100002", -// "path": "groups/developers", -// }) -// -// Result: -// URL - /v1/users/{userId}/{subAccountId}/{path}/details -// Composed URL - /v1/users/sample@sample.com/100002/groups/developers/details -// -// It replaces the value of the key while composing request URL. -// The values will be used as they are and will not be escaped. -// -// Also you can override Path Params value, which was set at client instance -// level. -// -// Since v2.8.0 -func (r *Request) SetRawPathParams(params map[string]string) *Request { - for p, v := range params { - r.SetRawPathParam(p, v) - } - return r -} - // ExpectContentType method allows to provide fallback `Content-Type` for automatic unmarshalling // when `Content-Type` response header is unavailable. func (r *Request) ExpectContentType(contentType string) *Request { @@ -746,17 +648,6 @@ func (r *Request) SetLogger(l Logger) *Request { return r } -// SetDebug method enables the debug mode on current request Resty request, It logs -// the details current request and response. -// For `Request` it logs information such as HTTP verb, Relative URL path, Host, Headers, Body if it has one. -// For `Response` it logs information such as Status, Response Time, Headers, Body if it has one. -// -// client.R().SetDebug(true) -func (r *Request) SetDebug(d bool) *Request { - r.Debug = d - return r -} - // AddRetryCondition method adds a retry condition function to the request's // array of functions that are checked to determine if the request is retried. // The request will retry if any of the functions return true and error is nil. @@ -946,7 +837,7 @@ func (r *Request) Execute(method, url string) (*Response, error) { resp, err = r.client.execute(r) if err != nil { - r.log.Warnf("%v, Attempt %v", err, r.Attempt) + r.log.Errorf("%v, Attempt %v", err, r.Attempt) } return resp, err @@ -959,10 +850,6 @@ func (r *Request) Execute(method, url string) (*Response, error) { ResetMultipartReaders(r.client.RetryResetReaders), ) - if err != nil { - r.log.Errorf("%v", err) - } - r.client.onErrorHooks(r, resp, unwrapNoRetryErr(err)) return resp, unwrapNoRetryErr(err) } @@ -1014,12 +901,7 @@ func (r *Request) fmtBodyString(sl int64) (body string) { contentType := r.Header.Get(hdrContentTypeKey) kind := kindOf(r.Body) if canJSONMarshal(contentType, kind) { - var bodyBuf *bytes.Buffer - bodyBuf, err = noescapeJSONMarshalIndent(&r.Body) - if err == nil { - prtBodyBytes = bodyBuf.Bytes() - defer releaseBuffer(bodyBuf) - } + prtBodyBytes, err = json.MarshalIndent(&r.Body, "", " ") } else if IsXMLType(contentType) && (kind == reflect.Struct) { prtBodyBytes, err = xml.MarshalIndent(&r.Body, "", " ") } else if b, ok := r.Body.(string); ok { @@ -1081,17 +963,3 @@ var noescapeJSONMarshal = func(v interface{}) (*bytes.Buffer, error) { return buf, nil } - -var noescapeJSONMarshalIndent = func(v interface{}) (*bytes.Buffer, error) { - buf := acquireBuffer() - encoder := json.NewEncoder(buf) - encoder.SetEscapeHTML(false) - encoder.SetIndent("", " ") - - if err := encoder.Encode(v); err != nil { - releaseBuffer(buf) - return nil, err - } - - return buf, nil -} diff --git a/vendor/github.com/go-resty/resty/v2/request_test.go b/vendor/github.com/go-resty/resty/v2/request_test.go index 7312128fb1d5..f7a3f4be1f2e 100644 --- a/vendor/github.com/go-resty/resty/v2/request_test.go +++ b/vendor/github.com/go-resty/resty/v2/request_test.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -10,6 +10,7 @@ import ( "encoding/xml" "errors" "io" + "io/ioutil" "net" "net/http" "net/url" @@ -19,8 +20,6 @@ import ( "strings" "testing" "time" - - "golang.org/x/time/rate" ) type AuthSuccess struct { @@ -49,63 +48,6 @@ func TestGet(t *testing.T) { logResponse(t, resp) } -func TestGetGH524(t *testing.T) { - ts := createGetServer(t) - defer ts.Close() - - resp, err := dc().R(). - SetPathParams((map[string]string{ - "userId": "sample@sample.com", - "subAccountId": "100002", - "path": "groups/developers", - })). - SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10)). - SetDebug(true). - Get(ts.URL + "/v1/users/{userId}/{subAccountId}/{path}/details") - - assertError(t, err) - assertEqual(t, http.StatusOK, resp.StatusCode()) - assertEqual(t, resp.Request.Header.Get("Content-Type"), "") // unable to reproduce reported issue -} - -func TestRateLimiter(t *testing.T) { - ts := createGetServer(t) - defer ts.Close() - - // Test a burst with a valid capacity and then a consecutive request that must fail. - - // Allow a rate of 1 every 100 ms but also allow bursts of 10 requests. - client := dc().SetRateLimiter(rate.NewLimiter(rate.Every(100*time.Millisecond), 10)) - - // Execute a burst of 10 requests. - for i := 0; i < 10; i++ { - resp, err := client.R(). - SetQueryParam("request_no", strconv.Itoa(i)).Get(ts.URL + "/") - assertError(t, err) - assertEqual(t, http.StatusOK, resp.StatusCode()) - } - // Next request issued directly should fail because burst of 10 has been consumed. - { - _, err := client.R(). - SetQueryParam("request_no", strconv.Itoa(11)).Get(ts.URL + "/") - assertErrorIs(t, ErrRateLimitExceeded, err) - } - - // Test continues request at a valid rate - - // Allow a rate of 1 every ms with no burst. - client = dc().SetRateLimiter(rate.NewLimiter(rate.Every(1*time.Millisecond), 1)) - - // Sending requests every ms+tiny delta must succeed. - for i := 0; i < 100; i++ { - resp, err := client.R(). - SetQueryParam("request_no", strconv.Itoa(i)).Get(ts.URL + "/") - assertError(t, err) - assertEqual(t, http.StatusOK, resp.StatusCode()) - time.Sleep(1*time.Millisecond + 100*time.Microsecond) - } -} - func TestIllegalRetryCount(t *testing.T) { ts := createGetServer(t) defer ts.Close() @@ -142,7 +84,7 @@ func TestGetClientParamRequestParam(t *testing.T) { c.SetQueryParam("client_param", "true"). SetQueryParams(map[string]string{"req_1": "jeeva", "req_3": "jeeva3"}). SetDebug(true) - c.outputLogTo(io.Discard) + c.outputLogTo(ioutil.Discard) resp, err := c.R(). SetQueryParams(map[string]string{"req_1": "req 1 value", "req_2": "req 2 value"}). @@ -688,59 +630,6 @@ func TestRequestAuthScheme(t *testing.T) { assertEqual(t, http.StatusOK, resp.StatusCode()) } -func TestRequestDigestAuth(t *testing.T) { - conf := defaultDigestServerConf() - ts := createDigestServer(t, nil) - defer ts.Close() - - resp, err := dclr(). - SetDigestAuth(conf.username, conf.password). - SetResult(&AuthSuccess{}). - Get(ts.URL + conf.uri) - - assertError(t, err) - assertEqual(t, http.StatusOK, resp.StatusCode()) - - t.Logf("Result Success: %q", resp.Result().(*AuthSuccess)) - logResponse(t, resp) -} - -func TestRequestDigestAuthFail(t *testing.T) { - conf := defaultDigestServerConf() - ts := createDigestServer(t, nil) - defer ts.Close() - - resp, err := dclr(). - SetDigestAuth(conf.username, "wrongPassword"). - SetError(AuthError{}). - Get(ts.URL + conf.uri) - - assertError(t, err) - assertEqual(t, http.StatusUnauthorized, resp.StatusCode()) - - t.Logf("Result Error: %q", resp.Error().(*AuthError)) - logResponse(t, resp) -} - -func TestRequestDigestAuthWithBody(t *testing.T) { - conf := defaultDigestServerConf() - ts := createDigestServer(t, nil) - defer ts.Close() - - resp, err := dclr(). - SetDigestAuth(conf.username, conf.password). - SetResult(&AuthSuccess{}). - SetHeader(hdrContentTypeKey, "application/json"). - SetBody(map[string]interface{}{"zip_code": "00000", "city": "Los Angeles"}). - Post(ts.URL + conf.uri) - - assertError(t, err) - assertEqual(t, http.StatusOK, resp.StatusCode()) - - t.Logf("Result Success: %q", resp.Result().(*AuthSuccess)) - logResponse(t, resp) -} - func TestFormData(t *testing.T) { ts := createFormPostServer(t) defer ts.Close() @@ -749,7 +638,7 @@ func TestFormData(t *testing.T) { c.SetFormData(map[string]string{"zip_code": "00000", "city": "Los Angeles"}). SetContentLength(true). SetDebug(true) - c.outputLogTo(io.Discard) + c.outputLogTo(ioutil.Discard) resp, err := c.R(). SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M", "zip_code": "00001"}). @@ -771,7 +660,7 @@ func TestMultiValueFormData(t *testing.T) { c := dc() c.SetContentLength(true).SetDebug(true) - c.outputLogTo(io.Discard) + c.outputLogTo(ioutil.Discard) resp, err := c.R(). SetQueryParamsFromValues(v). @@ -789,11 +678,11 @@ func TestFormDataDisableWarn(t *testing.T) { c := dc() c.SetFormData(map[string]string{"zip_code": "00000", "city": "Los Angeles"}). SetContentLength(true). + SetDebug(true). SetDisableWarn(true) - c.outputLogTo(io.Discard) + c.outputLogTo(ioutil.Discard) resp, err := c.R(). - SetDebug(true). SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M", "zip_code": "00001"}). SetBasicAuth("myuser", "mypass"). Post(ts.URL + "/profile") @@ -892,8 +781,8 @@ func TestMultiPartIoReaderFiles(t *testing.T) { defer cleanupFiles(".testdata/upload") basePath := getTestDataPath() - profileImgBytes, _ := os.ReadFile(filepath.Join(basePath, "test-img.png")) - notesBytes, _ := os.ReadFile(filepath.Join(basePath, "text-file.txt")) + profileImgBytes, _ := ioutil.ReadFile(filepath.Join(basePath, "test-img.png")) + notesBytes, _ := ioutil.ReadFile(filepath.Join(basePath, "text-file.txt")) // Just info values file := File{ @@ -1144,7 +1033,7 @@ func TestPutJSONString(t *testing.T) { }) client.SetDebug(true) - client.outputLogTo(io.Discard) + client.outputLogTo(ioutil.Discard) resp, err := client.R(). SetHeaders(map[string]string{hdrContentTypeKey: "application/json; charset=utf-8", hdrAcceptKey: "application/json; charset=utf-8"}). @@ -1200,8 +1089,8 @@ func TestHTTPAutoRedirectUpTo10(t *testing.T) { _, err := dc().R().Get(ts.URL + "/redirect-1") - assertEqual(t, true, (err.Error() == "Get /redirect-11: stopped after 10 redirects" || - err.Error() == "Get \"/redirect-11\": stopped after 10 redirects")) + assertEqual(t, true, ("Get /redirect-11: stopped after 10 redirects" == err.Error() || + "Get \"/redirect-11\": stopped after 10 redirects" == err.Error())) } func TestHostCheckRedirectPolicy(t *testing.T) { @@ -1247,7 +1136,7 @@ func TestPatchMethod(t *testing.T) { assertError(t, err) assertEqual(t, http.StatusOK, resp.StatusCode()) - resp.SetBody(nil) + resp.body = nil assertEqual(t, "", resp.String()) } @@ -1313,7 +1202,9 @@ func TestRawFileUploadByBody(t *testing.T) { ts := createFormPostServer(t) defer ts.Close() - fileBytes, err := os.ReadFile(filepath.Join(getTestDataPath(), "test-img.png")) + file, err := os.Open(filepath.Join(getTestDataPath(), "test-img.png")) + assertNil(t, err) + fileBytes, err := ioutil.ReadAll(file) assertNil(t, err) resp, err := dclr(). @@ -1330,7 +1221,7 @@ func TestRawFileUploadByBody(t *testing.T) { func TestProxySetting(t *testing.T) { c := dc() - transport, err := c.Transport() + transport, err := c.transport() assertNil(t, err) @@ -1395,7 +1286,7 @@ func TestDetectContentTypeForPointer(t *testing.T) { } type ExampleUser struct { - FirstName string `json:"first_name"` + FirstName string `json:"frist_name"` LastName string `json:"last_name"` ZipCode string `json:"zip_code"` } @@ -1542,8 +1433,7 @@ func TestSetHeaderVerbatim(t *testing.T) { SetHeaderVerbatim("header-lowercase", "value_lowercase"). SetHeader("header-lowercase", "value_standard") - //lint:ignore SA1008 valid one ignore this! - assertEqual(t, "value_lowercase", strings.Join(r.Header["header-lowercase"], "")) + assertEqual(t, "value_lowercase", strings.Join(r.Header["header-lowercase"], "")) //nolint assertEqual(t, "value_standard", r.Header.Get("Header-Lowercase")) } @@ -1569,7 +1459,7 @@ func TestOutputFileWithBaseDirAndRelativePath(t *testing.T) { SetRedirectPolicy(FlexibleRedirectPolicy(10)). SetOutputDirectory(filepath.Join(getTestDataPath(), "dir-sample")). SetDebug(true) - client.outputLogTo(io.Discard) + client.outputLogTo(ioutil.Discard) resp, err := client.R(). SetOutput("go-resty/test-img-success.png"). @@ -1714,7 +1604,7 @@ func TestGetPathParamAndPathParams(t *testing.T) { defer ts.Close() c := dc(). - SetBaseURL(ts.URL). + SetHostURL(ts.URL). SetPathParam("userId", "sample@sample.com") resp, err := c.R().SetPathParam("subAccountId", "100002"). @@ -1822,101 +1712,26 @@ func TestHostHeaderOverride(t *testing.T) { logResponse(t, resp) } -type HTTPErrorResponse struct { - Error string `json:"error,omitempty"` -} - -func TestNotFoundWithError(t *testing.T) { - var httpError HTTPErrorResponse - ts := createGetServer(t) - defer ts.Close() - - resp, err := dc().R(). - SetHeader(hdrContentTypeKey, "application/json"). - SetError(&httpError). - Get(ts.URL + "/not-found-with-error") - - assertError(t, err) - assertEqual(t, http.StatusNotFound, resp.StatusCode()) - assertEqual(t, "404 Not Found", resp.Status()) - assertNotNil(t, resp.Body()) - assertEqual(t, "{\"error\": \"Not found\"}", resp.String()) - assertNotNil(t, httpError) - assertEqual(t, "Not found", httpError.Error) - - logResponse(t, resp) -} - -func TestNotFoundWithoutError(t *testing.T) { - var httpError HTTPErrorResponse - - ts := createGetServer(t) - defer ts.Close() - - c := dc().outputLogTo(os.Stdout) - resp, err := c.R(). - SetError(&httpError). - SetHeader(hdrContentTypeKey, "application/json"). - Get(ts.URL + "/not-found-no-error") - - assertError(t, err) - assertEqual(t, http.StatusNotFound, resp.StatusCode()) - assertEqual(t, "404 Not Found", resp.Status()) - assertNotNil(t, resp.Body()) - assertEqual(t, 0, len(resp.Body())) - assertNotNil(t, httpError) - assertEqual(t, "", httpError.Error) - - logResponse(t, resp) -} - func TestPathParamURLInput(t *testing.T) { ts := createGetServer(t) defer ts.Close() - c := dc(). - SetBaseURL(ts.URL). + c := dc().SetDebug(true). + SetHostURL(ts.URL). SetPathParams(map[string]string{ "userId": "sample@sample.com", - "path": "users/developers", }) resp, err := c.R(). - SetDebug(true). SetPathParams(map[string]string{ "subAccountId": "100002", "website": "https://example.com", - }).Get("/v1/users/{userId}/{subAccountId}/{path}/{website}") + }).Get("/v1/users/{userId}/{subAccountId}/{website}") assertError(t, err) assertEqual(t, http.StatusOK, resp.StatusCode()) assertEqual(t, true, strings.Contains(resp.String(), "TestPathParamURLInput: text response")) - assertEqual(t, true, strings.Contains(resp.String(), "/v1/users/sample@sample.com/100002/users%2Fdevelopers/https:%2F%2Fexample.com")) - - logResponse(t, resp) -} - -func TestRawPathParamURLInput(t *testing.T) { - ts := createGetServer(t) - defer ts.Close() - - c := dc().SetDebug(true). - SetBaseURL(ts.URL). - SetRawPathParams(map[string]string{ - "userId": "sample@sample.com", - "path": "users/developers", - }) - - resp, err := c.R(). - SetRawPathParams(map[string]string{ - "subAccountId": "100002", - "website": "https://example.com", - }).Get("/v1/users/{userId}/{subAccountId}/{path}/{website}") - - assertError(t, err) - assertEqual(t, http.StatusOK, resp.StatusCode()) - assertEqual(t, true, strings.Contains(resp.String(), "TestPathParamURLInput: text response")) - assertEqual(t, true, strings.Contains(resp.String(), "/v1/users/sample@sample.com/100002/users/developers/https://example.com")) + assertEqual(t, true, strings.Contains(resp.String(), "/v1/users/sample@sample.com/100002/https:%2F%2Fexample.com")) logResponse(t, resp) } @@ -2027,8 +1842,7 @@ func TestDebugLoggerRequestBodyTooLarge(t *testing.T) { // upload a text file with no more than 512 bytes output = bytes.NewBufferString("") - resp, err = New().outputLogTo(output).SetDebugBodyLimit(debugBodySizeLimit).R(). - SetDebug(true). + resp, err = New().SetDebug(true).outputLogTo(output).SetDebugBodyLimit(debugBodySizeLimit).R(). SetFile("file", filepath.Join(getTestDataPath(), "text-file.txt")). SetHeader("Content-Type", "text/plain"). Post(ts.URL + "/upload") @@ -2055,8 +1869,7 @@ func TestDebugLoggerRequestBodyTooLarge(t *testing.T) { // post form with no more than 512 bytes data output = bytes.NewBufferString("") - resp, err = New().outputLogTo(output).SetDebugBodyLimit(debugBodySizeLimit).R(). - SetDebug(true). + resp, err = New().SetDebug(true).outputLogTo(output).SetDebugBodyLimit(debugBodySizeLimit).R(). SetFormData(map[string]string{ "first_name": "Alex", "last_name": "C", @@ -2083,8 +1896,7 @@ func TestDebugLoggerRequestBodyTooLarge(t *testing.T) { // post slice with more than 512 bytes data output = bytes.NewBufferString("") - resp, err = New().outputLogTo(output).SetDebugBodyLimit(debugBodySizeLimit).R(). - SetDebug(true). + resp, err = New().SetDebug(true).outputLogTo(output).SetDebugBodyLimit(debugBodySizeLimit).R(). SetBody([]string{strings.Repeat("C", int(debugBodySizeLimit))}). SetBasicAuth("myuser", "mypass"). Post(formTs.URL + "/profile") @@ -2135,3 +1947,4 @@ func TestSetResultMustNotPanicOnNil(t *testing.T) { }() dc().R().SetResult(nil) } + diff --git a/vendor/github.com/go-resty/resty/v2/response.go b/vendor/github.com/go-resty/resty/v2/response.go index 63c95c4186ac..0356c97118c7 100644 --- a/vendor/github.com/go-resty/resty/v2/response.go +++ b/vendor/github.com/go-resty/resty/v2/response.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -37,18 +37,6 @@ func (r *Response) Body() []byte { return r.body } -// SetBody method is to set Response body in byte slice. Typically, -// its helpful for test cases. -// -// resp.SetBody([]byte("This is test body content")) -// resp.SetBody(nil) -// -// Since v2.10.0 -func (r *Response) SetBody(b []byte) *Response { - r.body = b - return r -} - // Status method returns the HTTP status string for the executed request. // // Example: 200 OK @@ -105,7 +93,7 @@ func (r *Response) Cookies() []*http.Cookie { // String method returns the body of the server response as String. func (r *Response) String() string { - if len(r.body) == 0 { + if r.body == nil { return "" } return strings.TrimSpace(string(r.body)) @@ -168,7 +156,7 @@ func (r *Response) setReceivedAt() { } func (r *Response) fmtBodyString(sl int64) string { - if len(r.body) > 0 { + if r.body != nil { if int64(len(r.body)) > sl { return fmt.Sprintf("***** RESPONSE TOO LARGE (size - %d) *****", len(r.body)) } diff --git a/vendor/github.com/go-resty/resty/v2/resty.go b/vendor/github.com/go-resty/resty/v2/resty.go index 21dcd5655b95..6f9c8b4cd78e 100644 --- a/vendor/github.com/go-resty/resty/v2/resty.go +++ b/vendor/github.com/go-resty/resty/v2/resty.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -14,7 +14,7 @@ import ( ) // Version # of resty -const Version = "2.10.0" +const Version = "2.7.0" // New method creates a new Resty client. func New() *Client { diff --git a/vendor/github.com/go-resty/resty/v2/resty_test.go b/vendor/github.com/go-resty/resty/v2/resty_test.go index 67285bba48f4..367189245f2d 100644 --- a/vendor/github.com/go-resty/resty/v2/resty_test.go +++ b/vendor/github.com/go-resty/resty/v2/resty_test.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -6,14 +6,12 @@ package resty import ( "compress/gzip" - "crypto/md5" "encoding/base64" "encoding/json" "encoding/xml" - "errors" "fmt" "io" - "net" + "io/ioutil" "net/http" "net/http/httptest" "net/url" @@ -102,25 +100,18 @@ func createGetServer(t *testing.T) *httptest.Server { time.Sleep(time.Second * 6) _, _ = w.Write([]byte("TestClientTimeout page")) case "/my-image.png": - fileBytes, _ := os.ReadFile(filepath.Join(getTestDataPath(), "test-img.png")) + fileBytes, _ := ioutil.ReadFile(filepath.Join(getTestDataPath(), "test-img.png")) w.Header().Set("Content-Type", "image/png") w.Header().Set("Content-Length", strconv.Itoa(len(fileBytes))) _, _ = w.Write(fileBytes) case "/get-method-payload-test": - body, err := io.ReadAll(r.Body) + body, err := ioutil.ReadAll(r.Body) if err != nil { t.Errorf("Error: could not read get body: %s", err.Error()) } _, _ = w.Write(body) case "/host-header": _, _ = w.Write([]byte(r.Host)) - case "/not-found-with-error": - w.Header().Set(hdrContentTypeKey, "application/json") - w.WriteHeader(http.StatusNotFound) - _, _ = w.Write([]byte(`{"error": "Not found"}`)) - case "/not-found-no-error": - w.Header().Set(hdrContentTypeKey, "application/json") - w.WriteHeader(http.StatusNotFound) } switch { @@ -260,7 +251,7 @@ func createPostServer(t *testing.T) *httptest.Server { // JSON if IsJSONType(r.Header.Get(hdrContentTypeKey)) { if r.URL.Query().Get("status") == "500" { - body, err := io.ReadAll(r.Body) + body, err := ioutil.ReadAll(r.Body) if err != nil { t.Errorf("Error: could not read post body: %s", err.Error()) } @@ -299,13 +290,13 @@ func createPostServer(t *testing.T) *httptest.Server { w.Header().Set(hdrLocationKey, "/login") w.WriteHeader(http.StatusTemporaryRedirect) case "/redirect-with-body": - body, _ := io.ReadAll(r.Body) + body, _ := ioutil.ReadAll(r.Body) query := url.Values{} query.Add("body", string(body)) w.Header().Set(hdrLocationKey, "/redirected-with-body?"+query.Encode()) w.WriteHeader(http.StatusTemporaryRedirect) case "/redirected-with-body": - body, _ := io.ReadAll(r.Body) + body, _ := ioutil.ReadAll(r.Body) assertEqual(t, r.URL.Query().Get("body"), string(body)) w.WriteHeader(http.StatusOK) } @@ -591,7 +582,7 @@ func createGenServer(t *testing.T) *httptest.Server { } if r.Method == "REPORT" && r.URL.Path == "/report" { - body, _ := io.ReadAll(r.Body) + body, _ := ioutil.ReadAll(r.Body) if len(body) == 0 { w.WriteHeader(http.StatusOK) } @@ -631,166 +622,20 @@ func createRedirectServer(t *testing.T) *httptest.Server { return ts } -func createUnixSocketEchoServer(t *testing.T) string { - socketPath := filepath.Join(os.TempDir(), strconv.FormatInt(time.Now().Unix(), 10)) + ".sock" - - // Create a Unix domain socket and listen for incoming connections. - socket, err := net.Listen("unix", socketPath) - if err != nil { - t.Fatal(err) - } - - m := http.NewServeMux() - m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("Hi resty client from a server running on Unix domain socket!\n")) - }) - - m.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("Hello resty client from a server running on endpoint /hello!\n")) - }) - - go func(t *testing.T) { - server := http.Server{Handler: m} - if err := server.Serve(socket); err != nil { - t.Error(err) - } - }(t) - - return socketPath -} - -type digestServerConfig struct { - realm, qop, nonce, opaque, algo, uri, charset, username, password string -} - -func defaultDigestServerConf() *digestServerConfig { - return &digestServerConfig{ - realm: "testrealm@host.com", - qop: "auth", - nonce: "dcd98b7102dd2f0e8b11d0f600bfb0c093", - opaque: "5ccc069c403ebaf9f0171e9517f40e41", - algo: "MD5", - uri: "/dir/index.html", - charset: "utf-8", - username: "Mufasa", - password: "Circle Of Life", - } -} - -func createDigestServer(t *testing.T, conf *digestServerConfig) *httptest.Server { - if conf == nil { - conf = defaultDigestServerConf() - } - - setWWWAuthHeader := func(w http.ResponseWriter, v string) { - w.Header().Set("WWW-Authenticate", v) - w.WriteHeader(http.StatusUnauthorized) - } - ts := createTestServer(func(w http.ResponseWriter, r *http.Request) { - t.Logf("Method: %v", r.Method) - t.Logf("Path: %v", r.URL.Path) - - switch r.URL.Path { - case "/bad": - setWWWAuthHeader(w, "Bad Challenge") - return - case "/unknown_param": - setWWWAuthHeader(w, "Digest unknown_param=true") - return - case "/missing_value": - setWWWAuthHeader(w, `Digest realm="hello", domain`) - return - case "/no_challenge": - setWWWAuthHeader(w, "") - return - case "/status_500": - w.WriteHeader(http.StatusInternalServerError) - return - } - - w.Header().Set(hdrContentTypeKey, "application/json; charset=utf-8") - - if !authorizationHeaderValid(t, r, conf) { - setWWWAuthHeader(w, - fmt.Sprintf(`Digest realm="%s", domain="%s", qop="%s", algorithm=%s, nonce="%s", opaque="%s", userhash=true, charset=%s, stale=FALSE`, - conf.realm, conf.uri, conf.qop, conf.algo, conf.nonce, conf.opaque, conf.charset)) - _, _ = w.Write([]byte(`{ "id": "unauthorized", "message": "Invalid credentials" }`)) - } else { - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{ "id": "success", "message": "login successful" }`)) - } - }) - - return ts -} - -func authorizationHeaderValid(t *testing.T, r *http.Request, conf *digestServerConfig) bool { - h := func(data string) (string, error) { - hf := md5.New() - - _, err := io.WriteString(hf, data) - if err != nil { - return "", err - } - - return fmt.Sprintf("%x", hf.Sum(nil)), nil - } - input := r.Header.Get(hdrAuthorizationKey) - if input == "" { - return false - } - const ws = " \n\r\t" - const qs = `"` - s := strings.Trim(input, ws) - assertEqual(t, true, strings.HasPrefix(s, "Digest ")) - s = strings.Trim(s[7:], ws) - sl := strings.Split(s, ", ") - - pairs := make(map[string]string, len(sl)) - for i := range sl { - pair := strings.SplitN(sl[i], "=", 2) - pairs[pair[0]] = strings.Trim(pair[1], qs) - } - - assertEqual(t, conf.opaque, pairs["opaque"]) - assertEqual(t, conf.algo, pairs["algorithm"]) - assertEqual(t, "true", pairs["userhash"]) - - userhash, err := h(fmt.Sprintf("%s:%s", conf.username, conf.realm)) - assertError(t, err) - assertEqual(t, userhash, pairs["username"]) - - ha1, err := h(fmt.Sprintf("%s:%s:%s", conf.username, conf.realm, conf.password)) - assertError(t, err) - if strings.HasSuffix(conf.algo, "-sess") { - ha1, err = h(fmt.Sprintf("%s:%s:%s", ha1, pairs["nonce"], pairs["cnonce"])) - assertError(t, err) - } - ha2, err := h(fmt.Sprintf("%s:%s", r.Method, conf.uri)) - assertError(t, err) - nonceCount, err := strconv.Atoi(pairs["nc"]) - assertError(t, err) - kd, err := h(fmt.Sprintf("%s:%s", ha1, fmt.Sprintf("%s:%08x:%s:%s:%s", - pairs["nonce"], nonceCount, pairs["cnonce"], pairs["qop"], ha2))) - assertError(t, err) - - return kd == pairs["response"] -} - func createTestServer(fn func(w http.ResponseWriter, r *http.Request)) *httptest.Server { return httptest.NewServer(http.HandlerFunc(fn)) } func dc() *Client { c := New(). - outputLogTo(io.Discard) + outputLogTo(ioutil.Discard) return c } func dcl() *Client { c := New(). SetDebug(true). - outputLogTo(io.Discard) + outputLogTo(ioutil.Discard) return c } @@ -801,7 +646,7 @@ func dcr() *Request { func dclr() *Request { c := dc(). SetDebug(true). - outputLogTo(io.Discard) + outputLogTo(ioutil.Discard) return c.R() } @@ -829,14 +674,6 @@ func assertError(t *testing.T, err error) { } } -func assertErrorIs(t *testing.T, e, g error) (r bool) { - if !errors.Is(g, e) { - t.Errorf("Expected [%v], got [%v]", e, g) - } - - return true -} - func assertEqual(t *testing.T, e, g interface{}) (r bool) { if !equal(e, g) { t.Errorf("Expected [%v], got [%v]", e, g) diff --git a/vendor/github.com/go-resty/resty/v2/retry.go b/vendor/github.com/go-resty/resty/v2/retry.go index c5eda26be63b..f8c766597618 100644 --- a/vendor/github.com/go-resty/resty/v2/retry.go +++ b/vendor/github.com/go-resty/resty/v2/retry.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -209,9 +209,6 @@ func jitterBackoff(min, max time.Duration, attempt int) time.Duration { temp := math.Min(capLevel, base*math.Exp2(float64(attempt))) ri := time.Duration(temp / 2) - if ri == 0 { - ri = time.Nanosecond - } result := randDuration(ri) if result < min { diff --git a/vendor/github.com/go-resty/resty/v2/retry_test.go b/vendor/github.com/go-resty/resty/v2/retry_test.go index 8d58cc165f49..d979fbfe89c1 100644 --- a/vendor/github.com/go-resty/resty/v2/retry_test.go +++ b/vendor/github.com/go-resty/resty/v2/retry_test.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -295,20 +295,6 @@ func TestClientRetryWaitMaxInfinite(t *testing.T) { } } -func TestClientRetryWaitMaxMinimum(t *testing.T) { - ts := createGetServer(t) - defer ts.Close() - - const retryMaxWaitTime = time.Nanosecond // minimal duration value - - c := dc(). - SetRetryCount(1). - SetRetryMaxWaitTime(retryMaxWaitTime). - AddRetryCondition(func(*Response, error) bool { return true }) - _, err := c.R().Get(ts.URL + "/set-retrywaittime-test") - assertError(t, err) -} - func TestClientRetryWaitCallbackError(t *testing.T) { ts := createGetServer(t) defer ts.Close() @@ -616,18 +602,18 @@ func TestClientRetryPost(t *testing.T) { if resp != nil { if resp.StatusCode() == http.StatusInternalServerError { - t.Logf("Got response body: %s", resp.String()) + t.Logf("Got response body: %s", string(resp.body)) var usersResponse []map[string]interface{} err := json.Unmarshal(resp.body, &usersResponse) assertError(t, err) if !reflect.DeepEqual(users, usersResponse) { - t.Errorf("Expected request body to be echoed back as response body. Instead got: %s", resp.String()) + t.Errorf("Expected request body to be echoed back as response body. Instead got: %s", string(resp.body)) } return } - t.Errorf("Got unexpected response code: %d with body: %s", resp.StatusCode(), resp.String()) + t.Errorf("Got unexpected response code: %d with body: %s", resp.StatusCode(), string(resp.body)) } } @@ -751,7 +737,7 @@ func filler(*Response, error) bool { return false } -var errSeekFailure = fmt.Errorf("failing seek test") +var seekFailure = fmt.Errorf("failing seek test") type failingSeeker struct { reader *bytes.Reader @@ -763,7 +749,7 @@ func (f failingSeeker) Read(b []byte) (n int, err error) { func (f failingSeeker) Seek(offset int64, whence int) (int64, error) { if offset == 0 && whence == io.SeekStart { - return 0, errSeekFailure + return 0, seekFailure } return f.reader.Seek(offset, whence) @@ -788,7 +774,7 @@ func TestResetMultipartReaderSeekStartError(t *testing.T) { Post(ts.URL + "/set-reset-multipart-readers-test") assertEqual(t, 500, resp.StatusCode()) - assertEqual(t, err.Error(), errSeekFailure.Error()) + assertEqual(t, err.Error(), seekFailure.Error()) } func TestResetMultipartReaders(t *testing.T) { diff --git a/vendor/github.com/go-resty/resty/v2/trace.go b/vendor/github.com/go-resty/resty/v2/trace.go index be7555c2397a..23cf70335ebf 100644 --- a/vendor/github.com/go-resty/resty/v2/trace.go +++ b/vendor/github.com/go-resty/resty/v2/trace.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/go-resty/resty/v2/transport.go b/vendor/github.com/go-resty/resty/v2/transport.go index 191cd5193c1d..e15b48c551d7 100644 --- a/vendor/github.com/go-resty/resty/v2/transport.go +++ b/vendor/github.com/go-resty/resty/v2/transport.go @@ -1,7 +1,6 @@ -//go:build go1.13 // +build go1.13 -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -25,7 +24,7 @@ func createTransport(localAddr net.Addr) *http.Transport { } return &http.Transport{ Proxy: http.ProxyFromEnvironment, - DialContext: transportDialContext(dialer), + DialContext: dialer.DialContext, ForceAttemptHTTP2: true, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, diff --git a/vendor/github.com/go-resty/resty/v2/transport_other.go b/vendor/github.com/go-resty/resty/v2/transport_other.go deleted file mode 100644 index 73553c36f74c..000000000000 --- a/vendor/github.com/go-resty/resty/v2/transport_other.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2021 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !(js && wasm) -// +build !js !wasm - -package resty - -import ( - "context" - "net" -) - -func transportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) { - return dialer.DialContext -} diff --git a/vendor/github.com/go-resty/resty/v2/util.go b/vendor/github.com/go-resty/resty/v2/util.go index 27b466dc18b2..1d563befdb6d 100644 --- a/vendor/github.com/go-resty/resty/v2/util.go +++ b/vendor/github.com/go-resty/resty/v2/util.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -6,7 +6,6 @@ package resty import ( "bytes" - "errors" "fmt" "io" "log" @@ -65,16 +64,6 @@ func (l *logger) output(format string, v ...interface{}) { l.l.Printf(format, v...) } -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Rate Limiter interface -//_______________________________________________________________________ - -type RateLimiter interface { - Allow() bool -} - -var ErrRateLimitExceeded = errors.New("rate limit exceeded") - //‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ // Package Helper methods //_______________________________________________________________________ @@ -339,7 +328,25 @@ func silently(_ ...interface{}) {} func composeHeaders(c *Client, r *Request, hdrs http.Header) string { str := make([]string, 0, len(hdrs)) for _, k := range sortHeaderKeys(hdrs) { - str = append(str, "\t"+strings.TrimSpace(fmt.Sprintf("%25s: %s", k, strings.Join(hdrs[k], ", ")))) + var v string + if k == "Cookie" { + cv := strings.TrimSpace(strings.Join(hdrs[k], ", ")) + if c.GetClient().Jar != nil { + for _, c := range c.GetClient().Jar.Cookies(r.RawRequest.URL) { + if cv != "" { + cv = cv + "; " + c.String() + } else { + cv = c.String() + } + } + } + v = strings.TrimSpace(fmt.Sprintf("%25s: %s", k, cv)) + } else { + v = strings.TrimSpace(fmt.Sprintf("%25s: %s", k, strings.Join(hdrs[k], ", "))) + } + if v != "" { + str = append(str, "\t"+v) + } } return strings.Join(str, "\n") } diff --git a/vendor/github.com/go-resty/resty/v2/util_test.go b/vendor/github.com/go-resty/resty/v2/util_test.go index 74cf4b1f1b55..ef2bb915bb46 100644 --- a/vendor/github.com/go-resty/resty/v2/util_test.go +++ b/vendor/github.com/go-resty/resty/v2/util_test.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -23,18 +23,20 @@ func TestIsJSONType(t *testing.T) { {"application/vnd.foo+json; charset=utf-8", true}, {"text/json", true}, + {"text/xml+json", true}, {"text/vnd.foo+json", true}, - {"application/foo-json", true}, - {"application/foo.json", true}, - {"application/vnd.foo-json", true}, - {"application/vnd.foo.json", true}, - {"application/x-amz-json-1.1", true}, - - {"text/foo-json", true}, - {"text/foo.json", true}, - {"text/vnd.foo-json", true}, - {"text/vnd.foo.json", true}, + {"application/foo-json", false}, + {"application/foo.json", false}, + {"application/vnd.foo-json", false}, + {"application/vnd.foo.json", false}, + {"application/json+xml", false}, + + {"text/foo-json", false}, + {"text/foo.json", false}, + {"text/vnd.foo-json", false}, + {"text/vnd.foo.json", false}, + {"text/json+xml", false}, } { result := IsJSONType(test.input) @@ -50,23 +52,27 @@ func TestIsXMLType(t *testing.T) { expect bool }{ {"application/xml", true}, + {"application/json+xml", true}, {"application/vnd.foo+xml", true}, {"application/xml; charset=utf-8", true}, {"application/vnd.foo+xml; charset=utf-8", true}, {"text/xml", true}, + {"text/json+xml", true}, {"text/vnd.foo+xml", true}, - {"application/foo-xml", true}, - {"application/foo.xml", true}, - {"application/vnd.foo-xml", true}, - {"application/vnd.foo.xml", true}, - - {"text/foo-xml", true}, - {"text/foo.xml", true}, - {"text/vnd.foo-xml", true}, - {"text/vnd.foo.xml", true}, + {"application/foo-xml", false}, + {"application/foo.xml", false}, + {"application/vnd.foo-xml", false}, + {"application/vnd.foo.xml", false}, + {"application/xml+json", false}, + + {"text/foo-xml", false}, + {"text/foo.xml", false}, + {"text/vnd.foo-xml", false}, + {"text/vnd.foo.xml", false}, + {"text/xml+json", false}, } { result := IsXMLType(test.input) diff --git a/vendor/github.com/go-resty/resty/v2/ya.make b/vendor/github.com/go-resty/resty/v2/ya.make index ace1907a78f2..279f150aaf75 100644 --- a/vendor/github.com/go-resty/resty/v2/ya.make +++ b/vendor/github.com/go-resty/resty/v2/ya.make @@ -4,7 +4,6 @@ LICENSE(MIT) SRCS( client.go - digest.go middleware.go redirect.go request.go @@ -13,14 +12,12 @@ SRCS( retry.go trace.go transport.go - transport_other.go util.go ) GO_TEST_SRCS( client_test.go context_test.go - middleware_test.go request_test.go resty_test.go retry_test.go @@ -31,6 +28,4 @@ GO_XTEST_SRCS(example_test.go) END() -RECURSE( - gotest -) +RECURSE(gotest)