From aa7c48e13a748cfe05c39c0e836132ffcb5b5eb5 Mon Sep 17 00:00:00 2001 From: "Jeevanandam M." Date: Wed, 11 Sep 2024 21:08:44 -0700 Subject: [PATCH] doc: godoc improvements and corrections (#849) --- client.go | 209 ++++++++++++++----------------------- redirect.go | 5 +- request.go | 104 +++++++----------- response.go | 15 +-- resty.go | 2 +- retry.go | 2 +- shellescape/shellescape.go | 8 +- trace.go | 10 +- util.go | 4 - 9 files changed, 139 insertions(+), 220 deletions(-) diff --git a/client.go b/client.go index 48bfafde..3bdf0db7 100644 --- a/client.go +++ b/client.go @@ -96,7 +96,7 @@ type ( // these settings are applicable to all the request raised from the client. // // Resty also provides an options to override most of the client settings -// at request level. +// at [Request] level. type Client struct { BaseURL string HostURL string // Deprecated: use BaseURL instead. To be removed in v3.0.0 release. @@ -175,7 +175,7 @@ type User struct { // // Setting HTTPS address // client.SetHostURL("https://myjeeva.com") // -// Deprecated: use SetBaseURL instead. To be removed in v3.0.0 release. +// Deprecated: use [Client.SetBaseURL] instead. To be removed in v3.0.0 release. func (c *Client) SetHostURL(url string) *Client { c.SetBaseURL(url) return c @@ -189,8 +189,6 @@ func (c *Client) SetHostURL(url string) *Client { // // // Setting HTTPS address // client.SetBaseURL("https://myjeeva.com") -// -// Since v2.7.0 func (c *Client) SetBaseURL(url string) *Client { c.BaseURL = strings.TrimRight(url, "/") c.HostURL = c.BaseURL @@ -201,7 +199,7 @@ func (c *Client) SetBaseURL(url string) *Client { // These headers will be applied to all requests raised from this client instance. // Also it can be overridden at request level header options. // -// See `Request.SetHeader` or `Request.SetHeaders`. +// See [Request.SetHeader] or [Request.SetHeaders]. // // For Example: To set `Content-Type` and `Accept` as `application/json` // @@ -217,7 +215,7 @@ func (c *Client) SetHeader(header, value string) *Client { // These headers will be applied to all requests raised from this client instance. Also it can be // overridden at request level headers options. // -// See `Request.SetHeaders` or `Request.SetHeader`. +// See [Request.SetHeaders] or [Request.SetHeader]. // // For Example: To set `Content-Type` and `Accept` as `application/json` // @@ -241,16 +239,14 @@ func (c *Client) SetHeaders(headers map[string]string) *Client { // SetHeaderVerbatim("UPPERCASE", "available") // // Also you can override header value, which was set at client instance level. -// -// Since v2.6.0 func (c *Client) SetHeaderVerbatim(header, value string) *Client { c.Header[header] = []string{value} return c } -// SetCookieJar method sets custom http.CookieJar in the resty client. Its way to override default. +// SetCookieJar method sets custom [http.CookieJar] in the resty client. Its way to override default. // -// For Example: sometimes we don't want to save cookies in api contacting, we can remove the default +// For Example: sometimes we don't want to save cookies in API mode, we can remove the default // CookieJar in resty client. // // client.SetCookieJar(nil) @@ -295,11 +291,12 @@ func (c *Client) SetCookies(cs []*http.Cookie) *Client { // SetQueryParam method sets single parameter and its value in the client instance. // It will be formed as query string for the request. // -// For Example: `search=kitchen%20papers&size=large` -// in the URL after `?` mark. These query params will be added to all the request raised from +// For Example: `search=kitchen%20papers&size=large` +// +// In the URL after `?` mark. These query params will be added to all the request raised from // this client instance. Also it can be overridden at request level Query Param options. // -// See `Request.SetQueryParam` or `Request.SetQueryParams`. +// See [Request.SetQueryParam] or [Request.SetQueryParams]. // // client. // SetQueryParam("search", "kitchen papers"). @@ -312,11 +309,12 @@ func (c *Client) SetQueryParam(param, value string) *Client { // SetQueryParams method sets multiple parameters and their values at one go in the client instance. // It will be formed as query string for the request. // -// For Example: `search=kitchen%20papers&size=large` -// in the URL after `?` mark. These query params will be added to all the request raised from this +// For Example: `search=kitchen%20papers&size=large` +// +// In the URL after `?` mark. These query params will be added to all the request raised from this // client instance. Also it can be overridden at request level Query Param options. // -// See `Request.SetQueryParams` or `Request.SetQueryParam`. +// See [Request.SetQueryParams] or [Request.SetQueryParam]. // // client.SetQueryParams(map[string]string{ // "search": "kitchen papers", @@ -334,7 +332,7 @@ func (c *Client) SetQueryParams(params map[string]string) *Client { // `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. // -// See `Request.SetFormData`. +// See [Request.SetFormData]. // // client.SetFormData(map[string]string{ // "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", @@ -358,14 +356,14 @@ func (c *Client) SetFormData(data map[string]string) *Client { // This basic auth information gets added to all the request raised from this client instance. // Also it can be overridden or set one at the request level is supported. // -// See `Request.SetBasicAuth`. +// See [Request.SetBasicAuth]. func (c *Client) SetBasicAuth(username, password string) *Client { c.UserInfo = &User{Username: username, Password: password} return c } // SetAuthToken method sets the auth token of the `Authorization` header for all HTTP requests. -// The default auth scheme is `Bearer`, it can be customized with the method `SetAuthScheme`. For Example: +// The default auth scheme is `Bearer`, it can be customized with the method [Client.SetAuthScheme]. For Example: // // Authorization: // @@ -376,7 +374,7 @@ func (c *Client) SetBasicAuth(username, password string) *Client { // This auth token gets added to all the requests raised from this client instance. // Also it can be overridden or set one at the request level is supported. // -// See `Request.SetAuthToken`. +// See [Request.SetAuthToken]. func (c *Client) SetAuthToken(token string) *Client { c.Token = token return c @@ -393,13 +391,12 @@ func (c *Client) SetAuthToken(token string) *Client { // This auth scheme gets added to all the requests raised 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 the currently defined official authentication schemes: +// Information about auth schemes can be found in [RFC 7235], IANA [HTTP Auth schemes]. // -// https://tools.ietf.org/html/rfc7235 -// https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes +// See [Request.SetAuthToken]. // -// See `Request.SetAuthToken`. +// [RFC 7235]: https://tools.ietf.org/html/rfc7235 +// [HTTP Auth schemes]: https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes func (c *Client) SetAuthScheme(scheme string) *Client { c.AuthScheme = scheme return c @@ -412,11 +409,11 @@ func (c *Client) SetAuthScheme(scheme string) *Client { // // client.SetDigestAuth("Mufasa", "Circle Of Life") // -// Information about Digest Access Authentication can be found in RFC7616: +// Information about Digest Access Authentication can be found in [RFC 7616]. // -// https://datatracker.ietf.org/doc/html/rfc7616 +// See [Request.SetDigestAuth]. // -// See `Request.SetDigestAuth`. +// [RFC 7616]: https://datatracker.ietf.org/doc/html/rfc7616 func (c *Client) SetDigestAuth(username, password string) *Client { oldTransport := c.httpClient.Transport c.OnBeforeRequest(func(c *Client, _ *Request) error { @@ -501,7 +498,7 @@ func (c *Client) OnAfterResponse(m ResponseMiddleware) *Client { // OnError method adds a callback that will be run whenever a request execution fails. // This is called after all retries have been attempted (if any). -// If there was a response from the server, the error will be wrapped in *ResponseError +// If there was a response from the server, the error will be wrapped in [ResponseError] // which has the last response received from the server. // // client.OnError(func(req *resty.Request, err error) { @@ -511,8 +508,8 @@ func (c *Client) OnAfterResponse(m ResponseMiddleware) *Client { // // Log the error, increment a metric, etc... // }) // -// Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one -// set will be invoked for each call to Request.Execute() that completes. +// Out of the [Client.OnSuccess], [Client.OnError], [Client.OnInvalid], [Client.OnPanic] +// callbacks, exactly one set will be invoked for each call to [Request.Execute] that completes. func (c *Client) OnError(h ErrorHook) *Client { c.errorHooks = append(c.errorHooks, h) return c @@ -521,10 +518,8 @@ func (c *Client) OnError(h ErrorHook) *Client { // OnSuccess method adds a callback that will be run whenever a request execution // 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 +// Out of the [Client.OnSuccess], [Client.OnError], [Client.OnInvalid], [Client.OnPanic] +// callbacks, exactly one set will be invoked for each call to [Request.Execute] that completes. func (c *Client) OnSuccess(h SuccessHook) *Client { c.successHooks = append(c.successHooks, h) return c @@ -533,10 +528,8 @@ func (c *Client) OnSuccess(h SuccessHook) *Client { // OnInvalid method adds a callback that will be run whenever 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 +// Out of the [Client.OnSuccess], [Client.OnError], [Client.OnInvalid], [Client.OnPanic] +// callbacks, exactly one set will be invoked for each call to [Request.Execute] that completes. func (c *Client) OnInvalid(h ErrorHook) *Client { c.invalidHooks = append(c.invalidHooks, h) return c @@ -545,12 +538,11 @@ func (c *Client) OnInvalid(h ErrorHook) *Client { // OnPanic method adds a callback that will be run whenever 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. +// Out of the [Client.OnSuccess], [Client.OnError], [Client.OnInvalid], [Client.OnPanic] +// callbacks, exactly one set will be invoked for each call to [Request.Execute] that completes. // -// Since v2.8.0 +// If an [Client.OnSuccess], [Client.OnError], or [Client.OnInvalid] callback panics, +// then the exactly one rule can be violated. func (c *Client) OnPanic(h ErrorHook) *Client { c.panicHooks = append(c.panicHooks, h) return c @@ -559,7 +551,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 multiple. func (c *Client) SetPreRequestHook(h PreRequestHook) *Client { if c.preReqHook != nil { c.log.Warnf("Overwriting an existing pre-request hook: %s", functionName(h)) @@ -569,12 +561,12 @@ func (c *Client) SetPreRequestHook(h PreRequestHook) *Client { } // SetDebug method enables the debug mode on Resty client. Client logs details of every 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. +// 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.SetDebug(true) // -// Also it can be enabled at request level for particular request, see `Request.SetDebug`. +// 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 @@ -632,7 +624,7 @@ func (c *Client) SetAllowGetMethodPayload(a bool) *Client { // SetLogger method sets given writer for logging Resty request and response details. // -// Compliant to interface `resty.Logger`. +// Compliant to interface [resty.Logger] func (c *Client) SetLogger(l Logger) *Client { c.log = l return c @@ -643,7 +635,7 @@ func (c *Client) SetLogger(l Logger) *Client { // // client.SetContentLength(true) // -// Also you have an option to enable for particular request. See `Request.SetContentLength` +// Also you have an option to enable for particular request. See [Request.SetContentLength] func (c *Client) SetContentLength(l bool) *Client { c.setContentLength = l return c @@ -729,36 +721,28 @@ func (c *Client) SetRetryAfter(callback RetryAfterFunc) *Client { } // 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 +// By default, Resty uses [encoding/json] package to marshal the request body. 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 +// By default, Resty uses [encoding/json] package to unmarshal the response body. 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 +// By default, Resty uses [encoding/xml] package to marshal the request body. 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 +// By default, Resty uses [encoding/xml] package to unmarshal the response body. func (c *Client) SetXMLUnmarshaler(unmarshaler func(data []byte, v interface{}) error) *Client { c.XMLUnmarshal = unmarshaler return c @@ -768,8 +752,8 @@ func (c *Client) SetXMLUnmarshaler(unmarshaler func(data []byte, v interface{}) // 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. // -// Note: These retry conditions are applied on all Request made using this Client. -// For Request specific retry conditions check *Request.AddRetryCondition +// NOTE: These retry conditions are applied on all Request made using this Client. +// For [Request] specific retry conditions check [Request.AddRetryCondition] func (c *Client) AddRetryCondition(condition RetryConditionFunc) *Client { c.RetryConditions = append(c.RetryConditions, condition) return c @@ -777,8 +761,6 @@ func (c *Client) AddRetryCondition(condition RetryConditionFunc) *Client { // AddRetryAfterErrorCondition adds the basic condition of retrying after encountering // an error from the http response -// -// Since v2.6.0 func (c *Client) AddRetryAfterErrorCondition() *Client { c.AddRetryCondition(func(response *Response, err error) bool { return response.IsError() @@ -788,17 +770,13 @@ func (c *Client) AddRetryAfterErrorCondition() *Client { // AddRetryHook adds a side-effecting retry hook to an array of hooks // that will be executed on each retry. -// -// Since v2.6.0 func (c *Client) AddRetryHook(hook OnRetryFunc) *Client { c.RetryHooks = append(c.RetryHooks, hook) return c } // SetRetryResetReaders method enables the Resty client to seek the start of all -// file readers given as multipart files, if the given object implements `io.ReadSeeker`. -// -// Since ... +// file readers given as multipart files, if the given object implements [io.ReadSeeker]. func (c *Client) SetRetryResetReaders(b bool) *Client { c.RetryResetReaders = b return c @@ -814,7 +792,7 @@ func (c *Client) SetRetryResetReaders(b bool) *Client { // // or One can disable security check (https) // client.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true }) // -// Note: This method overwrites existing `TLSClientConfig`. +// NOTE: This method overwrites existing [http.Transport.TLSClientConfig] func (c *Client) SetTLSClientConfig(config *tls.Config) *Client { transport, err := c.Transport() if err != nil { @@ -829,9 +807,7 @@ func (c *Client) SetTLSClientConfig(config *tls.Config) *Client { // // client.SetProxy("http://proxyserver:8888") // -// OR Without this `SetProxy` method, you could also set Proxy via environment variable. -// -// Refer to godoc `http.ProxyFromEnvironment`. +// OR you could also set Proxy via environment variable, refer to [http.ProxyFromEnvironment] func (c *Client) SetProxy(proxyURL string) *Client { transport, err := c.Transport() if err != nil { @@ -940,7 +916,7 @@ func (c *Client) handleCAs(scope string, permCerts []byte) { // SetOutputDirectory method sets output directory for saving HTTP response into file. // If the output directory not exists then resty creates one. This setting is optional one, -// if you're planning using absolute path in `Request.SetOutput` and can used together. +// if you're planning using absolute path in [Request.SetOutput] and can used together. // // client.SetOutputDirectory("/save/http/response/here") func (c *Client) SetOutputDirectory(dirPath string) *Client { @@ -948,33 +924,28 @@ func (c *Client) SetOutputDirectory(dirPath string) *Client { return c } -// SetRateLimiter sets an optional `RateLimiter`. If set the rate limiter will control +// 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` +// SetTransport method sets custom [http.Transport] or any [http.RoundTripper] // compatible interface implementation in the resty client. // -// Note: -// -// - If transport is not type of `*http.Transport` then you may not be able to -// take advantage of some of the Resty client settings. -// -// - It overwrites the Resty client transport instance and it's configurations. -// // transport := &http.Transport{ // // something like Proxying to httptest.Server, etc... // Proxy: func(req *http.Request) (*url.URL, error) { // return url.Parse(server.URL) // }, // } -// // client.SetTransport(transport) +// +// NOTE: +// - If transport is not type of `*http.Transport` then you may not be able to +// take advantage of some of the Resty client settings. +// - It overwrites the Resty client transport instance and it's configurations. func (c *Client) SetTransport(transport http.RoundTripper) *Client { if transport != nil { c.httpClient.Transport = transport @@ -1000,10 +971,10 @@ func (c *Client) SetCloseConnection(close bool) *Client { } // SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically. -// Resty exposes the raw response body as `io.ReadCloser`. Also do not forget to close the body, +// Resty exposes the raw response body as [io.ReadCloser]. Also do not forget to close the body, // otherwise you might get into connection leaks, no connection reuse. // -// Note: Response middlewares are not applicable, if you use this option. Basically you have +// NOTE: [Response] middlewares are not applicable, if you use this option. Basically you have // taken over the control of response parsing from `Resty`. func (c *Client) SetDoNotParseResponse(notParse bool) *Client { c.notParseResponse = notParse @@ -1020,10 +991,10 @@ func (c *Client) SetDoNotParseResponse(notParse 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. +// 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`. +// see [Request.SetPathParam] or [Request.SetPathParams] func (c *Client) SetPathParam(param, value string) *Client { c.PathParams[param] = value return c @@ -1043,10 +1014,10 @@ func (c *Client) SetPathParam(param, value string) *Client { // Composed URL - /v1/users/sample@sample.com/100002/groups%2Fdevelopers/details // // It replaces the value of the key while composing the request URL. -// The values will be escaped using `url.PathEscape` function. +// 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`. +// see [Request.SetPathParam] or [Request.SetPathParams] func (c *Client) SetPathParams(params map[string]string) *Client { for p, v := range params { c.SetPathParam(p, v) @@ -1073,9 +1044,7 @@ func (c *Client) SetPathParams(params map[string]string) *Client { // 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 +// see [Request.SetRawPathParam] or [Request.SetRawPathParams] func (c *Client) SetRawPathParam(param, value string) *Client { c.RawPathParams[param] = value return c @@ -1098,9 +1067,7 @@ func (c *Client) SetRawPathParam(param, value string) *Client { // 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 +// see [Request.SetRawPathParam] or [Request.SetRawPathParams] func (c *Client) SetRawPathParams(params map[string]string) *Client { for p, v := range params { c.SetRawPathParam(p, v) @@ -1110,7 +1077,7 @@ func (c *Client) SetRawPathParams(params map[string]string) *Client { // SetJSONEscapeHTML method is to enable/disable the HTML escape on JSON marshal. // -// Note: This option only applicable to standard JSON Marshaller. +// NOTE: This option only applicable to standard JSON Marshaller. func (c *Client) SetJSONEscapeHTML(b bool) *Client { c.jsonEscapeHTML = b return c @@ -1131,7 +1098,7 @@ func (c *Client) SetResponseBodyLimit(v int) *Client { } // EnableTrace method enables the Resty client trace for the requests fired from -// the client using `httptrace.ClientTrace` and provides insights. +// the client using [httptrace.ClientTrace] and provides insights. // // client := resty.New().EnableTrace() // @@ -1139,17 +1106,13 @@ func (c *Client) SetResponseBodyLimit(v int) *Client { // fmt.Println("Error:", err) // fmt.Println("Trace Info:", resp.Request.TraceInfo()) // -// Also `Request.EnableTrace` available too to get trace info for single request. -// -// Since v2.0.0 +// Also [Request.EnableTrace] available too to get trace info for single request. func (c *Client) EnableTrace() *Client { c.trace = true return c } -// DisableTrace method disables the Resty client trace. Refer to `Client.EnableTrace`. -// -// Since v2.0.0 +// DisableTrace method disables the Resty client trace. Refer to [Client.EnableTrace]. func (c *Client) DisableTrace() *Client { c.trace = false return c @@ -1173,25 +1136,23 @@ func (c *Client) DisableGenerateCurlOnDebug() *Client { } // IsProxySet method returns the true is proxy is set from resty client otherwise -// false. By default proxy is set from environment, refer to `http.ProxyFromEnvironment`. +// false. By default proxy is set from environment, refer to [http.ProxyFromEnvironment]. func (c *Client) IsProxySet() bool { return c.proxyURL != nil } -// GetClient method returns the current `http.Client` used by the resty client. +// GetClient method returns the current [http.Client] used by the resty client. func (c *Client) GetClient() *http.Client { return c.httpClient } // Clone returns a clone of the original client. // -// Be careful when using this function: -// - Interface values are not deeply cloned. Thus, both the original and the clone will use the -// same value. -// - This function is not safe for concurrent use. You should only use this when you are sure that -// the client is not being used by any other goroutine. -// -// Since v2.12.0 +// NOTE: Use with care: +// - Interface values are not deeply cloned. Thus, both the original and the +// clone will use the same value. +// - This function is not safe for concurrent use. You should only use this +// when you are sure that the client is not being used by any other goroutine. func (c *Client) Clone() *Client { // dereference the pointer and copy the value cc := *c @@ -1202,10 +1163,6 @@ func (c *Client) Clone() *Client { return &cc } -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Client Unexported methods -//_______________________________________________________________________ - func (c *Client) executeBefore(req *Request) error { // Lock the user-defined pre-request hooks. c.udBeforeRequestLock.RLock() @@ -1372,8 +1329,8 @@ func (c *Client) tlsConfig() (*tls.Config, error) { return transport.TLSClientConfig, nil } -// Transport method returns `*http.Transport` currently in use or error -// in case currently used `transport` is not a `*http.Transport`. +// 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) { @@ -1405,7 +1362,7 @@ func (e *ResponseError) Unwrap() error { } // Helper to run errorHooks hooks. -// It wraps the error in a ResponseError if the resp is not nil +// It wraps the error in a [ResponseError] if the resp is not nil // so hooks can access it. func (c *Client) onErrorHooks(req *Request, resp *Response, err error) { if err != nil { @@ -1464,10 +1421,6 @@ type MultipartField struct { io.Reader } -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Unexported package methods -//_______________________________________________________________________ - func createClient(hc *http.Client) *Client { if hc.Transport == nil { hc.Transport = createTransport(nil) diff --git a/redirect.go b/redirect.go index 19bd587d..fececc41 100644 --- a/redirect.go +++ b/redirect.go @@ -13,13 +13,12 @@ import ( ) 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 + // Objects implementing the [RedirectPolicy] interface can be registered as // // Apply function should return nil to continue the redirect journey, otherwise // return error to stop the redirect. @@ -27,7 +26,7 @@ type ( Apply(req *http.Request, via []*http.Request) error } - // The RedirectPolicyFunc type is an adapter to allow the use of ordinary functions as RedirectPolicy. + // The [RedirectPolicyFunc] type is an adapter to allow the use of ordinary functions as [RedirectPolicy]. // If f is a function with the appropriate signature, RedirectPolicyFunc(f) is a RedirectPolicy object that calls f. RedirectPolicyFunc func(*http.Request, []*http.Request) error ) diff --git a/request.go b/request.go index 8ad4a6ad..241e4618 100644 --- a/request.go +++ b/request.go @@ -49,8 +49,6 @@ type Request struct { // Attempt is to represent the request attempt made during a Resty // request execution flow, including retry count. - // - // Since v2.4.0 Attempt int isMultiPart bool @@ -98,7 +96,7 @@ func (r *Request) GenerateCurlCommand() string { } // Context method returns the Context if its already set in request -// otherwise it creates new one using `context.Background()`. +// otherwise it creates new one using [context.Background]. func (r *Request) Context() context.Context { if r.ctx == nil { return context.Background() @@ -106,7 +104,7 @@ func (r *Request) Context() context.Context { return r.ctx } -// SetContext method sets the context.Context for current Request. It allows +// SetContext method sets the [context.Context] for current [Request]. It allows // to interrupt the request execution if ctx.Done() channel is closed. // See https://blog.golang.org/context article and the "context" package // documentation. @@ -173,8 +171,6 @@ func (r *Request) SetHeaderMultiValues(headers map[string][]string) *Request { // SetHeaderVerbatim("UPPERCASE", "available") // // Also you can override header value, which was set at client instance level. -// -// Since v2.6.0 func (r *Request) SetHeaderVerbatim(header, value string) *Request { r.Header[header] = []string{value} return r @@ -215,7 +211,7 @@ func (r *Request) SetQueryParams(params map[string]string) *Request { } // SetQueryParamsFromValues method appends multiple parameters with multi-value -// (`url.Values`) at one go in the current request. It will be formed as +// ([url.Values]) at one go in the current request. It will be formed as // query string for the request. // // For Example: `status=pending&status=approved&status=open` in the URL after `?` mark. @@ -274,7 +270,7 @@ func (r *Request) SetFormData(data map[string]string) *Request { } // SetFormDataFromValues method appends multiple form parameters with multi-value -// (`url.Values`) at one go in the current request. +// ([url.Values]) at one go in the current request. // // client.R(). // SetFormDataFromValues(url.Values{ @@ -293,10 +289,10 @@ func (r *Request) SetFormDataFromValues(data url.Values) *Request { // SetBody method sets the request body for the request. It supports various realtime needs as easy. // We can say its quite handy or powerful. Supported request body data types is `string`, -// `[]byte`, `struct`, `map`, `slice` and `io.Reader`. Body value can be pointer or non-pointer. +// `[]byte`, `struct`, `map`, `slice` and [io.Reader]. Body value can be pointer or non-pointer. // Automatic marshalling for JSON and XML content type, if it is `struct`, `map`, or `slice`. // -// Note: `io.Reader` is processed as bufferless mode while sending request. +// NOTE: [io.Reader] is processed as bufferless mode while sending request. // // For Example: Struct as a body input, based on content type, it will be marshalled. // @@ -341,7 +337,7 @@ func (r *Request) SetBody(body interface{}) *Request { // SetResult method is to register the response `Result` object for automatic unmarshalling for the request, // if response status code is between 200 and 299 and content type either JSON or XML. // -// Note: Result object can be pointer or non-pointer. +// NOTE: Result object can be pointer or non-pointer. // // client.R().SetResult(&AuthToken{}) // // OR @@ -360,7 +356,7 @@ func (r *Request) SetResult(res interface{}) *Request { // SetError method is to register the request `Error` object for automatic unmarshalling for the request, // if response status code is greater than 399 and content type either JSON or XML. // -// Note: Error object can be pointer or non-pointer. +// NOTE: Error object can be pointer or non-pointer. // // client.R().SetError(&AuthError{}) // // OR @@ -436,7 +432,7 @@ func (r *Request) SetMultipartField(param, fileName, contentType string, reader return r } -// SetMultipartFields method is to set multiple data fields using io.Reader for multipart upload. +// SetMultipartFields method is to set multiple data fields using [io.Reader] for multipart upload. // // For Example: // @@ -465,8 +461,6 @@ func (r *Request) SetMultipartFields(fields ...*MultipartField) *Request { // SetMultipartBoundary method sets the custom multipart boundary for the multipart request. // Typically, the `mime/multipart` package generates a random multipart boundary, if not provided. -// -// Since v2.15.0 func (r *Request) SetMultipartBoundary(boundary string) *Request { r.multipartBoundary = boundary return r @@ -476,7 +470,7 @@ func (r *Request) SetMultipartBoundary(boundary string) *Request { // By default Resty won't set `Content-Length`. Also you have an option to enable for every // request. // -// See `Client.SetContentLength` +// See [Client.SetContentLength] // // client.R().SetContentLength(true) func (r *Request) SetContentLength(l bool) *Request { @@ -494,7 +488,7 @@ func (r *Request) SetContentLength(l bool) *Request { // // client.R().SetBasicAuth("go-resty", "welcome") // -// This method overrides the credentials set by method `Client.SetBasicAuth`. +// This method overrides the credentials set by method [Client.SetBasicAuth]. func (r *Request) SetBasicAuth(username, password string) *Request { r.UserInfo = &User{Username: username, Password: password} return r @@ -508,7 +502,7 @@ func (r *Request) SetBasicAuth(username, password string) *Request { // // client.R().SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") // -// This method overrides the Auth token set by method `Client.SetAuthToken`. +// This method overrides the Auth token set by method [Client.SetAuthToken]. func (r *Request) SetAuthToken(token string) *Request { r.Token = token return r @@ -525,30 +519,30 @@ func (r *Request) SetAuthToken(token string) *Request { // This auth header scheme gets added to all the request raised 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 -// the currently defined official authentication schemes: +// Information about Auth schemes can be found in [RFC 7235], IANA [HTTP Auth schemes] // -// https://tools.ietf.org/html/rfc7235 -// https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes +// This method overrides the Authorization scheme set by method [Client.SetAuthScheme]. // -// This method overrides the Authorization scheme set by method `Client.SetAuthScheme`. +// [RFC 7235]: https://tools.ietf.org/html/rfc7235 +// [HTTP Auth schemes]: https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes func (r *Request) SetAuthScheme(scheme string) *Request { r.AuthScheme = scheme 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. +// 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: +// Information about Digest Access Authentication can be found in [RFC 7616] // -// https://datatracker.ietf.org/doc/html/rfc7616 +// This method overrides the username and password set by method [Client.SetDigestAuth]. // -// This method overrides the username and password set by method `Client.SetDigestAuth`. +// [RFC 7616]: https://datatracker.ietf.org/doc/html/rfc7616 func (r *Request) SetDigestAuth(username, password string) *Request { oldTransport := r.client.httpClient.Transport r.client.OnBeforeRequest(func(c *Client, _ *Request) error { @@ -569,13 +563,13 @@ func (r *Request) SetDigestAuth(username, password string) *Request { // 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 -// in the `Client.SetOutputDirectory`. +// in the [Client.SetOutputDirectory]. // // client.R(). // SetOutput("/Users/jeeva/Downloads/ReplyWithHeader-v5.1-beta.zip"). // Get("http://bit.ly/1LouEKr") // -// Note: In this scenario `Response.Body` might be nil. +// NOTE: In this scenario [Response.Body] might be nil. func (r *Request) SetOutput(file string) *Request { r.outputFile = file r.isSaveResponse = true @@ -594,10 +588,10 @@ func (r *Request) SetSRV(srv *SRVRecord) *Request { } // SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically. -// Resty exposes the raw response body as `io.ReadCloser`. Also do not forget to close the body, +// Resty exposes the raw response body as [io.ReadCloser]. Also do not forget to close the body, // otherwise you might get into connection leaks, no connection reuse. // -// Note: Response middlewares are not applicable, if you use this option. Basically you have +// NOTE: [Response] middlewares are not applicable, if you use this option. Basically you have // taken over the control of response parsing from `Resty`. func (r *Request) SetDoNotParseResponse(parse bool) *Request { r.notParseResponse = parse @@ -688,8 +682,6 @@ func (r *Request) SetPathParams(params map[string]string) *Request { // // 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 @@ -713,8 +705,6 @@ func (r *Request) SetRawPathParam(param, value string) *Request { // // 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) @@ -731,7 +721,7 @@ func (r *Request) ExpectContentType(contentType string) *Request { // ForceContentType method provides a strong sense of response `Content-Type` for automatic unmarshalling. // Resty gives this a higher priority than the `Content-Type` response header. This means that if both -// `Request.ForceContentType` is set and the response `Content-Type` is available, `ForceContentType` will win. +// [Request.ForceContentType] is set and the response `Content-Type` is available, `ForceContentType` will win. func (r *Request) ForceContentType(contentType string) *Request { r.forceContentType = contentType return r @@ -739,7 +729,7 @@ func (r *Request) ForceContentType(contentType string) *Request { // SetJSONEscapeHTML method is to enable/disable the HTML escape on JSON marshal. // -// Note: This option only applicable to standard JSON Marshaller. +// NOTE: This option only applicable to standard JSON Marshaller. func (r *Request) SetJSONEscapeHTML(b bool) *Request { r.jsonEscapeHTML = b return r @@ -752,9 +742,7 @@ func (r *Request) SetJSONEscapeHTML(b bool) *Request { // Value:"This is cookie value", // }) // -// Note: Method appends the Cookie value into existing Cookie if already existing. -// -// Since v2.1.0 +// NOTE: Method appends the Cookie value into existing Cookie if already existing. func (r *Request) SetCookie(hc *http.Cookie) *Request { r.Cookies = append(r.Cookies, hc) return r @@ -776,9 +764,7 @@ func (r *Request) SetCookie(hc *http.Cookie) *Request { // // Setting a cookies into resty's current request // client.R().SetCookies(cookies) // -// Note: Method appends the Cookie value into existing Cookie if already existing. -// -// Since v2.1.0 +// NOTE: Method appends the Cookie value into existing Cookie if already existing. func (r *Request) SetCookies(rs []*http.Cookie) *Request { r.Cookies = append(r.Cookies, rs...) return r @@ -787,7 +773,7 @@ func (r *Request) SetCookies(rs []*http.Cookie) *Request { // SetLogger method sets given writer for logging Resty request and response details. // By default, requests and responses inherit their logger from the client. // -// Compliant to interface `resty.Logger`. +// Compliant to interface [resty.Logger]. func (r *Request) SetLogger(l Logger) *Request { r.log = l return r @@ -795,8 +781,8 @@ func (r *Request) SetLogger(l Logger) *Request { // 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. +// 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 { @@ -808,9 +794,7 @@ func (r *Request) SetDebug(d bool) *Request { // 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. // -// Note: These retry conditions are checked before all retry conditions of the client. -// -// Since v2.7.0 +// NOTE: These retry conditions are checked before all retry conditions of the client. func (r *Request) AddRetryCondition(condition RetryConditionFunc) *Request { r.retryConditions = append(r.retryConditions, condition) return r @@ -821,7 +805,7 @@ func (r *Request) AddRetryCondition(condition RetryConditionFunc) *Request { //_______________________________________________________________________ // EnableTrace method enables trace for the current request -// using `httptrace.ClientTrace` and provides insights. +// using [httptrace.ClientTrace] and provides insights. // // client := resty.New() // @@ -829,9 +813,7 @@ func (r *Request) AddRetryCondition(condition RetryConditionFunc) *Request { // fmt.Println("Error:", err) // fmt.Println("Trace Info:", resp.Request.TraceInfo()) // -// See `Client.EnableTrace` available too to get trace info for all requests. -// -// Since v2.0.0 +// See [Client.EnableTrace] available too to get trace info for all requests. func (r *Request) EnableTrace() *Request { r.trace = true return r @@ -856,10 +838,8 @@ func (r *Request) DisableGenerateCurlOnDebug() *Request { } // TraceInfo method returns the trace info for the request. -// If either the Client or Request EnableTrace function has not been called -// prior to the request being made, an empty TraceInfo object will be returned. -// -// Since v2.0.0 +// If either the [Client.EnableTrace] or [Request.EnableTrace] function has not been called +// prior to the request being made, an empty [resty.TraceInfo] object will be returned. func (r *Request) TraceInfo() TraceInfo { ct := r.clientTrace @@ -948,7 +928,7 @@ func (r *Request) Patch(url string) (*Response, error) { } // Send method performs the HTTP request using the method and URL already defined -// for current `Request`. +// for current [Request]. // // req := client.R() // req.Method = resty.MethodGet @@ -959,7 +939,7 @@ func (r *Request) Send() (*Response, error) { } // Execute method performs the HTTP request with given HTTP method and URL -// for current `Request`. +// for current [Request]. // // resp, err := client.R().Execute(resty.MethodGet, "http://httpbin.org/get") func (r *Request) Execute(method, url string) (*Response, error) { @@ -1043,10 +1023,6 @@ type SRVRecord struct { Domain string } -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Request Unexported methods -//_______________________________________________________________________ - func (r *Request) fmtBodyString(sl int64) (body string) { body = "***** NO CONTENT *****" if !isPayloadSupported(r.Method, r.client.AllowGetMethodPayload) { diff --git a/response.go b/response.go index 58a8e816..5a85aac1 100644 --- a/response.go +++ b/response.go @@ -29,7 +29,7 @@ type Response struct { // Body method returns HTTP response as []byte array for the executed request. // -// Note: `Response.Body` might be nil, if `Request.SetOutput` is used. +// NOTE: [Response.Body] might be nil, if [Request.SetOutput] is used. func (r *Response) Body() []byte { if r.RawResponse == nil { return []byte{} @@ -37,13 +37,11 @@ func (r *Response) Body() []byte { return r.body } -// SetBody method is to set Response body in byte slice. Typically, +// 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 @@ -113,7 +111,7 @@ func (r *Response) String() string { // Time method returns the time of HTTP response time that from request we sent and received a request. // -// See `Response.ReceivedAt` to know when client received response and see `Response.Request.Time` to know +// See [Response.ReceivedAt] to know when client received response and see `Response.Request.Time` to know // when client sent a request. func (r *Response) Time() time.Duration { if r.Request.clientTrace != nil { @@ -134,7 +132,8 @@ func (r *Response) Size() int64 { return r.size } -// RawBody method exposes the HTTP raw response body. Use this method in-conjunction with `SetDoNotParseResponse` +// RawBody method exposes the HTTP raw response body. Use this method in-conjunction with +// [Client.SetDoNotParseResponse] or [Request.SetDoNotParseResponse] // option otherwise you get an error as `read err: http: read on closed response body`. // // Do not forget to close the body, otherwise you might get into connection leaks, no connection reuse. @@ -156,10 +155,6 @@ func (r *Response) IsError() bool { return r.StatusCode() > 399 } -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Response Unexported methods -//_______________________________________________________________________ - func (r *Response) setReceivedAt() { r.receivedAt = time.Now() if r.Request.clientTrace != nil { diff --git a/resty.go b/resty.go index 7458af76..85451744 100644 --- a/resty.go +++ b/resty.go @@ -24,7 +24,7 @@ func New() *Client { }) } -// NewWithClient method creates a new Resty client with given `http.Client`. +// NewWithClient method creates a new Resty client with given [http.Client]. func NewWithClient(hc *http.Client) *Client { return createClient(hc) } diff --git a/retry.go b/retry.go index 932a266d..16f54169 100644 --- a/retry.go +++ b/retry.go @@ -84,7 +84,7 @@ func RetryHooks(hooks []OnRetryFunc) Option { } // ResetMultipartReaders sets a boolean value which will lead the start being seeked out -// on all multipart file readers, if they implement io.ReadSeeker +// on all multipart file readers, if they implement [io.ReadSeeker] func ResetMultipartReaders(value bool) Option { return func(o *Options) { o.resetReaders = value diff --git a/shellescape/shellescape.go b/shellescape/shellescape.go index 5e6a3799..c46b5e76 100644 --- a/shellescape/shellescape.go +++ b/shellescape/shellescape.go @@ -1,5 +1,11 @@ +// Copyright (c) 2015-present Jeevanandam M (jeeva@myjeeva.com) +// 2024 Ahuigo (https://github.com/ahuigo) +// All rights reserved. +// resty source code and usage is governed by a MIT style +// license that can be found in the LICENSE file. + /* -Package shellescape provides the shellescape.Quote to escape arbitrary +Package shellescape provides the methods to escape arbitrary strings for a safe use as command line arguments in the most common POSIX shells. diff --git a/trace.go b/trace.go index 7798a395..2fb2ceb0 100644 --- a/trace.go +++ b/trace.go @@ -18,8 +18,6 @@ import ( // TraceInfo struct is used provide request trace info such as DNS lookup // duration, Connection obtain duration, Server processing duration, etc. -// -// Since v2.0.0 type TraceInfo struct { // DNSLookup is a duration that transport took to perform // DNS lookup. @@ -68,9 +66,9 @@ type TraceInfo struct { // ClientTrace struct and its methods //_______________________________________________________________________ -// tracer struct maps the `httptrace.ClientTrace` hooks into Fields +// tracer struct maps the [httptrace.ClientTrace] hooks into Fields // with same naming for easy understanding. Plus additional insights -// Request. +// [Request]. type clientTrace struct { getConn time.Time dnsStart time.Time @@ -84,10 +82,6 @@ type clientTrace struct { gotConnInfo httptrace.GotConnInfo } -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Trace unexported methods -//_______________________________________________________________________ - func (t *clientTrace) createContext(ctx context.Context) context.Context { return httptrace.WithClientTrace( ctx, diff --git a/util.go b/util.go index 7bbba912..812dce3d 100644 --- a/util.go +++ b/util.go @@ -145,10 +145,6 @@ type ResponseLog struct { Body string } -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Package Unexported methods -//_______________________________________________________________________ - // way to disable the HTML escape as opt-in func jsonMarshal(c *Client, r *Request, d interface{}) (*bytes.Buffer, error) { if !r.jsonEscapeHTML || !c.jsonEscapeHTML {