Client is the req's http client.AllowGetMethodPayloadboolBaseURLstringDebugLogboolFormDataurlpkg.ValuesPathParamsmap[string]stringQueryParamsurlpkg.ValuesTransport*TransportTransport.Cookies[]*http.CookieTransport.Headershttp.Header AutoDecompression, if true, enables automatic decompression of
compressed responses. It is equivalent to setting the Accept-Encoding
header to "gzip, deflate, br, zstd" and the Transport will handle the
decompression of the response transparently, returning the uncompressed. Debugf is the optional debug function. DialContext specifies the dial function for creating unencrypted TCP connections.
If DialContext is nil, then the transport dials using package net.
DialContext runs concurrently with calls to RoundTrip.
A RoundTrip call that initiates a dial may end up using
a connection dialed previously when the earlier connection
becomes idle before the later DialContext completes. DialTLSContext specifies an optional dial function for creating
TLS connections for non-proxied HTTPS requests.
If DialTLSContext is nil, DialContext and TLSClientConfig are used.
If DialTLSContext is set, the Dial and DialContext hooks are not used for HTTPS
requests and the TLSClientConfig and TLSHandshakeTimeout
are ignored. The returned net.Conn is assumed to already be
past the TLS handshake.Transport.Options.Dump*dump.Dumper ExpectContinueTimeout, if non-zero, specifies the amount of
time to wait for a server's first response headers after fully
writing the request headers if the request has an
"Expect: 100-continue" header. Zero means no timeout and
causes the body to be sent immediately, without
waiting for the server to approve.
This time does not include the time to send the request header. GetProxyConnectHeader optionally specifies a func to return
headers to send to proxyURL during a CONNECT request to the
ip:port target.
If it returns an error, the Transport's RoundTrip fails with
that error. It can return (nil, nil) to not add headers.
If GetProxyConnectHeader is non-nil, ProxyConnectHeader is
ignored. IdleConnTimeout is the maximum amount of time an idle
(keep-alive) connection will remain idle before closing
itself.
Zero means no limit. MaxConnsPerHost optionally limits the total number of
connections per host, including connections in the dialing,
active, and idle states. On limit violation, dials will block.
Zero means no limit. MaxIdleConns controls the maximum number of idle (keep-alive)
connections across all hosts. Zero means no limit. MaxIdleConnsPerHost, if non-zero, controls the maximum idle
(keep-alive) connections to keep per-host. If zero,
defaultMaxIdleConnsPerHost is used. MaxResponseHeaderBytes specifies a limit on how many
response bytes are allowed in the server's response
header.
Zero means to use a default limit. OnProxyConnectResponse is called when the Transport gets an HTTP response from
a proxy for a CONNECT request. It's called before the check for a 200 OK response.
If it returns an error, the request fails with that error. Proxy specifies a function to return a proxy for a given
Request. If the function returns a non-nil error, the
request is aborted with the provided error.
The proxy type is determined by the URL scheme. "http",
"https", "socks5", "socks5h", "socks4", and "socks4a" are supported.
If the scheme is empty, "http" is assumed.
"socks5" is treated the same as "socks5h".
"socks4" resolves domain names locally to IPv4; "socks4a" lets the
proxy resolve domain names. SOCKS4 only supports IPv4 destinations.
If the proxy URL contains a userinfo subcomponent,
the proxy request will pass the username and password
in a Proxy-Authorization header for HTTP proxies, or the username
as the SOCKS4 user ID / SOCKS5 credentials for SOCKS proxies.
If Proxy is nil or returns a nil *URL, no proxy is used. ProxyConnectHeader optionally specifies headers to send to
proxies during CONNECT requests.
To set the header dynamically, see GetProxyConnectHeader. ReadBufferSize specifies the size of the read buffer used
when reading from the transport.
If zero, a default (currently 4KB) is used. ResponseHeaderTimeout, if non-zero, specifies the amount of
time to wait for a server's response headers after fully
writing the request (including its body, if any). This
time does not include the time to read the response body. TLSClientConfig specifies the TLS configuration to use with
tls.Client.
If nil, the default configuration is used.
If non-nil, HTTP/2 support may not be enabled by default. TLSHandshakeContext specifies an optional dial function for tls handshake,
it works even if a proxy is set, can be used to customize the tls fingerprint. TLSHandshakeTimeout specifies the maximum amount of time to
wait for a TLS handshake. Zero means no timeout. WriteBufferSize specifies the size of the write buffer used
when writing to the transport.
If zero, a default (currently 4KB) is used. AddCommonQueryParam add a URL query parameter with a key-value
pair for requests fired from the client. AddCommonQueryParams add one or more values of specified URL query parameter
for requests fired from the client. AddCommonRetryCondition adds a retry condition, which determines whether the
request should retry. AddCommonRetryHook adds a retry hook for requests fired from the client,
which will be executed before a retry. CancelRequest cancels an in-flight request by closing its connection.
CancelRequest should only be called after [Transport.RoundTrip] has returned.
Deprecated: Use [Request.WithContext] to create a request with a
cancelable context instead. CancelRequest cannot cancel HTTP/2
requests. This may become a no-op in a future release of Go. ClearCookies clears all cookies if cookie is enabled, including
cookies from cookie jar and cookies set by SetCommonCookies.
Note: The cookie jar will not be cleared if you called SetCookieJar
instead of SetCookieJarFactory. Clone copy and returns the Client CloseIdleConnections closes any connections which were previously
connected from previous requests but are now sitting idle in
a "keep-alive" state. It does not interrupt any connections currently
in use. Delete create a new DELETE request. DevMode enables:
1. Dump content of all requests and responses to see details.
2. Output debug level log for deeper insights.
3. Trace all requests, so you can get trace info to analyze performance. DisableAllowGetMethodPayload disable sending GET method requests with body. DisableAutoDecode disable auto-detect charset and decode to utf-8 (enabled by default). DisableAutoDecompress disables the automatic decompression (disabled by default). DisableAutoReadResponse disable read response body automatically (enabled by default). DisableCompression disables the compression (enabled by default),
which prevents the Transport from requesting compression
with an "Accept-Encoding: gzip" request header when the
Request contains no existing Accept-Encoding value. If
the Transport requests gzip on its own and gets a gzipped
response, it's transparently decoded in the Response.Body.
However, if the user explicitly requested gzip it is not
automatically uncompressed. DisableDebugLog disable debug level log (disabled by default). DisableDump disables the dump. DisableDumpAll disable dump for requests fired from the client. DisableForceHttpVersion disable force using specified http
version (disabled by default). DisableH2C disables HTTP/2 over TCP without TLS. DisableHTTP3 disables the http3 protocol. DisableInsecureSkipVerify disable send https without verifying
the server's certificates (disabled by default). DisableKeepAlives disable the HTTP keep-alives (enabled by default)
and will only use the connection to the server for a single
HTTP request.
This is unrelated to the similarly named TCP keep-alives. DisableTraceAll disable trace for requests fired from the client. Do is compatible with http.Client.Do, which can make req integration easier
in some scenarios. It should be noted that this will make some req features
not work properly, such as automatic retry, client middleware, etc. EnableAllowGetMethodPayload allows sending GET method requests with body. EnableAutoDecode enable auto-detect charset and decode to utf-8 (enabled by default). EnableAutoDecompress enables the automatic decompression (disabled by default). EnableAutoReadResponse enable read response body automatically (enabled by default). EnableCompression enables the compression (enabled by default). EnableDebugLog enable debug level log (disabled by default). EnableDump enables the dump for all requests with specified dump options. EnableDumpAll enable dump for requests fired from the client, including
all content for the request and response by default. EnableDumpAllAsync enable dump for requests fired from the
client and output asynchronously, can be used for debugging
in production environment without affecting performance. EnableDumpAllTo enable dump for requests fired from the
client and output to the specified io.Writer. EnableDumpAllToFile enable dump for requests fired from the
client and output to the specified file. EnableDumpAllWithoutBody enable dump for requests fired from
the client without body, can be used if you only care about
the header. EnableDumpAllWithoutHeader enable dump for requests fired from
the client without header, can be used if you only care about
the body. EnableDumpAllWithoutRequest enables dump for requests fired from
the client without request, can be used if you only care about
the response. EnableDumpAllWithoutRequestBody enable dump for requests fired
from the client without request body, can be used in the upload
request to avoid dumping the unreadable binary content. EnableDumpAllWithoutResponse enable dump for requests fired from
the client without response, can be used if you only care about
the request. EnableDumpAllWithoutResponseBody enable dump for requests fired
from the client without response body, can be used in the download
request to avoid dumping the unreadable binary content. EnableDumpEachRequest enable dump at the request-level for each request, and only
temporarily stores the dump content in memory, call Response.Dump() to get the
dump content when needed. EnableDumpEachRequestWithoutBody enable dump without body at the request-level for
each request, and only temporarily stores the dump content in memory, call
Response.Dump() to get the dump content when needed. EnableDumpEachRequestWithoutHeader enable dump without header at the request-level for
each request, and only temporarily stores the dump content in memory, call
Response.Dump() to get the dump content when needed. EnableDumpEachRequestWithoutRequest enable dump without request at the request-level for
each request, and only temporarily stores the dump content in memory, call
Response.Dump() to get the dump content when needed. EnableDumpEachRequestWithoutRequestBody enable dump without request body at the
request-level for each request, and only temporarily stores the dump content in memory,
call Response.Dump() to get the dump content when needed. EnableDumpEachRequestWithoutResponse enable dump without response at the request-level for
each request, and only temporarily stores the dump content in memory, call
Response.Dump() to get the dump content when needed. EnableDumpEachRequestWithoutResponseBody enable dump without response body at the
request-level for each request, and only temporarily stores the dump content in memory,
call Response.Dump() to get the dump content when needed. EnableForceHTTP1 enable force using HTTP1 (disabled by default).
Attention: This method should not be called when ImpersonateXXX, SetTLSFingerPrint or
SetTLSHandshake and other methods that will customize the tls handshake are called. EnableForceHTTP2 enable force using HTTP2 for https requests (disabled by default).
Attention: This method should not be called when ImpersonateXXX, SetTLSFingerPrint or
SetTLSHandshake and other methods that will customize the tls handshake are called. EnableForceHTTP3 enable force using HTTP3 for https requests (disabled by default).
Attention: This method should not be called when ImpersonateXXX, SetTLSFingerPrint or
SetTLSHandshake and other methods that will customize the tls handshake are called. EnableH2C enables HTTP/2 over TCP without TLS. EnableHTTP3 enables the http3 protocol. EnableInsecureSkipVerify enable send https without verifying
the server's certificates (disabled by default). EnableKeepAlives enables HTTP keep-alives (enabled by default). EnableTraceAll enable trace for requests fired from the client (http3
currently does not support trace). Get create a new GET request, accepts 0 or 1 url. GetClient returns the underlying `http.Client`. GetCookies get cookies from the underlying `http.Client`'s `CookieJar`. GetLogger return the internal logger, usually used in middleware. GetMaxIdleConns returns MaxIdleConns. GetTLSClientConfig return the underlying tls.Config. GetTransport return the underlying transport. Head create a new HEAD request. ImpersonateChrome impersonates Chrome browser (version 120). ImpersonateFirefox impersonates Firefox browser (version 120). ImpersonateSafari impersonates Safari browser (version 16.6).(*Client) NewParallelDownload(url string) *ParallelDownload NewRequest is the alias of R() OnAfterResponse add a response middleware which hooks after response received. OnBeforeRequest add a request middleware which hooks before request sent. OnError set the error hook which will be executed if any error returned,
even if the occurs before request is sent (e.g. invalid URL). Options create a new OPTIONS request. Patch create a new PATCH request. Post create a new POST request. Put create a new PUT request. R create a new request. RoundTrip implements the RoundTripper interface.
For higher-level HTTP client support (such as handling of cookies
and redirects), see Get, Post, and the Client type.
Like the RoundTripper interface, the error types returned
by RoundTrip are unspecified. SetAutoDecodeAllContentType enable try auto-detect charset and decode all content type to utf-8. SetAutoDecodeContentType set the content types that will be auto-detected and decode to utf-8
(e.g. "json", "xml", "html", "text"). SetAutoDecodeContentTypeFunc set the function that determines whether the specified `Content-Type` should be auto-detected and decode to utf-8. SetBaseURL set the default base URL, will be used if request URL is
a relative URL. SetCertFromFile helps to set client certificates from cert and key file. SetCerts set client certificates. SetCommonBasicAuth set the basic auth for requests fired from
the client. SetCommonBearerAuthToken set the bearer auth token for requests fired from the client. SetCommonContentType set the `Content-Type` header for requests fired
from the client. SetCommonCookies set HTTP cookies for requests fired from the client. SetCommonDigestAuth sets the Digest Access auth scheme for requests fired from 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 "roc" and password "123456"
client.SetCommonDigestAuth("roc", "123456")
Information about Digest Access Authentication can be found in RFC7616:
https://datatracker.ietf.org/doc/html/rfc7616 SetCommonDumpOptions configures the underlying Transport's DumpOptions
for requests fired from the client. SetCommonError set the common result that response body will be unmarshalled to
if no error occurs but Response.ResultState returns ErrorState, by default it
is HTTP status `code >= 400`, you can also use SetCommonResultStateChecker
to customize the result state check logic.
Deprecated: Use SetCommonErrorResult instead. SetCommonErrorResult set the common result that response body will be unmarshalled to
if no error occurs but Response.ResultState returns ErrorState, by default it
is HTTP status `code >= 400`, you can also use SetCommonResultStateChecker
to customize the result state check logic. SetCommonFormData set the form data from map for requests fired from the client
which request method allows payload. SetCommonFormDataFromValues set the form data from url.Values for requests
fired from the client which request method allows payload. SetCommonHeader set a header for requests fired from the client. SetCommonHeaderNonCanonical set a header for requests fired from
the client which key is a non-canonical key (keep case unchanged),
only valid for HTTP/1.1. SetCommonHeaderOrder set the order of the http header requests fired from the
client (case-insensitive).
For example:
client.R().SetCommonHeaderOrder(
"custom-header",
"cookie",
"user-agent",
"accept-encoding",
).Get(url SetCommonHeaders set headers for requests fired from the client. SetCommonHeadersNonCanonical set headers for requests fired from the
client which key is a non-canonical key (keep case unchanged), only
valid for HTTP/1.1. SetCommonPathParam set a path parameter for requests fired from the client. SetCommonPathParams set path parameters for requests fired from the client. SetCommonPseudoHeaderOder set the order of the pseudo http header requests fired
from the client (case-insensitive).
Note this is only valid for http2 and http3.
For example:
client.SetCommonPseudoHeaderOder(
":scheme",
":authority",
":path",
":method",
) SetCommonQueryParam set a URL query parameter with a key-value
pair for requests fired from the client. SetCommonQueryParams set URL query parameters with a map
for requests fired from the client. SetCommonQueryParamsFromStruct set URL query parameters from a struct using go-querystring
for requests fired from the client. SetCommonQueryParamsFromValues set URL query parameters from a url.Values map
for requests fired from the client. SetCommonQueryString set URL query parameters with a raw query string
for requests fired from the client. SetCommonRetryBackoffInterval set retry to use a capped exponential backoff
with jitter for requests fired from the client.
https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ SetCommonRetryCondition sets the retry condition, which determines whether the
request should retry.
It will override other retry conditions if any been added before. SetCommonRetryCount enables retry and set the maximum retry count for requests
fired from the client.
It will retry infinitely if count is negative. SetCommonRetryFixedInterval set retry to use a fixed interval for requests
fired from the client. SetCommonRetryHook set the retry hook which will be executed before a retry.
It will override other retry hooks if any been added before. SetCommonRetryInterval sets the custom GetRetryIntervalFunc for requests fired
from the client, you can use this to implement your own backoff retry algorithm.
For example:
req.SetCommonRetryInterval(func(resp *req.Response, attempt int) time.Duration {
sleep := 0.01 * math.Exp2(float64(attempt))
return time.Duration(math.Min(2, sleep)) * time.Second
}) SetCookieJar set the cookie jar to the underlying `http.Client`, set to nil if you
want to disable cookies.
Note: If you use Client.Clone to clone a new Client, the new client will share the same
cookie jar as the old Client after cloning. Use SetCookieJarFactory instead if you want
to create a new CookieJar automatically when cloning a client. SetCookieJarFactory set the functional factory of cookie jar, which creates
cookie jar that store cookies for underlying `http.Client`. After client clone,
the cookie jar of the new client will also be regenerated using this factory
function. SetDebug set the optional debug function. SetDial set the customized `DialContext` function to Transport. SetDialTLS set the customized `DialTLSContext` function to Transport.
Make sure the returned `conn` implements pkg/tls.Conn if you want your
customized `conn` supports HTTP2. SetExpectContinueTimeout set the ExpectContinueTimeout, if non-zero, specifies
the amount of time to wait for a server's first response headers after fully
writing the request headers if the request has an "Expect: 100-continue" header.
Zero means no timeout and causes the body to be sent immediately, without waiting
for the server to approve.
This time does not include the time to send the request header. SetGetProxyConnectHeader set the GetProxyConnectHeader, which optionally specifies a func
to return headers to send to proxyURL during a CONNECT request to the ip:port target.
If it returns an error, the Transport's RoundTrip fails with that error. It can
return (nil, nil) to not add headers.
If GetProxyConnectHeader is non-nil, ProxyConnectHeader is ignored. SetHTTP2ConnectionFlow set the default http2 connection flow, which is the increment
value of initial WINDOW_UPDATE frame. SetHTTP2HeaderPriority set the header priority param. SetHTTP2MaxHeaderListSize set the http2 MaxHeaderListSize,
which is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
send in the initial settings frame. It is how many bytes
of response headers are allowed. Unlike the http2 spec, zero here
means to use a default limit (currently 10MB). If you actually
want to advertise an unlimited value to the peer, Transport
interprets the highest possible value here (0xffffffff or 1<<32-1)
to mean no limit. SetHTTP2PingTimeout set the http2 PingTimeout, which is the timeout
after which the connection will be closed if a response to Ping is
not received.
Defaults to 15s SetHTTP2PriorityFrames set the ordered http2 priority frames. SetHTTP2ReadIdleTimeout set the http2 ReadIdleTimeout,
which is the timeout after which a health check using ping
frame will be carried out if no frame is received on the connection.
Note that a ping response will is considered a received frame, so if
there is no other traffic on the connection, the health check will
be performed every ReadIdleTimeout interval.
If zero, no health check is performed. SetHTTP2SettingsFrame set the ordered http2 settings frame. SetHTTP2StrictMaxConcurrentStreams set the http2
StrictMaxConcurrentStreams, which controls whether the
server's SETTINGS_MAX_CONCURRENT_STREAMS should be respected
globally. If false, new TCP connections are created to the
server as needed to keep each under the per-connection
SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
a global limit and callers of RoundTrip block when needed,
waiting for their turn. SetHTTP2WriteByteTimeout set the http2 WriteByteTimeout, which is the
timeout after which the connection will be closed no data can be written
to it. The timeout begins when data is available to write, and is
extended whenever any bytes are written. SetHosts configures a static hostname-to-IP mapping used when dialing HTTP/1
and HTTP/2 connections (like a hosts file). Hostnames not present in the map
fail immediately with a "no such host" DNS error and do not consult the
system resolver. This avoids long DNS timeouts when maintaining a custom
host list (e.g. crawlers).
Notes:
- Keys are hostnames only (no port). Matching is case-insensitive and
IDNA-normalized to match the dial address form used by the transport.
- Values must be literal IP addresses (IPv4 or IPv6). Optional surrounding
brackets on IPv6 (e.g. "[::1]") are accepted and normalized. Non-IP
values never fall through to system DNS; dialing that host returns a
clear error instead.
- IP-literal request addresses (e.g. https://1.2.3.4/) skip the map and
dial directly. Scoped IPv6 literals (e.g. https://[fe80::1%25eth0]/)
are supported.
- An empty or nil map makes every non-literal hostname fail closed.
- Proxy routing is rejected while SetHosts is active because a proxy can
resolve the destination remotely and bypass the static mapping.
- Only valid for HTTP/1 and HTTP/2 (same limitation as SetDial). SetDialTLS
still bypasses this dialer for HTTPS when set. Calling SetDial,
SetResolver, or SetUnixSocket replaces this dialer.
- The map is copied; later changes to the caller's map are ignored.
For example:
client.SetHosts(map[string]string{
"api.internal": "10.0.0.5",
"db.internal": "10.0.0.6",
"v6.internal": "::1",
}) SetIdleConnTimeout set the IdleConnTimeout, which is the maximum
amount of time an idle (keep-alive) connection will remain idle before
closing itself.
Zero means no limit. SetJsonMarshal set the JSON marshal function which will be used
to marshal request body. SetJsonUnmarshal set the JSON unmarshal function which will be used
to unmarshal response body. SetLogger set the customized logger for client, will disable log if set to nil. SetMaxConnsPerHost set the MaxConnsPerHost, optionally limits the
total number of connections per host, including connections in the
dialing, active, and idle states. On limit violation, dials will block.
Zero means no limit. SetMaxIdleConns set the MaxIdleConns, which controls the maximum number of idle (keep-alive)
connections across all hosts. Zero means no limit. SetMaxResponseHeaderBytes set the MaxResponseHeaderBytes, which specifies a limit on how many
response bytes are allowed in the server's response header.
Zero means to use a default limit. SetMaxResponseSize sets the maximum allowed size of a response body in bytes.
Enforcement:
- When Response.ContentLength is known and greater than the limit, the body
is closed without reading and a ResponseBodyTooLargeError is returned.
Closing early may prevent connection reuse for that request.
- Otherwise the body is wrapped so application reads stop at the limit.
- HEAD requests never fail the Content-Length early check (there is no body).
The limit is applied to bytes delivered to the application after the transport
has handled Content-Encoding (e.g. gzip decompression). For auto-decompressed
responses ContentLength is typically -1, so only the streaming limit applies.
Charset auto-decode, if enabled, also runs underneath the limit.
A value of 0 or less disables the limit (default). This is useful for bounding
memory use and network bandwidth when talking to untrusted or unexpectedly
large endpoints. SetMultipartBoundaryFunc overrides the default function used to generate
boundary delimiters for "multipart/form-data" requests with a customized one,
which returns a boundary delimiter (without the two leading hyphens).
Boundary delimiter may only contain certain ASCII characters, and must be
non-empty and at most 70 bytes long (see RFC 2046, Section 5.1.1). SetOutputDirectory set output directory that response will
be downloaded to. SetProxy set the proxy function. SetProxyConnectHeader set the ProxyConnectHeader, which optionally specifies headers to
send to proxies during CONNECT requests.
To set the header dynamically, see SetGetProxyConnectHeader. SetProxyURL set proxy from the proxy URL. SetReadBufferSize set the ReadBufferSize, which specifies the size of the read buffer used
when reading from the transport.
If zero, a default (currently 4KB) is used. SetRedirectPolicy set the RedirectPolicy which controls the behavior of receiving redirect
responses (usually responses with 301 and 302 status code), see the predefined
AllowedDomainRedirectPolicy, AllowedHostRedirectPolicy, DefaultRedirectPolicy, MaxRedirectPolicy,
NoRedirectPolicy, SameDomainRedirectPolicy and SameHostRedirectPolicy. SetResolver sets a custom DNS resolver used when dialing HTTP/1 and HTTP/2
connections. It is implemented via SetDial and a net.Dialer that uses r.
If r is nil, the default resolver is used.
Only valid for HTTP/1 and HTTP/2 (same limitation as SetDial). Calling
SetDial, SetHosts, or SetUnixSocket replaces this dialer.
For example, use a specific DNS server:
r := &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
var d net.Dialer
return d.DialContext(ctx, "udp", "1.1.1.1:53")
},
}
client.SetResolver(r) SetResponseBodyTransformer set the response body transformer, which can modify the
response body before unmarshalled if auto-read response body is not disabled. SetResponseHeaderTimeout set the ResponseHeaderTimeout, if non-zero, specifies
the amount of time to wait for a server's response headers after fully writing
the request (including its body, if any). This time does not include the time
to read the response body. SetResultStateCheckFunc overrides the default result state checker with customized one,
which returns SuccessState when HTTP status `code >= 200 and <= 299`, and returns
ErrorState when HTTP status `code >= 400`, otherwise returns UnknownState. SetRootCertFromString set root certificates from string. SetRootCertsFromFile set root certificates from files. SetScheme set the default scheme for client, will be used when
there is no scheme in the request URL (e.g. "github.com/imroc/req"). SetTLSClientConfig set the TLS client config. Be careful! Usually
you don't need this, you can directly set the tls configuration with
methods like EnableInsecureSkipVerify, SetCerts etc. Or you can call
GetTLSClientConfig to get the current tls configuration to avoid
overwriting some important configurations, such as not setting NextProtos
will not use http2 by default. SetTLSFingerprint set the tls fingerprint for tls handshake, will use utls
(https://github.com/refraction-networking/utls) to perform the tls handshake,
which uses the specified clientHelloID to simulate the tls fingerprint.
Note this is valid for HTTP1 and HTTP2, not HTTP3. SetTLSFingerprint360 uses tls fingerprint of 360 browser. SetTLSFingerprintAndroid uses tls fingerprint of Android. SetTLSFingerprintChrome uses tls fingerprint of Chrome browser. SetTLSFingerprintEdge uses tls fingerprint of Edge browser. SetTLSFingerprintFirefox uses tls fingerprint of Firefox browser. SetTLSFingerprintIOS uses tls fingerprint of IOS. SetTLSFingerprintQQ uses tls fingerprint of QQ browser. SetTLSFingerprintRandomized uses randomized tls fingerprint. SetTLSFingerprintSafari uses tls fingerprint of Safari browser. SetTLSFingerprintSpec set the tls fingerprint for tls handshake using a custom
ClientHelloSpec, which allows fine-grained control over the TLS fingerprint
(e.g. for JA3/JA4 customization). Uses utls
(https://github.com/refraction-networking/utls) to perform the tls handshake.
Note this is valid for HTTP1 and HTTP2, not HTTP3. SetTLSHandshake set the custom tls handshake function, only valid for HTTP1 and HTTP2, not HTTP3,
it specifies an optional dial function for tls handshake, it works even if a proxy is set, can be
used to customize the tls fingerprint. SetTLSHandshakeTimeout set the TLS handshake timeout. SetTimeout set timeout for requests fired from the client. SetUnixSocket set client to dial connection use unix socket.
For example:
client.SetUnixSocket("/var/run/custom.sock") SetUserAgent set the "User-Agent" header for requests fired from the client. SetWriteBufferSize set the WriteBufferSize, which specifies the size of the write buffer used
when writing to the transport.
If zero, a default (currently 4KB) is used. SetXmlMarshal set the XML marshal function which will be used
to marshal request body. SetXmlUnmarshal set the XML unmarshal function which will be used
to unmarshal response body. WrapRoundTrip adds a client middleware function that will give the caller
an opportunity to wrap the underlying http.RoundTripper. WrapRoundTripFunc adds a client middleware function that will give the caller
an opportunity to wrap the underlying http.RoundTripper.
*Client : github.com/prometheus/client_golang/prometheus/push.HTTPDoer
Client : net/http.RoundTripper
func AddCommonQueryParam(key, value string) *Client
func AddCommonQueryParams(key string, values ...string) *Client
func AddCommonRetryCondition(condition RetryConditionFunc) *Client
func AddCommonRetryHook(hook RetryHookFunc) *Client
func C() *Client
func ClearCookies() *Client
func DefaultClient() *Client
func DevMode() *Client
func DisableAllowGetMethodPayload() *Client
func DisableAutoDecode() *Client
func DisableAutoReadResponse() *Client
func DisableCompression() *Client
func DisableDebugLog() *Client
func DisableDumpAll() *Client
func DisableForceHttpVersion() *Client
func DisableH2C() *Client
func DisableInsecureSkipVerify() *Client
func DisableKeepAlives() *Client
func DisableTraceAll() *Client
func EnableAllowGetMethodPayload() *Client
func EnableAutoDecode() *Client
func EnableAutoReadResponse() *Client
func EnableCompression() *Client
func EnableDebugLog() *Client
func EnableDumpAll() *Client
func EnableDumpAllAsync() *Client
func EnableDumpAllTo(output io.Writer) *Client
func EnableDumpAllToFile(filename string) *Client
func EnableDumpAllWithoutBody() *Client
func EnableDumpAllWithoutHeader() *Client
func EnableDumpAllWithoutRequest() *Client
func EnableDumpAllWithoutRequestBody() *Client
func EnableDumpAllWithoutResponse() *Client
func EnableDumpAllWithoutResponseBody() *Client
func EnableDumpEachRequest() *Client
func EnableDumpEachRequestWithoutBody() *Client
func EnableDumpEachRequestWithoutHeader() *Client
func EnableDumpEachRequestWithoutRequest() *Client
func EnableDumpEachRequestWithoutRequestBody() *Client
func EnableDumpEachRequestWithoutResponse() *Client
func EnableDumpEachRequestWithoutResponseBody() *Client
func EnableForceHTTP1() *Client
func EnableForceHTTP2() *Client
func EnableForceHTTP3() *Client
func EnableH2C() *Client
func EnableHTTP3() *Client
func EnableInsecureSkipVerify() *Client
func EnableKeepAlives() *Client
func EnableTraceAll() *Client
func ImpersonateChrome() *Client
func ImpersonateFirefox() *Client
func ImpersonateSafari() *Client
func NewClient() *Client
func OnAfterResponse(m ResponseMiddleware) *Client
func OnBeforeRequest(m RequestMiddleware) *Client
func SetAutoDecodeAllContentType() *Client
func SetAutoDecodeContentType(contentTypes ...string) *Client
func SetAutoDecodeContentTypeFunc(fn func(contentType string) bool) *Client
func SetBaseURL(u string) *Client
func SetCertFromFile(certFile, keyFile string) *Client
func SetCerts(certs ...tls.Certificate) *Client
func SetCommonBasicAuth(username, password string) *Client
func SetCommonBearerAuthToken(token string) *Client
func SetCommonContentType(ct string) *Client
func SetCommonCookies(cookies ...*http.Cookie) *Client
func SetCommonDigestAuth(username, password string) *Client
func SetCommonDumpOptions(opt *DumpOptions) *Client
func SetCommonError(err any) *Client
func SetCommonErrorResult(err any) *Client
func SetCommonFormData(data map[string]string) *Client
func SetCommonFormDataFromValues(data url.Values) *Client
func SetCommonHeader(key, value string) *Client
func SetCommonHeaderOrder(keys ...string) *Client
func SetCommonHeaders(hdrs map[string]string) *Client
func SetCommonPathParam(key, value string) *Client
func SetCommonPathParams(pathParams map[string]string) *Client
func SetCommonPseudoHeaderOder(keys ...string) *Client
func SetCommonQueryParam(key, value string) *Client
func SetCommonQueryParams(params map[string]string) *Client
func SetCommonQueryParamsFromStruct(v any) *Client
func SetCommonQueryParamsFromValues(params url.Values) *Client
func SetCommonQueryString(query string) *Client
func SetCommonRetryBackoffInterval(min, max time.Duration) *Client
func SetCommonRetryCondition(condition RetryConditionFunc) *Client
func SetCommonRetryCount(count int) *Client
func SetCommonRetryFixedInterval(interval time.Duration) *Client
func SetCommonRetryHook(hook RetryHookFunc) *Client
func SetCommonRetryInterval(getRetryIntervalFunc GetRetryIntervalFunc) *Client
func SetCookieJar(jar http.CookieJar) *Client
func SetDial(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Client
func SetDialTLS(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Client
func SetHosts(hosts map[string]string) *Client
func SetHTTP2ConnectionFlow(flow uint32) *Client
func SetHTTP2HeaderPriority(priority http2.PriorityParam) *Client
func SetHTTP2MaxHeaderListSize(max uint32) *Client
func SetHTTP2PingTimeout(timeout time.Duration) *Client
func SetHTTP2PriorityFrames(frames ...http2.PriorityFrame) *Client
func SetHTTP2ReadIdleTimeout(timeout time.Duration) *Client
func SetHTTP2SettingsFrame(settings ...http2.Setting) *Client
func SetHTTP2StrictMaxConcurrentStreams(strict bool) *Client
func SetHTTP2WriteByteTimeout(timeout time.Duration) *Client
func SetJsonMarshal(fn func(v any) ([]byte, error)) *Client
func SetJsonUnmarshal(fn func(data []byte, v any) error) *Client
func SetLogger(log Logger) *Client
func SetMaxResponseSize(max int64) *Client
func SetMultipartBoundaryFunc(fn func() string) *Client
func SetOutputDirectory(dir string) *Client
func SetProxy(proxy func(*http.Request) (*url.URL, error)) *Client
func SetProxyURL(proxyUrl string) *Client
func SetRedirectPolicy(policies ...RedirectPolicy) *Client
func SetResolver(r *net.Resolver) *Client
func SetResponseBodyTransformer(fn func(rawBody []byte, req *Request, resp *Response) (transformedBody []byte, err error)) *Client
func SetResultStateCheckFunc(fn func(resp *Response) ResultState) *Client
func SetRootCertFromString(pemContent string) *Client
func SetRootCertsFromFile(pemFiles ...string) *Client
func SetScheme(scheme string) *Client
func SetTimeout(d time.Duration) *Client
func SetTLSClientConfig(conf *tls.Config) *Client
func SetTLSFingerprint(clientHelloID utls.ClientHelloID) *Client
func SetTLSFingerprint360() *Client
func SetTLSFingerprintAndroid() *Client
func SetTLSFingerprintChrome() *Client
func SetTLSFingerprintEdge() *Client
func SetTLSFingerprintFirefox() *Client
func SetTLSFingerprintIOS() *Client
func SetTLSFingerprintQQ() *Client
func SetTLSFingerprintRandomized() *Client
func SetTLSFingerprintSafari() *Client
func SetTLSHandshakeTimeout(timeout time.Duration) *Client
func SetUnixSocket(file string) *Client
func SetUserAgent(userAgent string) *Client
func SetXmlMarshal(fn func(v any) ([]byte, error)) *Client
func SetXmlUnmarshal(fn func(data []byte, v any) error) *Client
func WrapRoundTrip(wrappers ...RoundTripWrapper) *Client
func WrapRoundTripFunc(funcs ...RoundTripWrapperFunc) *Client
func (*Client).AddCommonQueryParam(key, value string) *Client
func (*Client).AddCommonQueryParams(key string, values ...string) *Client
func (*Client).AddCommonRetryCondition(condition RetryConditionFunc) *Client
func (*Client).AddCommonRetryHook(hook RetryHookFunc) *Client
func (*Client).ClearCookies() *Client
func (*Client).Clone() *Client
func (*Client).DevMode() *Client
func (*Client).DisableAllowGetMethodPayload() *Client
func (*Client).DisableAutoDecode() *Client
func (*Client).DisableAutoDecompress() *Client
func (*Client).DisableAutoReadResponse() *Client
func (*Client).DisableCompression() *Client
func (*Client).DisableDebugLog() *Client
func (*Client).DisableDumpAll() *Client
func (*Client).DisableForceHttpVersion() *Client
func (*Client).DisableH2C() *Client
func (*Client).DisableHTTP3() *Client
func (*Client).DisableInsecureSkipVerify() *Client
func (*Client).DisableKeepAlives() *Client
func (*Client).DisableTraceAll() *Client
func (*Client).EnableAllowGetMethodPayload() *Client
func (*Client).EnableAutoDecode() *Client
func (*Client).EnableAutoDecompress() *Client
func (*Client).EnableAutoReadResponse() *Client
func (*Client).EnableCompression() *Client
func (*Client).EnableDebugLog() *Client
func (*Client).EnableDumpAll() *Client
func (*Client).EnableDumpAllAsync() *Client
func (*Client).EnableDumpAllTo(output io.Writer) *Client
func (*Client).EnableDumpAllToFile(filename string) *Client
func (*Client).EnableDumpAllWithoutBody() *Client
func (*Client).EnableDumpAllWithoutHeader() *Client
func (*Client).EnableDumpAllWithoutRequest() *Client
func (*Client).EnableDumpAllWithoutRequestBody() *Client
func (*Client).EnableDumpAllWithoutResponse() *Client
func (*Client).EnableDumpAllWithoutResponseBody() *Client
func (*Client).EnableDumpEachRequest() *Client
func (*Client).EnableDumpEachRequestWithoutBody() *Client
func (*Client).EnableDumpEachRequestWithoutHeader() *Client
func (*Client).EnableDumpEachRequestWithoutRequest() *Client
func (*Client).EnableDumpEachRequestWithoutRequestBody() *Client
func (*Client).EnableDumpEachRequestWithoutResponse() *Client
func (*Client).EnableDumpEachRequestWithoutResponseBody() *Client
func (*Client).EnableForceHTTP1() *Client
func (*Client).EnableForceHTTP2() *Client
func (*Client).EnableForceHTTP3() *Client
func (*Client).EnableH2C() *Client
func (*Client).EnableHTTP3() *Client
func (*Client).EnableInsecureSkipVerify() *Client
func (*Client).EnableKeepAlives() *Client
func (*Client).EnableTraceAll() *Client
func (*Client).ImpersonateChrome() *Client
func (*Client).ImpersonateFirefox() *Client
func (*Client).ImpersonateSafari() *Client
func (*Client).OnAfterResponse(m ResponseMiddleware) *Client
func (*Client).OnBeforeRequest(m RequestMiddleware) *Client
func (*Client).OnError(hook ErrorHook) *Client
func (*Client).SetAutoDecodeAllContentType() *Client
func (*Client).SetAutoDecodeContentType(contentTypes ...string) *Client
func (*Client).SetAutoDecodeContentTypeFunc(fn func(contentType string) bool) *Client
func (*Client).SetBaseURL(u string) *Client
func (*Client).SetCertFromFile(certFile, keyFile string) *Client
func (*Client).SetCerts(certs ...tls.Certificate) *Client
func (*Client).SetCommonBasicAuth(username, password string) *Client
func (*Client).SetCommonBearerAuthToken(token string) *Client
func (*Client).SetCommonContentType(ct string) *Client
func (*Client).SetCommonCookies(cookies ...*http.Cookie) *Client
func (*Client).SetCommonDigestAuth(username, password string) *Client
func (*Client).SetCommonDumpOptions(opt *DumpOptions) *Client
func (*Client).SetCommonError(err any) *Client
func (*Client).SetCommonErrorResult(err any) *Client
func (*Client).SetCommonFormData(data map[string]string) *Client
func (*Client).SetCommonFormDataFromValues(data urlpkg.Values) *Client
func (*Client).SetCommonHeader(key, value string) *Client
func (*Client).SetCommonHeaderNonCanonical(key, value string) *Client
func (*Client).SetCommonHeaderOrder(keys ...string) *Client
func (*Client).SetCommonHeaders(hdrs map[string]string) *Client
func (*Client).SetCommonHeadersNonCanonical(hdrs map[string]string) *Client
func (*Client).SetCommonPathParam(key, value string) *Client
func (*Client).SetCommonPathParams(pathParams map[string]string) *Client
func (*Client).SetCommonPseudoHeaderOder(keys ...string) *Client
func (*Client).SetCommonQueryParam(key, value string) *Client
func (*Client).SetCommonQueryParams(params map[string]string) *Client
func (*Client).SetCommonQueryParamsFromStruct(v any) *Client
func (*Client).SetCommonQueryParamsFromValues(params urlpkg.Values) *Client
func (*Client).SetCommonQueryString(query string) *Client
func (*Client).SetCommonRetryBackoffInterval(min, max time.Duration) *Client
func (*Client).SetCommonRetryCondition(condition RetryConditionFunc) *Client
func (*Client).SetCommonRetryCount(count int) *Client
func (*Client).SetCommonRetryFixedInterval(interval time.Duration) *Client
func (*Client).SetCommonRetryHook(hook RetryHookFunc) *Client
func (*Client).SetCommonRetryInterval(getRetryIntervalFunc GetRetryIntervalFunc) *Client
func (*Client).SetCookieJar(jar http.CookieJar) *Client
func (*Client).SetCookieJarFactory(factory func() http.CookieJar) *Client
func (*Client).SetDial(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Client
func (*Client).SetDialTLS(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Client
func (*Client).SetHosts(hosts map[string]string) *Client
func (*Client).SetHTTP2ConnectionFlow(flow uint32) *Client
func (*Client).SetHTTP2HeaderPriority(priority http2.PriorityParam) *Client
func (*Client).SetHTTP2MaxHeaderListSize(max uint32) *Client
func (*Client).SetHTTP2PingTimeout(timeout time.Duration) *Client
func (*Client).SetHTTP2PriorityFrames(frames ...http2.PriorityFrame) *Client
func (*Client).SetHTTP2ReadIdleTimeout(timeout time.Duration) *Client
func (*Client).SetHTTP2SettingsFrame(settings ...http2.Setting) *Client
func (*Client).SetHTTP2StrictMaxConcurrentStreams(strict bool) *Client
func (*Client).SetHTTP2WriteByteTimeout(timeout time.Duration) *Client
func (*Client).SetJsonMarshal(fn func(v any) ([]byte, error)) *Client
func (*Client).SetJsonUnmarshal(fn func(data []byte, v any) error) *Client
func (*Client).SetLogger(log Logger) *Client
func (*Client).SetMaxResponseSize(max int64) *Client
func (*Client).SetMultipartBoundaryFunc(fn func() string) *Client
func (*Client).SetOutputDirectory(dir string) *Client
func (*Client).SetProxy(proxy func(*http.Request) (*urlpkg.URL, error)) *Client
func (*Client).SetProxyURL(proxyUrl string) *Client
func (*Client).SetRedirectPolicy(policies ...RedirectPolicy) *Client
func (*Client).SetResolver(r *net.Resolver) *Client
func (*Client).SetResponseBodyTransformer(fn func(rawBody []byte, req *Request, resp *Response) (transformedBody []byte, err error)) *Client
func (*Client).SetResultStateCheckFunc(fn func(resp *Response) ResultState) *Client
func (*Client).SetRootCertFromString(pemContent string) *Client
func (*Client).SetRootCertsFromFile(pemFiles ...string) *Client
func (*Client).SetScheme(scheme string) *Client
func (*Client).SetTimeout(d time.Duration) *Client
func (*Client).SetTLSClientConfig(conf *tls.Config) *Client
func (*Client).SetTLSFingerprint(clientHelloID utls.ClientHelloID) *Client
func (*Client).SetTLSFingerprint360() *Client
func (*Client).SetTLSFingerprintAndroid() *Client
func (*Client).SetTLSFingerprintChrome() *Client
func (*Client).SetTLSFingerprintEdge() *Client
func (*Client).SetTLSFingerprintFirefox() *Client
func (*Client).SetTLSFingerprintIOS() *Client
func (*Client).SetTLSFingerprintQQ() *Client
func (*Client).SetTLSFingerprintRandomized() *Client
func (*Client).SetTLSFingerprintSafari() *Client
func (*Client).SetTLSFingerprintSpec(fn func() utls.ClientHelloSpec) *Client
func (*Client).SetTLSHandshake(fn func(ctx context.Context, addr string, plainConn net.Conn) (conn net.Conn, tlsState *tls.ConnectionState, err error)) *Client
func (*Client).SetTLSHandshakeTimeout(timeout time.Duration) *Client
func (*Client).SetUnixSocket(file string) *Client
func (*Client).SetUserAgent(userAgent string) *Client
func (*Client).SetXmlMarshal(fn func(v any) ([]byte, error)) *Client
func (*Client).SetXmlUnmarshal(fn func(data []byte, v any) error) *Client
func (*Client).WrapRoundTrip(wrappers ...RoundTripWrapper) *Client
func (*Client).WrapRoundTripFunc(funcs ...RoundTripWrapperFunc) *Client
func (*Request).GetClient() *Client
func github.com/goforj/httpx.(*Client).Raw() *Client
func github.com/goforj/httpx.(*Client).Req() *Client
func SetDefaultClient(c *Client)
func (*Request).SetClient(client *Client) *Request
ContentDisposition represents parameters in `Content-Disposition`
MIME header of multipart request. Add adds a new key-value pair of Content-Disposition
func (*ContentDisposition).Add(key, value string) *ContentDisposition
DownloadInfo is the information for each DownloadCallback call. downloaded body length in bytes. Response is the corresponding Response during download.
FileUpload represents a "form-data" multipart Optional Content-Type Optional extra ContentDisposition parameters.
According to the HTTP specification, this should be nil,
but some servers may not follow the specification and
requires `Content-Disposition` parameters more than just
"name" and "filename". "filename" parameter in `Content-Disposition` Optional file length in bytes. The file to be uploaded. "name" parameter in `Content-Disposition`
func SetFileUpload(f ...FileUpload) *Request
func (*Request).SetFileUpload(uploads ...FileUpload) *Request
HttpRoundTripFunc is a http.RoundTripper implementation, which is a simple function. RoundTrip implements http.RoundTripper.
HttpRoundTripFunc : net/http.RoundTripper
HttpRoundTripWrapper is transport middleware function.
func (*Transport).WrapRoundTrip(wrappers ...HttpRoundTripWrapper) *Transport
HttpRoundTripWrapperFunc is transport middleware function, more convenient than HttpRoundTripWrapper.
func (*Transport).WrapRoundTripFunc(funcs ...HttpRoundTripWrapperFunc) *Transport
Request struct is used to compose and fire individual request from
req client. Request provides lots of chainable settings which can
override client level settings.Body[]byteCookies[]*http.CookieErroranyFormDataurlpkg.ValuesGetBodyGetContentFuncHeadershttp.HeaderMethodstringOrderedFormData[]stringPathParamsmap[string]stringQueryParamsurlpkg.ValuesRawRequest*http.Request // read onlyResultanyRetryAttemptintStartTimetime.Time URL is an auto-generated field, and is nil in request middleware (OnBeforeRequest),
consider using RawURL if you want, it's not nil in client middleware (WrapRoundTripFunc) AddQueryParam add a URL query parameter for the request. AddQueryParams add one or more values of specified URL query parameter for the request. AddRetryCondition adds a retry condition, which determines whether the
request should retry. AddRetryHook adds a retry hook which will be executed before a retry. Context method returns the Context if its already set in request
otherwise it creates new one using `context.Background()`. Delete fires http request with DELETE method and the specified URL. DisableAutoReadResponse disable read response body automatically (enabled by default). DisableForceChunkedEncoding disables force using chunked encoding when uploading. DisableForceMultipart disables force using multipart to upload form data. DisableTrace disables trace. Do fires http request, 0 or 1 context is allowed, and returns the *Response which
is always not nil, and Response.Err is not nil if error occurs. EnableAutoReadResponse enable read response body automatically (enabled by default). EnableCloseConnection closes the connection after sending this
request and reading its response if set to true in HTTP/1.1 and
HTTP/2.
Setting this field prevents reuse of TCP connections between
requests to the same hosts event if EnableKeepAlives() were called. EnableDump enables dump, including all content for the request and response by default. EnableDumpTo enables dump and save to the specified io.Writer. EnableDumpToFile enables dump and save to the specified filename. EnableDumpWithoutBody enables dump only header for the request and response. EnableDumpWithoutHeader enables dump only Body for the request and response. EnableDumpWithoutRequest enables dump only response. EnableDumpWithoutRequestBody enables dump with request Body excluded,
can be used in upload request to avoid dump the unreadable binary content. EnableDumpWithoutResponse enables dump only request. EnableDumpWithoutResponseBody enables dump with response Body excluded,
can be used in download request to avoid dump the unreadable binary content. EnableForceChunkedEncoding enables force using chunked encoding when uploading. EnableForceMultipart enables force using multipart to upload form data. EnableTrace enables trace (http3 currently does not support trace). Get fires http request with GET method and the specified URL. GetClient returns the current client used by request. GetContextData returns the context data of specified key, which set by SetContextData. GetRetryOption returns the retry configuration of this request.
It returns nil if retry has not been configured (neither via
Client.SetCommonRetry* nor Request.SetRetry*).
The returned value is the live option used by this request: mutations
affect subsequent retries on the same request. Treat it as read-only
unless you intentionally want to change retry behavior from middleware.
This is useful in middleware to inspect MaxRetries together with
Request.RetryAttempt, e.g. to report errors only after the configured
retry budget is exhausted:
client.OnAfterResponse(func(c *req.Client, resp *req.Response) error {
ro := resp.Request.GetRetryOption()
if ro == nil {
return nil
}
// Cover HTTP error statuses and transport failures (resp.Err with
// no Response). Client OnAfterResponse still runs after failed Do.
failed := resp.IsErrorState() || resp.Err != nil
// RetryAttempt >= MaxRetries only detects budget exhaustion. Retries
// may also stop earlier when a RetryCondition returns false; in that
// case RetryAttempt can be less than MaxRetries on a terminal failure.
if failed && ro.MaxRetries >= 0 &&
resp.Request.RetryAttempt >= ro.MaxRetries {
// report once after final failure
}
return nil
}) Head fires http request with HEAD method and the specified URL. HeaderToString get all header as string. MustDelete like Delete, panic if error happens, should only be used
to test without error handling. MustGet like Get, panic if error happens, should only be used to
test without error handling. MustHead like Head, panic if error happens, should only be used
to test without error handling. MustOptions like Options, panic if error happens, should only be
used to test without error handling. MustPatch like Patch, panic if error happens, should only be used
to test without error handling. MustPost like Post, panic if error happens. should only be used to
test without error handling. MustPut like Put, panic if error happens, should only be used to
test without error handling. MustQuery like Query, panic if error happens, should only be used
to test without error handling. OnAfterResponse add a response middleware which hooks after response received. Options fires http request with OPTIONS method and the specified URL. Patch fires http request with PATCH method and the specified URL. Post fires http request with POST method and the specified URL. Put fires http request with PUT method and the specified URL. Query fires http request with QUERY method and the specified URL. QUERY is a
safe, idempotent method that carries the query as request content, defined in
RFC 10008. Send fires http request with specified method and url, returns the
*Response which is always not nil, and the error is not nil if error occurs. SetBasicAuth set basic auth for the request. SetBearerAuthToken set bearer auth token for the request. SetBody set the request Body, accepts string, []byte, io.Reader, map and struct. SetBodyBytes set the request Body as []byte. SetBodyJsonBytes set the request Body as []byte and set Content-Type header
as "application/json; charset=utf-8" SetBodyJsonMarshal set the request Body that marshaled from object, and
set Content-Type header as "application/json; charset=utf-8" SetBodyJsonString set the request Body as string and set Content-Type header
as "application/json; charset=utf-8" SetBodyString set the request Body as string. SetBodyXmlBytes set the request Body as []byte and set Content-Type header
as "text/xml; charset=utf-8" SetBodyXmlMarshal set the request Body that marshaled from object, and
set Content-Type header as "text/xml; charset=utf-8" SetBodyXmlString set the request Body as string and set Content-Type header
as "text/xml; charset=utf-8" SetClient change the client of request dynamically. SetContentType set the `Content-Type` for the request. 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.
Attention: make sure call SetContext before EnableDumpXXX if you want to
dump at the request level. SetContextData sets the key-value pair data for current Request, so you
can access some extra context info for current Request in hook or middleware. SetCookies set http cookies for the request. SetDigestAuth 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 "roc" and password "123456"
client.R().SetDigestAuth("roc", "123456")
Information about Digest Access Authentication can be found in RFC7616:
https://datatracker.ietf.org/doc/html/rfc7616
Deprecated: Use Client.SetCommonDigestAuth instead. Request level digest auth is not recommended, SetDownloadCallback set the DownloadCallback which will be invoked at least
every 200ms during file upload, usually used to show download progress. SetDownloadCallbackWithInterval set the DownloadCallback which will be invoked at least
every `minInterval` during file upload, usually used to show download progress. SetDumpOptions sets DumpOptions at request level. SetError set the result that response body will be unmarshalled to if
no error occurs and Response.ResultState() returns ErrorState, by default
it requires HTTP status `code >= 400`, you can also use
Client.SetResultStateCheckFunc to customize the result state check logic.
Deprecated: Use SetErrorResult result. SetErrorResult set the result that response body will be unmarshalled to if
no error occurs and Response.ResultState() returns ErrorState, by default
it requires HTTP status `code >= 400`, you can also
use Client.SetResultStateCheckFunc to customize the result state check logic. SetFile set up a multipart form from file path to upload,
which read file from filePath automatically to upload. SetFileBytes set up a multipart form with given []byte to upload. SetFileReader set up a multipart form with a reader to upload file. SetFileUpload set the fully customized multipart file upload options. SetFiles set up a multipart form from a map to upload, which
key is the parameter name, and value is the file path. SetFormData set the form data from a map, will not been used
if request method does not allow payload. SetFormDataAnyType set the form data from a map, which value could be any type,
will convert to string automatically.
It will not been used if request method does not allow payload. SetFormDataFromValues set the form data from url.Values, will not
been used if request method does not allow payload. SetHeader set a header for the request. SetHeaderNonCanonical set a header for the request which key is a
non-canonical key (keep case unchanged), only valid for HTTP/1.1. SetHeaderOrder set the order of the http header (case-insensitive).
For example:
client.R().SetHeaderOrder(
"custom-header",
"cookie",
"user-agent",
"accept-encoding",
) SetHeaders set headers from a map for the request. SetHeadersNonCanonical set headers from a map for the request which key is a
non-canonical key (keep case unchanged), only valid for HTTP/1.1. SetMaxResponseSize sets the maximum allowed size of the response body in bytes
for this request, overriding Client.SetMaxResponseSize. A value of 0 or less
disables the limit for this request even if the client has a limit configured.
See Client.SetMaxResponseSize for behavior details. SetOrderedFormData set the ordered form data from key-values pairs. SetOutput set the io.Writer that response Body will be downloaded to. SetOutputFile set the file that response Body will be downloaded to. SetPathParam set a URL path parameter for the request. SetPathParams set URL path parameters from a map for the request. SetPseudoHeaderOrder set the order of the pseudo http header (case-insensitive).
Note this is only valid for http2 and http3.
For example:
client.R().SetPseudoHeaderOrder(
":scheme",
":authority",
":path",
":method",
) SetQueryParam set an URL query parameter for the request. SetQueryParams set URL query parameters from a map for the request. SetQueryParamsAnyType set URL query parameters from a map for the request.
The value of map is any type, will be convert to string automatically. SetQueryParamsFromStruct sets query parameters from a struct using go-querystring.
This method provides a higher-level abstraction by allowing users to directly pass
a struct to configure query parameters. The struct should use `url` tags to specify
parameter names. SetQueryParamsFromValues sets query parameters from a url.Values map.
This method allows direct configuration of query parameters from url.Values,
which is commonly used with libraries like go-querystring. SetQueryString set URL query parameters for the request using
raw query string. SetResult set the result that response Body will be unmarshalled to if
no error occurs and Response.ResultState() returns SuccessState, by default
it requires HTTP status `code >= 200 && code <= 299`, you can also use
Client.SetResultStateCheckFunc to customize the result state check logic.
Deprecated: Use SetSuccessResult instead. SetRetryBackoffInterval set retry to use a capped exponential backoff with jitter.
https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ SetRetryCondition sets the retry condition, which determines whether the
request should retry.
It will override other retry conditions if any been added before (including
client-level retry conditions). SetRetryCount enables retry and set the maximum retry count.
It will retry infinitely if count is negative. SetRetryFixedInterval set retry to use a fixed interval. SetRetryHook set the retry hook which will be executed before a retry.
It will override other retry hooks if any been added before (including
client-level retry hooks). SetRetryInterval sets the custom GetRetryIntervalFunc, you can use this to
implement your own backoff retry algorithm.
For example:
req.SetRetryInterval(func(resp *req.Response, attempt int) time.Duration {
sleep := 0.01 * math.Exp2(float64(attempt))
return time.Duration(math.Min(2, sleep)) * time.Second
}) SetSuccessResult set the result that response Body will be unmarshalled to if
no error occurs and Response.ResultState() returns SuccessState, by default
it requires HTTP status `code >= 200 && code <= 299`, you can also use
Client.SetResultStateCheckFunc to customize the result state check logic. SetURL set the url for request. SetUploadCallback set the UploadCallback which will be invoked at least
every 200ms during file upload, usually used to show upload progress. SetUploadCallbackWithInterval set the UploadCallback which will be invoked at least
every `minInterval` during file upload, usually used to show upload progress. TraceInfo returns the trace information, only available if trace is enabled
(see Request.EnableTrace and Client.EnableTraceAll).
func AddQueryParam(key, value string) *Request
func AddQueryParams(key string, values ...string) *Request
func AddRetryCondition(condition RetryConditionFunc) *Request
func AddRetryHook(hook RetryHookFunc) *Request
func DisableForceChunkedEncoding() *Request
func DisableForceMultipart() *Request
func DisableTrace() *Request
func EnableCloseConnection() *Request
func EnableDump() *Request
func EnableDumpTo(output io.Writer) *Request
func EnableDumpToFile(filename string) *Request
func EnableDumpWithoutBody() *Request
func EnableDumpWithoutHeader() *Request
func EnableDumpWithoutRequest() *Request
func EnableDumpWithoutRequestBody() *Request
func EnableDumpWithoutResponse() *Request
func EnableDumpWithoutResponseBody() *Request
func EnableForceChunkedEncoding() *Request
func EnableForceMultipart() *Request
func EnableTrace() *Request
func NewRequest() *Request
func R() *Request
func SetBasicAuth(username, password string) *Request
func SetBearerAuthToken(token string) *Request
func SetBody(body any) *Request
func SetBodyBytes(body []byte) *Request
func SetBodyJsonBytes(body []byte) *Request
func SetBodyJsonMarshal(v any) *Request
func SetBodyJsonString(body string) *Request
func SetBodyString(body string) *Request
func SetBodyXmlBytes(body []byte) *Request
func SetBodyXmlMarshal(v any) *Request
func SetBodyXmlString(body string) *Request
func SetContentType(contentType string) *Request
func SetContext(ctx context.Context) *Request
func SetCookies(cookies ...*http.Cookie) *Request
func SetDigestAuth(username, password string) *Request
func SetDownloadCallback(callback DownloadCallback) *Request
func SetDownloadCallbackWithInterval(callback DownloadCallback, minInterval time.Duration) *Request
func SetDumpOptions(opt *DumpOptions) *Request
func SetError(error any) *Request
func SetErrorResult(error any) *Request
func SetFile(paramName, filePath string) *Request
func SetFileBytes(paramName, filename string, content []byte) *Request
func SetFileReader(paramName, filePath string, reader io.Reader) *Request
func SetFiles(files map[string]string) *Request
func SetFileUpload(f ...FileUpload) *Request
func SetFormData(data map[string]string) *Request
func SetFormDataAnyType(data map[string]any) *Request
func SetFormDataFromValues(data url.Values) *Request
func SetHeader(key, value string) *Request
func SetHeaderOrder(keys ...string) *Request
func SetHeaders(hdrs map[string]string) *Request
func SetOrderedFormData(kvs ...string) *Request
func SetOutput(output io.Writer) *Request
func SetOutputFile(file string) *Request
func SetPathParam(key, value string) *Request
func SetPathParams(params map[string]string) *Request
func SetPseudoHeaderOrder(keys ...string) *Request
func SetQueryParam(key, value string) *Request
func SetQueryParams(params map[string]string) *Request
func SetQueryParamsAnyType(params map[string]any) *Request
func SetQueryParamsFromStruct(v any) *Request
func SetQueryParamsFromValues(params url.Values) *Request
func SetQueryString(query string) *Request
func SetResult(result any) *Request
func SetRetryBackoffInterval(min, max time.Duration) *Request
func SetRetryCondition(condition RetryConditionFunc) *Request
func SetRetryCount(count int) *Request
func SetRetryFixedInterval(interval time.Duration) *Request
func SetRetryHook(hook RetryHookFunc) *Request
func SetRetryInterval(getRetryIntervalFunc GetRetryIntervalFunc) *Request
func SetSuccessResult(result any) *Request
func SetUploadCallback(callback UploadCallback) *Request
func SetUploadCallbackWithInterval(callback UploadCallback, minInterval time.Duration) *Request
func SetURL(url string) *Request
func (*Client).Delete(url ...string) *Request
func (*Client).Get(url ...string) *Request
func (*Client).Head(url ...string) *Request
func (*Client).NewRequest() *Request
func (*Client).Options(url ...string) *Request
func (*Client).Patch(url ...string) *Request
func (*Client).Post(url ...string) *Request
func (*Client).Put(url ...string) *Request
func (*Client).R() *Request
func (*Request).AddQueryParam(key, value string) *Request
func (*Request).AddQueryParams(key string, values ...string) *Request
func (*Request).AddRetryCondition(condition RetryConditionFunc) *Request
func (*Request).AddRetryHook(hook RetryHookFunc) *Request
func (*Request).DisableAutoReadResponse() *Request
func (*Request).DisableForceChunkedEncoding() *Request
func (*Request).DisableForceMultipart() *Request
func (*Request).DisableTrace() *Request
func (*Request).EnableAutoReadResponse() *Request
func (*Request).EnableCloseConnection() *Request
func (*Request).EnableDump() *Request
func (*Request).EnableDumpTo(output io.Writer) *Request
func (*Request).EnableDumpToFile(filename string) *Request
func (*Request).EnableDumpWithoutBody() *Request
func (*Request).EnableDumpWithoutHeader() *Request
func (*Request).EnableDumpWithoutRequest() *Request
func (*Request).EnableDumpWithoutRequestBody() *Request
func (*Request).EnableDumpWithoutResponse() *Request
func (*Request).EnableDumpWithoutResponseBody() *Request
func (*Request).EnableForceChunkedEncoding() *Request
func (*Request).EnableForceMultipart() *Request
func (*Request).EnableTrace() *Request
func (*Request).OnAfterResponse(m ResponseMiddleware) *Request
func (*Request).SetBasicAuth(username, password string) *Request
func (*Request).SetBearerAuthToken(token string) *Request
func (*Request).SetBody(body any) *Request
func (*Request).SetBodyBytes(body []byte) *Request
func (*Request).SetBodyJsonBytes(body []byte) *Request
func (*Request).SetBodyJsonMarshal(v any) *Request
func (*Request).SetBodyJsonString(body string) *Request
func (*Request).SetBodyString(body string) *Request
func (*Request).SetBodyXmlBytes(body []byte) *Request
func (*Request).SetBodyXmlMarshal(v any) *Request
func (*Request).SetBodyXmlString(body string) *Request
func (*Request).SetClient(client *Client) *Request
func (*Request).SetContentType(contentType string) *Request
func (*Request).SetContext(ctx context.Context) *Request
func (*Request).SetContextData(key, val any) *Request
func (*Request).SetCookies(cookies ...*http.Cookie) *Request
func (*Request).SetDigestAuth(username, password string) *Request
func (*Request).SetDownloadCallback(callback DownloadCallback) *Request
func (*Request).SetDownloadCallbackWithInterval(callback DownloadCallback, minInterval time.Duration) *Request
func (*Request).SetDumpOptions(opt *DumpOptions) *Request
func (*Request).SetError(err any) *Request
func (*Request).SetErrorResult(err any) *Request
func (*Request).SetFile(paramName, filePath string) *Request
func (*Request).SetFileBytes(paramName, filename string, content []byte) *Request
func (*Request).SetFileReader(paramName, filename string, reader io.Reader) *Request
func (*Request).SetFiles(files map[string]string) *Request
func (*Request).SetFileUpload(uploads ...FileUpload) *Request
func (*Request).SetFormData(data map[string]string) *Request
func (*Request).SetFormDataAnyType(data map[string]any) *Request
func (*Request).SetFormDataFromValues(data urlpkg.Values) *Request
func (*Request).SetHeader(key, value string) *Request
func (*Request).SetHeaderNonCanonical(key, value string) *Request
func (*Request).SetHeaderOrder(keys ...string) *Request
func (*Request).SetHeaders(hdrs map[string]string) *Request
func (*Request).SetHeadersNonCanonical(hdrs map[string]string) *Request
func (*Request).SetMaxResponseSize(max int64) *Request
func (*Request).SetOrderedFormData(kvs ...string) *Request
func (*Request).SetOutput(output io.Writer) *Request
func (*Request).SetOutputFile(file string) *Request
func (*Request).SetPathParam(key, value string) *Request
func (*Request).SetPathParams(params map[string]string) *Request
func (*Request).SetPseudoHeaderOrder(keys ...string) *Request
func (*Request).SetQueryParam(key, value string) *Request
func (*Request).SetQueryParams(params map[string]string) *Request
func (*Request).SetQueryParamsAnyType(params map[string]any) *Request
func (*Request).SetQueryParamsFromStruct(v any) *Request
func (*Request).SetQueryParamsFromValues(params urlpkg.Values) *Request
func (*Request).SetQueryString(query string) *Request
func (*Request).SetResult(result any) *Request
func (*Request).SetRetryBackoffInterval(min, max time.Duration) *Request
func (*Request).SetRetryCondition(condition RetryConditionFunc) *Request
func (*Request).SetRetryCount(count int) *Request
func (*Request).SetRetryFixedInterval(interval time.Duration) *Request
func (*Request).SetRetryHook(hook RetryHookFunc) *Request
func (*Request).SetRetryInterval(getRetryIntervalFunc GetRetryIntervalFunc) *Request
func (*Request).SetSuccessResult(result any) *Request
func (*Request).SetUploadCallback(callback UploadCallback) *Request
func (*Request).SetUploadCallbackWithInterval(callback UploadCallback, minInterval time.Duration) *Request
func (*Request).SetURL(url string) *Request
func RoundTripFunc.RoundTrip(req *Request) (*Response, error)
func RoundTripper.RoundTrip(*Request) (*Response, error)
Response is the http response. Err is the underlying error, not nil if some error occurs.
Usually used in the ResponseMiddleware, you can skip logic in
ResponseMiddleware that doesn't need to be executed when err occurs. Request is the Response's related Request. The underlying http.Response is embed into Response. Body represents the response body.
The response body is streamed on demand as the Body field
is read. If the network connection fails or the server
terminates the response, Body.Read calls return an error.
The http Client and Transport guarantee that Body is always
non-nil, even on responses without a body or responses with
a zero-length body. It is the caller's responsibility to
close Body. The default HTTP client's Transport may not
reuse HTTP/1.x "keep-alive" TCP connections if the Body is
not read to completion and closed; however, manually reading
the body to completion should not be needed in most cases,
as closing the body will also cause the body to be read to
completion asynchronously, up to a conservative limit.
The Body is automatically dechunked if the server replied
with a "chunked" Transfer-Encoding.
As of Go 1.12, the Body will also implement io.Writer
on a successful "101 Switching Protocols" response,
as used by WebSockets and HTTP/2's "h2c" mode. Close records whether the header directed that the connection be
closed after reading Body. The value is advice for clients: neither
ReadResponse nor Response.Write ever closes a connection. ContentLength records the length of the associated content. The
value -1 indicates that the length is unknown. Unless Request.Method
is "HEAD", values >= 0 indicate that the given number of bytes may
be read from Body. Header maps header keys to values. If the response had multiple
headers with the same key, they may be concatenated, with comma
delimiters. (RFC 7230, section 3.2.2 requires that multiple headers
be semantically equivalent to a comma-delimited sequence.) When
Header values are duplicated by other fields in this struct (e.g.,
ContentLength, TransferEncoding, Trailer), the field values are
authoritative.
Keys in the map are canonicalized (see CanonicalHeaderKey). // e.g. "HTTP/1.0" // e.g. 1 // e.g. 0 // e.g. "200 OK" // e.g. 200 TLS contains information about the TLS connection on which the
response was received. It is nil for unencrypted responses.
The pointer is shared between responses and should not be
modified. Trailer maps trailer keys to values in the same
format as Header.
The Trailer initially contains only nil values, one for
each key specified in the server's "Trailer" header
value. Those values are not added to Header.
Trailer must not be accessed concurrently with Read calls
on the Body.
After Body.Read has returned io.EOF, Trailer will contain
any trailer values sent by the server. Contains transfer encodings from outer-most to inner-most. Value is
nil, means that "identity" encoding is used. Uncompressed reports whether the response was sent compressed but
was decompressed by the http package. When true, reading from
Body yields the uncompressed content instead of the compressed
content actually set from the server, ContentLength is set to -1,
and the "Content-Length" and "Content-Encoding" fields are deleted
from the responseHeader. To get the original response from
the server, set Transport.DisableCompression to true. Bytes return the response body as []bytes that have already been read, could be
nil if not read, the following cases are already read:
1. `Request.SetResult` or `Request.SetError` is called.
2. `Client.DisableAutoReadResponse` and `Request.DisableAutoReadResponse` is not
called, and also `Request.SetOutput` and `Request.SetOutputFile` is not called. Cookies parses and returns the cookies set in the Set-Cookie headers. Dump return the string content that have been dumped for the request.
`Request.Dump` or `Request.DumpXXX` MUST have been called. Error returns the automatically unmarshalled object when Request.SetErrorResult
or Client.SetCommonErrorResult is called, and ResultState returns ErrorState.
Otherwise, return nil.
Deprecated: Use ErrorResult instead. ErrorResult returns the automatically unmarshalled object when Request.SetErrorResult
or Client.SetCommonErrorResult is called, and ResultState returns ErrorState.
Otherwise, return nil. GetContentType return the `Content-Type` header value. GetHeader returns the response header value by key. GetHeaderValues returns the response header values by key. GetStatus returns the response status. GetStatusCode returns the response status code. HeaderToString get all header as string. Into unmarshalls response body into the specified object according
to response `Content-Type`. IsError method returns true if no error occurs and HTTP status `code >= 400`
by default, you can also use Client.SetResultStateCheckFunc to customize the result
state check logic.
Deprecated: Use IsErrorState instead. IsErrorState method returns true if no error occurs and HTTP status `code >= 400`
by default, you can also use Client.SetResultStateCheckFunc to customize the result
state check logic. IsSuccess method returns true if no error occurs and HTTP status `code >= 200 and <= 299`
by default, you can also use Client.SetResultStateCheckFunc to customize the result
state check logic.
Deprecated: Use IsSuccessState instead. IsSuccessState method returns true if no error occurs and HTTP status `code >= 200 and <= 299`
by default, you can also use Client.SetResultStateCheckFunc to customize the result state
check logic. Location returns the URL of the response's "Location" header,
if present. Relative redirects are resolved relative to
[Response.Request]. [ErrNoLocation] is returned if no
Location header is present. ProtoAtLeast reports whether the HTTP protocol used
in the response is at least major.minor. ReceivedAt returns the timestamp that response we received. Result returns the automatically unmarshalled object if Request.SetSuccessResult
is called and ResultState returns SuccessState.
Otherwise, return nil.
Deprecated: Use SuccessResult instead. ResultState returns the result state.
By default, it returns SuccessState if HTTP status `code >= 200 && code <= 299`, and returns
ErrorState if HTTP status `code >= 400`, otherwise returns UnknownState.
You can also use Client.SetResultStateCheckFunc to customize the result
state check logic. Set response body with byte array content Set response body with string content String returns the response body as string that have already been read, could be
nil if not read, the following cases are already read:
1. `Request.SetResult` or `Request.SetError` is called.
2. `Client.DisableAutoReadResponse` and `Request.DisableAutoReadResponse` is not
called, and also `Request.SetOutput` and `Request.SetOutputFile` is not called. SuccessResult returns the automatically unmarshalled object if Request.SetSuccessResult
is called and ResultState returns SuccessState.
Otherwise, return nil. ToBytes returns the response body as []byte, read body if not have been read. ToString returns the response body as string, read body if not have been read. TotalTime returns the total time of the request, from request we sent to response we received. TraceInfo returns the TraceInfo from Request. Unmarshal unmarshalls response body into the specified object according
to response `Content-Type`. UnmarshalJson unmarshalls JSON response body into the specified object. UnmarshalXml unmarshalls XML response body into the specified object. Write writes r to w in the HTTP/1.x server response format,
including the status line, headers, body, and optional trailer.
This method consults the following fields of the response r:
StatusCode
ProtoMajor
ProtoMinor
Request.Method
TransferEncoding
Trailer
Body
ContentLength
Header, values for non-canonical keys will have unpredictable behavior
The Response Body is closed after it is sent.
*Response : github.com/apache/arrow-go/v18/internal/hashing.ByteSlice
*Response : github.com/pancsta/asyncmachine-go/internal/nofmt.Stringer
*Response : github.com/pandatix/go-abnf.ElemItf
*Response : expvar.Var
*Response : fmt.Stringer
func Delete(url string) (*Response, error)
func Get(url string) (*Response, error)
func Head(url string) (*Response, error)
func MustDelete(url string) *Response
func MustGet(url string) *Response
func MustHead(url string) *Response
func MustOptions(url string) *Response
func MustPatch(url string) *Response
func MustPost(url string) *Response
func MustPut(url string) *Response
func Options(url string) (*Response, error)
func Patch(url string) (*Response, error)
func Post(url string) (*Response, error)
func Put(url string) (*Response, error)
func (*Request).Delete(url string) (*Response, error)
func (*Request).Do(ctx ...context.Context) *Response
func (*Request).Get(url string) (*Response, error)
func (*Request).Head(url string) (*Response, error)
func (*Request).MustDelete(url string) *Response
func (*Request).MustGet(url string) *Response
func (*Request).MustHead(url string) *Response
func (*Request).MustOptions(url string) *Response
func (*Request).MustPatch(url string) *Response
func (*Request).MustPost(url string) *Response
func (*Request).MustPut(url string) *Response
func (*Request).MustQuery(url string) *Response
func (*Request).Options(url string) (*Response, error)
func (*Request).Patch(url string) (*Response, error)
func (*Request).Post(url string) (*Response, error)
func (*Request).Put(url string) (*Response, error)
func (*Request).Query(url string) (*Response, error)
func (*Request).Send(method, url string) (*Response, error)
func RoundTripFunc.RoundTrip(req *Request) (*Response, error)
func RoundTripper.RoundTrip(*Request) (*Response, error)
ResponseBodyTooLargeError is returned when a response body exceeds the
configured maximum size. Limit is the configured max in bytes. ContentLength
is the response's Content-Length when the body was rejected based on headers
without reading; it is -1 when the limit was exceeded while reading.ContentLengthint64Limitint64(*ResponseBodyTooLargeError) Error() string Is reports whether target is ErrResponseBodyTooLarge.
*ResponseBodyTooLargeError : error
RetryOption controls the retry behavior of a request.
It is typically configured via Client.SetCommonRetry* or Request.SetRetry*
methods and can be read from middleware with Request.GetRetryOption.
MaxRetries is the maximum number of retries (not including the initial
attempt). A negative value means retry infinitely. Zero means no retries.
GetRetryOption may still return a non-nil option if only non-count setters
(interval, condition, or hook) were used while leaving MaxRetries at zero.GetRetryIntervalGetRetryIntervalFuncMaxRetriesintRetryConditions[]RetryConditionFuncRetryHooks[]RetryHookFunc Clone returns a deep copy of RetryOption.
func (*Request).GetRetryOption() *RetryOption
func (*RetryOption).Clone() *RetryOption
RoundTripFunc is a RoundTripper implementation, which is a simple function. RoundTrip implements RoundTripper.
RoundTripFunc : RoundTripper
RoundTripWrapperFunc is client middleware function, more convenient than RoundTripWrapper.
func WrapRoundTripFunc(funcs ...RoundTripWrapperFunc) *Client
func (*Client).WrapRoundTripFunc(funcs ...RoundTripWrapperFunc) *Client
TraceInfo represents the trace information. ConnIdleTime is a duration how long the connection was previously
idle, if IsConnWasIdle is true. ConnectTime is a duration that took to obtain a successful connection. DNSLookupTime is a duration that transport took to perform
DNS lookup. FirstResponseTime is a duration that server took to respond first byte since
connection ready (after tls handshake if it's tls and not a reused connection). IsConnReused is whether this connection has been previously
used for another HTTP request. IsConnWasIdle is whether this connection was obtained from an
idle pool. LocalAddr returns the local network address. RemoteAddr returns the remote network address. ResponseTime is a duration since first response byte from server to
request completion. TCPConnectTime is a duration that took to obtain the TCP connection. TLSHandshakeTime is a duration that TLS handshake took place. TotalTime is a duration that total request took end-to-end. Blame return the human-readable reason of why request is slowing. String return the details of trace information.
TraceInfo : github.com/pancsta/asyncmachine-go/internal/nofmt.Stringer
TraceInfo : github.com/pandatix/go-abnf.ElemItf
TraceInfo : expvar.Var
TraceInfo : fmt.Stringer
func (*Request).TraceInfo() TraceInfo
func (*Response).TraceInfo() TraceInfo
Transport is an implementation of http.RoundTripper that supports HTTP,
HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT).
By default, Transport caches connections for future reuse.
This may leave many open connections when accessing many hosts.
This behavior can be managed using Transport's CloseIdleConnections method
and the MaxIdleConnsPerHost and DisableKeepAlives fields.
Transports should be reused instead of created as needed.
Transports are safe for concurrent use by multiple goroutines.
A Transport is a low-level primitive for making HTTP and HTTPS requests.
For high-level functionality, such as cookies and redirects, see Client.
Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2
for HTTPS URLs, depending on whether the server supports HTTP/2,
and how the Transport is configured. The DefaultTransport supports HTTP/2.
To explicitly enable HTTP/2 on a transport, use golang.org/x/net/http2
and call ConfigureTransport. See the package docs for more about HTTP/2.
Responses with status codes in the 1xx range are either handled
automatically (100 expect-continue) or ignored. The one
exception is HTTP status code 101 (Switching Protocols), which is
considered a terminal status and returned by RoundTrip. To see the
ignored 1xx responses, use the httptrace trace package's
ClientTrace.Got1xxResponse.
Transport only retries a request upon encountering a network error
if the request is idempotent and either has no body or has its
Request.GetBody defined. HTTP requests are considered idempotent if
they have HTTP methods GET, HEAD, OPTIONS, or TRACE; or if their
Header map contains an "Idempotency-Key" or "X-Idempotency-Key"
entry. If the idempotency key value is a zero-length slice, the
request is treated as idempotent but the header is not sent on the
wire.Cookies[]*http.CookieHeadershttp.HeaderOptionstransport.Options AutoDecompression, if true, enables automatic decompression of
compressed responses. It is equivalent to setting the Accept-Encoding
header to "gzip, deflate, br, zstd" and the Transport will handle the
decompression of the response transparently, returning the uncompressed. Debugf is the optional debug function. DialContext specifies the dial function for creating unencrypted TCP connections.
If DialContext is nil, then the transport dials using package net.
DialContext runs concurrently with calls to RoundTrip.
A RoundTrip call that initiates a dial may end up using
a connection dialed previously when the earlier connection
becomes idle before the later DialContext completes. DialTLSContext specifies an optional dial function for creating
TLS connections for non-proxied HTTPS requests.
If DialTLSContext is nil, DialContext and TLSClientConfig are used.
If DialTLSContext is set, the Dial and DialContext hooks are not used for HTTPS
requests and the TLSClientConfig and TLSHandshakeTimeout
are ignored. The returned net.Conn is assumed to already be
past the TLS handshake. DisableCompression, if true, prevents the Transport from
requesting compression with an "Accept-Encoding: gzip"
request header when the Request contains no existing
Accept-Encoding value. If the Transport requests gzip on
its own and gets a gzipped response, it's transparently
decoded in the Response.Body. However, if the user
explicitly requested gzip it is not automatically
uncompressed. DisableKeepAlives, if true, disables HTTP keep-alives and
will only use the connection to the server for a single
HTTP request.
This is unrelated to the similarly named TCP keep-alives.Options.Dump*dump.Dumper ExpectContinueTimeout, if non-zero, specifies the amount of
time to wait for a server's first response headers after fully
writing the request headers if the request has an
"Expect: 100-continue" header. Zero means no timeout and
causes the body to be sent immediately, without
waiting for the server to approve.
This time does not include the time to send the request header. GetProxyConnectHeader optionally specifies a func to return
headers to send to proxyURL during a CONNECT request to the
ip:port target.
If it returns an error, the Transport's RoundTrip fails with
that error. It can return (nil, nil) to not add headers.
If GetProxyConnectHeader is non-nil, ProxyConnectHeader is
ignored. IdleConnTimeout is the maximum amount of time an idle
(keep-alive) connection will remain idle before closing
itself.
Zero means no limit. MaxConnsPerHost optionally limits the total number of
connections per host, including connections in the dialing,
active, and idle states. On limit violation, dials will block.
Zero means no limit. MaxIdleConns controls the maximum number of idle (keep-alive)
connections across all hosts. Zero means no limit. MaxIdleConnsPerHost, if non-zero, controls the maximum idle
(keep-alive) connections to keep per-host. If zero,
defaultMaxIdleConnsPerHost is used. MaxResponseHeaderBytes specifies a limit on how many
response bytes are allowed in the server's response
header.
Zero means to use a default limit. OnProxyConnectResponse is called when the Transport gets an HTTP response from
a proxy for a CONNECT request. It's called before the check for a 200 OK response.
If it returns an error, the request fails with that error. Proxy specifies a function to return a proxy for a given
Request. If the function returns a non-nil error, the
request is aborted with the provided error.
The proxy type is determined by the URL scheme. "http",
"https", "socks5", "socks5h", "socks4", and "socks4a" are supported.
If the scheme is empty, "http" is assumed.
"socks5" is treated the same as "socks5h".
"socks4" resolves domain names locally to IPv4; "socks4a" lets the
proxy resolve domain names. SOCKS4 only supports IPv4 destinations.
If the proxy URL contains a userinfo subcomponent,
the proxy request will pass the username and password
in a Proxy-Authorization header for HTTP proxies, or the username
as the SOCKS4 user ID / SOCKS5 credentials for SOCKS proxies.
If Proxy is nil or returns a nil *URL, no proxy is used. ProxyConnectHeader optionally specifies headers to send to
proxies during CONNECT requests.
To set the header dynamically, see GetProxyConnectHeader. ReadBufferSize specifies the size of the read buffer used
when reading from the transport.
If zero, a default (currently 4KB) is used. ResponseHeaderTimeout, if non-zero, specifies the amount of
time to wait for a server's response headers after fully
writing the request (including its body, if any). This
time does not include the time to read the response body. TLSClientConfig specifies the TLS configuration to use with
tls.Client.
If nil, the default configuration is used.
If non-nil, HTTP/2 support may not be enabled by default. TLSHandshakeContext specifies an optional dial function for tls handshake,
it works even if a proxy is set, can be used to customize the tls fingerprint. TLSHandshakeTimeout specifies the maximum amount of time to
wait for a TLS handshake. Zero means no timeout. WriteBufferSize specifies the size of the write buffer used
when writing to the transport.
If zero, a default (currently 4KB) is used. CancelRequest cancels an in-flight request by closing its connection.
CancelRequest should only be called after [Transport.RoundTrip] has returned.
Deprecated: Use [Request.WithContext] to create a request with a
cancelable context instead. CancelRequest cannot cancel HTTP/2
requests. This may become a no-op in a future release of Go. Clone returns a deep copy of t's exported fields. CloseIdleConnections closes any connections which were previously
connected from previous requests but are now sitting idle in
a "keep-alive" state. It does not interrupt any connections currently
in use. DisableAutoDecode disable auto-detect charset and decode to utf-8
(enabled by default). DisableDump disables the dump. DisableForceHttpVersion disable force using specified http
version (disabled by default). DisableH2C disables HTTP2 over TCP without TLS.(*Transport) DisableHTTP3() EnableAutoDecode enable auto-detect charset and decode to utf-8
(enabled by default). EnableDump enables the dump for all requests with specified dump options. EnableForceHTTP1 enable force using HTTP1 (disabled by default). EnableForceHTTP2 enable force using HTTP2 for https requests
(disabled by default). EnableForceHTTP3 enable force using HTTP3 for https requests
(disabled by default). EnableH2C enables HTTP2 over TCP without TLS.(*Transport) EnableHTTP3() GetMaxIdleConns returns MaxIdleConns. RoundTrip implements the RoundTripper interface.
For higher-level HTTP client support (such as handling of cookies
and redirects), see Get, Post, and the Client type.
Like the RoundTripper interface, the error types returned
by RoundTrip are unspecified. SetAutoDecodeAllContentType enable try auto-detect charset and decode all
content type to utf-8. SetAutoDecodeContentType set the content types that will be auto-detected and decode
to utf-8 (e.g. "json", "xml", "html", "text"). SetAutoDecodeContentTypeFunc set the function that determines whether the
specified `Content-Type` should be auto-detected and decode to utf-8. SetDebug set the optional debug function. SetDial set the custom DialContext function, only valid for HTTP1 and HTTP2, which specifies the
dial function for creating unencrypted TCP connections.
If it is nil, then the transport dials using package net.
The dial function runs concurrently with calls to RoundTrip.
A RoundTrip call that initiates a dial may end up using a connection dialed previously when the
earlier connection becomes idle before the later dial function completes. SetDialTLS set the custom DialTLSContext function, only valid for HTTP1 and HTTP2, which specifies
an optional dial function for creating TLS connections for non-proxied HTTPS requests (proxy will
not work if set).
If it is nil, DialContext and TLSClientConfig are used.
If it is set, the function that set in SetDial is not used for HTTPS requests and the TLSClientConfig
and TLSHandshakeTimeout are ignored. The returned net.Conn is assumed to already be past the TLS handshake. SetExpectContinueTimeout set the ExpectContinueTimeout, if non-zero, specifies
the amount of time to wait for a server's first response headers after fully
writing the request headers if the request has an "Expect: 100-continue" header.
Zero means no timeout and causes the body to be sent immediately, without waiting
for the server to approve.
This time does not include the time to send the request header. SetGetProxyConnectHeader set the GetProxyConnectHeader, which optionally specifies a func
to return headers to send to proxyURL during a CONNECT request to the ip:port target.
If it returns an error, the Transport's RoundTrip fails with that error. It can
return (nil, nil) to not add headers.
If GetProxyConnectHeader is non-nil, ProxyConnectHeader is ignored. SetHTTP2ConnectionFlow set the default http2 connection flow, which is the increment
value of initial WINDOW_UPDATE frame. SetHTTP2HeaderPriority set the header priority param. SetHTTP2MaxHeaderListSize set the http2 MaxHeaderListSize,
which is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
send in the initial settings frame. It is how many bytes
of response headers are allowed. Unlike the http2 spec, zero here
means to use a default limit (currently 10MB). If you actually
want to advertise an unlimited value to the peer, Transport
interprets the highest possible value here (0xffffffff or 1<<32-1)
to mean no limit. SetHTTP2PingTimeout set the http2 PingTimeout, which is the timeout
after which the connection will be closed if a response to Ping is
not received.
Defaults to 15s SetHTTP2PriorityFrames set the ordered http2 priority frames. SetHTTP2ReadIdleTimeout set the http2 ReadIdleTimeout,
which is the timeout after which a health check using ping
frame will be carried out if no frame is received on the connection.
Note that a ping response will is considered a received frame, so if
there is no other traffic on the connection, the health check will
be performed every ReadIdleTimeout interval.
If zero, no health check is performed. SetHTTP2SettingsFrame set the ordered http2 settings frame. SetHTTP2StrictMaxConcurrentStreams set the http2
StrictMaxConcurrentStreams, which controls whether the
server's SETTINGS_MAX_CONCURRENT_STREAMS should be respected
globally. If false, new TCP connections are created to the
server as needed to keep each under the per-connection
SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
a global limit and callers of RoundTrip block when needed,
waiting for their turn. SetHTTP2WriteByteTimeout set the http2 WriteByteTimeout, which is the
timeout after which the connection will be closed no data can be written
to it. The timeout begins when data is available to write, and is
extended whenever any bytes are written. SetIdleConnTimeout set the IdleConnTimeout, which is the maximum
amount of time an idle (keep-alive) connection will remain idle before
closing itself.
Zero means no limit. SetMaxConnsPerHost set the MaxConnsPerHost, optionally limits the
total number of connections per host, including connections in the
dialing, active, and idle states. On limit violation, dials will block.
Zero means no limit. SetMaxIdleConns set the MaxIdleConns, which controls the maximum number of idle (keep-alive)
connections across all hosts. Zero means no limit. SetMaxResponseHeaderBytes set the MaxResponseHeaderBytes, which specifies a limit on how many
response bytes are allowed in the server's response header.
Zero means to use a default limit. SetProxy set the http proxy, only valid for HTTP1 and HTTP2, which specifies a function
to return a proxy for a given Request. If the function returns a non-nil error, the request
is aborted with the provided error.
The proxy type is determined by the URL scheme. "http",
"https", "socks5", "socks5h", "socks4", and "socks4a" are
supported. If the scheme is empty, "http" is assumed.
"socks5" is treated the same as "socks5h".
"socks4" resolves domain names locally to IPv4; "socks4a" lets the
proxy resolve domain names. SOCKS4 only supports IPv4 destinations.
If Proxy is nil or returns a nil *URL, no proxy is used. SetProxyConnectHeader set the ProxyConnectHeader, which optionally specifies headers to
send to proxies during CONNECT requests.
To set the header dynamically, see SetGetProxyConnectHeader. SetReadBufferSize set the ReadBufferSize, which specifies the size of the read buffer used
when reading from the transport.
If zero, a default (currently 4KB) is used. SetResponseHeaderTimeout set the ResponseHeaderTimeout, if non-zero, specifies
the amount of time to wait for a server's response headers after fully writing
the request (including its body, if any). This time does not include the time
to read the response body. SetTLSClientConfig set the custom TLSClientConfig, which specifies the TLS configuration to
use with tls.Client.
If nil, the default configuration is used.
If non-nil, HTTP/2 support may not be enabled by default. SetTLSHandshake set the custom tls handshake function, only valid for HTTP1 and HTTP2, not HTTP3,
it specifies an optional dial function for tls handshake, it works even if a proxy is set, can be
used to customize the tls fingerprint. SetTLSHandshakeTimeout set the TLSHandshakeTimeout, which specifies the
maximum amount of time waiting to wait for a TLS handshake.
Zero means no timeout. SetWriteBufferSize set the WriteBufferSize, which specifies the size of the write buffer used
when writing to the transport.
If zero, a default (currently 4KB) is used. WrapRoundTrip adds a transport middleware function that will give the caller
an opportunity to wrap the underlying http.RoundTripper. WrapRoundTripFunc adds a transport middleware function that will give the caller
an opportunity to wrap the underlying http.RoundTripper.
*Transport : net/http.RoundTripper
func NewTransport() *Transport
func T() *Transport
func (*Client).GetTransport() *Transport
func (*Transport).Clone() *Transport
func (*Transport).DisableAutoDecode() *Transport
func (*Transport).DisableForceHttpVersion() *Transport
func (*Transport).DisableH2C() *Transport
func (*Transport).EnableAutoDecode() *Transport
func (*Transport).EnableForceHTTP1() *Transport
func (*Transport).EnableForceHTTP2() *Transport
func (*Transport).EnableForceHTTP3() *Transport
func (*Transport).EnableH2C() *Transport
func (*Transport).SetAutoDecodeAllContentType() *Transport
func (*Transport).SetAutoDecodeContentTypeFunc(fn func(contentType string) bool) *Transport
func (*Transport).SetDebug(debugf func(format string, v ...any)) *Transport
func (*Transport).SetDial(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Transport
func (*Transport).SetDialTLS(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Transport
func (*Transport).SetExpectContinueTimeout(timeout time.Duration) *Transport
func (*Transport).SetGetProxyConnectHeader(fn func(ctx context.Context, proxyURL *url.URL, target string) (http.Header, error)) *Transport
func (*Transport).SetHTTP2ConnectionFlow(flow uint32) *Transport
func (*Transport).SetHTTP2HeaderPriority(priority http2.PriorityParam) *Transport
func (*Transport).SetHTTP2MaxHeaderListSize(max uint32) *Transport
func (*Transport).SetHTTP2PingTimeout(timeout time.Duration) *Transport
func (*Transport).SetHTTP2PriorityFrames(frames ...http2.PriorityFrame) *Transport
func (*Transport).SetHTTP2ReadIdleTimeout(timeout time.Duration) *Transport
func (*Transport).SetHTTP2SettingsFrame(settings ...http2.Setting) *Transport
func (*Transport).SetHTTP2StrictMaxConcurrentStreams(strict bool) *Transport
func (*Transport).SetHTTP2WriteByteTimeout(timeout time.Duration) *Transport
func (*Transport).SetIdleConnTimeout(timeout time.Duration) *Transport
func (*Transport).SetMaxConnsPerHost(max int) *Transport
func (*Transport).SetMaxIdleConns(max int) *Transport
func (*Transport).SetMaxResponseHeaderBytes(max int64) *Transport
func (*Transport).SetProxy(proxy func(*http.Request) (*url.URL, error)) *Transport
func (*Transport).SetProxyConnectHeader(header http.Header) *Transport
func (*Transport).SetReadBufferSize(size int) *Transport
func (*Transport).SetResponseHeaderTimeout(timeout time.Duration) *Transport
func (*Transport).SetTLSClientConfig(cfg *tls.Config) *Transport
func (*Transport).SetTLSHandshake(fn func(ctx context.Context, addr string, plainConn net.Conn) (conn net.Conn, tlsState *tls.ConnectionState, err error)) *Transport
func (*Transport).SetTLSHandshakeTimeout(timeout time.Duration) *Transport
func (*Transport).SetWriteBufferSize(size int) *Transport
func (*Transport).WrapRoundTrip(wrappers ...HttpRoundTripWrapper) *Transport
func (*Transport).WrapRoundTripFunc(funcs ...HttpRoundTripWrapperFunc) *Transport
UploadInfo is the information for each UploadCallback call. filename in multipart upload total file length in bytes. parameter name in multipart upload uploaded file length in bytes.
Package-Level Functions (total 242)
AddCommonQueryParam is a global wrapper methods which delegated
to the default client's Client.AddCommonQueryParam.
AddCommonQueryParams is a global wrapper methods which delegated
to the default client's Client.AddCommonQueryParams.
AddCommonRetryCondition is a global wrapper methods which delegated
to the default client's Client.AddCommonRetryCondition.
AddCommonRetryHook is a global wrapper methods which delegated
to the default client's Client.AddCommonRetryHook.
AddQueryParam is a global wrapper methods which delegated
to the default client, create a request and AddQueryParam for request.
AddQueryParams is a global wrapper methods which delegated
to the default client, create a request and AddQueryParams for request.
AddRetryCondition is a global wrapper methods which delegated
to the default client, create a request and AddRetryCondition for request.
AddRetryHook is a global wrapper methods which delegated
to the default client, create a request and AddRetryHook for request.
AllowedDomainRedirectPolicy allows redirect only if the redirected domain
match one of the domain that specified.
AllowedHostRedirectPolicy allows redirect only if the redirected host
match one of the host that specified.
AlwaysCopyHeaderRedirectPolicy ensures that the given sensitive headers will
always be copied on redirect.
By default, golang will copy all of the original request's headers on redirect,
unless they're sensitive, like "Authorization" or "Www-Authenticate". Only send
sensitive ones to the same origin, or subdomains thereof (https://go-review.googlesource.com/c/go/+/28930/)
Check discussion: https://github.com/golang/go/issues/4800
For example:
client.SetRedirectPolicy(req.AlwaysCopyHeaderRedirectPolicy("Authorization"))
C create a new client.
ClearCookies is a global wrapper methods which delegated
to the default client's Client.ClearCookies.
DefaultClient returns the global default Client.
DefaultRedirectPolicy allows up to 10 redirects
Delete is a global wrapper methods which delegated
to the default client, create a request and Delete for request.
DevMode is a global wrapper methods which delegated
to the default client's Client.DevMode.
DisableAllowGetMethodPayload is a global wrapper methods which delegated
to the default client's Client.DisableAllowGetMethodPayload.
DisableAutoDecode is a global wrapper methods which delegated
to the default client's Client.DisableAutoDecode.
DisableAutoReadResponse is a global wrapper methods which delegated
to the default client's Client.DisableAutoReadResponse.
DisableCompression is a global wrapper methods which delegated
to the default client's Client.DisableCompression.
DisableDebugLog is a global wrapper methods which delegated
to the default client's Client.DisableDebugLog.
DisableDumpAll is a global wrapper methods which delegated
to the default client's Client.DisableDumpAll.
DisableForceChunkedEncoding is a global wrapper methods which delegated
to the default client, create a request and DisableForceChunkedEncoding for request.
DisableForceHttpVersion is a global wrapper methods which delegated
to the default client's Client.DisableForceHttpVersion.
DisableForceMultipart is a global wrapper methods which delegated
to the default client, create a request and DisableForceMultipart for request.
DisableH2C is a global wrapper methods which delegated
to the default client's Client.DisableH2C.
DisableInsecureSkipVerify is a global wrapper methods which delegated
to the default client's Client.DisableInsecureSkipVerify.
DisableKeepAlives is a global wrapper methods which delegated
to the default client's Client.DisableKeepAlives.
DisableTrace is a global wrapper methods which delegated
to the default client, create a request and DisableTrace for request.
DisableTraceAll is a global wrapper methods which delegated
to the default client's Client.DisableTraceAll.
EnableAllowGetMethodPayload is a global wrapper methods which delegated
to the default client's Client.EnableAllowGetMethodPayload.
EnableAutoDecode is a global wrapper methods which delegated
to the default client's Client.EnableAutoDecode.
EnableAutoReadResponse is a global wrapper methods which delegated
to the default client's Client.EnableAutoReadResponse.
EnableCloseConnection is a global wrapper methods which delegated
to the default client, create a request and EnableCloseConnection for request.
EnableCompression is a global wrapper methods which delegated
to the default client's Client.EnableCompression.
EnableDebugLog is a global wrapper methods which delegated
to the default client's Client.EnableDebugLog.
EnableDump is a global wrapper methods which delegated
to the default client, create a request and EnableDump for request.
EnableDumpAll is a global wrapper methods which delegated
to the default client's Client.EnableDumpAll.
EnableDumpAllAsync is a global wrapper methods which delegated
to the default client's Client.EnableDumpAllAsync.
EnableDumpAllTo is a global wrapper methods which delegated
to the default client's Client.EnableDumpAllTo.
EnableDumpAllToFile is a global wrapper methods which delegated
to the default client's Client.EnableDumpAllToFile.
EnableDumpAllWithoutBody is a global wrapper methods which delegated
to the default client's Client.EnableDumpAllWithoutBody.
EnableDumpAllWithoutHeader is a global wrapper methods which delegated
to the default client's Client.EnableDumpAllWithoutHeader.
EnableDumpAllWithoutRequest is a global wrapper methods which delegated
to the default client's Client.EnableDumpAllWithoutRequest.
EnableDumpAllWithoutRequestBody is a global wrapper methods which delegated
to the default client's Client.EnableDumpAllWithoutRequestBody.
EnableDumpAllWithoutResponse is a global wrapper methods which delegated
to the default client's Client.EnableDumpAllWithoutResponse.
EnableDumpAllWithoutResponseBody is a global wrapper methods which delegated
to the default client's Client.EnableDumpAllWithoutResponseBody.
EnableDumpEachRequest is a global wrapper methods which delegated
to the default client's Client.EnableDumpEachRequest.
EnableDumpEachRequestWithoutBody is a global wrapper methods which delegated
to the default client's Client.EnableDumpEachRequestWithoutBody.
EnableDumpEachRequestWithoutHeader is a global wrapper methods which delegated
to the default client's Client.EnableDumpEachRequestWithoutHeader.
EnableDumpEachRequestWithoutRequest is a global wrapper methods which delegated
to the default client's Client.EnableDumpEachRequestWithoutRequest.
EnableDumpEachRequestWithoutRequestBody is a global wrapper methods which delegated
to the default client's Client.EnableDumpEachRequestWithoutRequestBody.
EnableDumpEachRequestWithoutResponse is a global wrapper methods which delegated
to the default client's Client.EnableDumpEachRequestWithoutResponse.
EnableDumpEachRequestWithoutResponseBody is a global wrapper methods which delegated
to the default client's Client.EnableDumpEachRequestWithoutResponseBody.
EnableDumpTo is a global wrapper methods which delegated
to the default client, create a request and EnableDumpTo for request.
EnableDumpToFile is a global wrapper methods which delegated
to the default client, create a request and EnableDumpToFile for request.
EnableDumpWithoutBody is a global wrapper methods which delegated
to the default client, create a request and EnableDumpWithoutBody for request.
EnableDumpWithoutHeader is a global wrapper methods which delegated
to the default client, create a request and EnableDumpWithoutHeader for request.
EnableDumpWithoutRequest is a global wrapper methods which delegated
to the default client, create a request and EnableDumpWithoutRequest for request.
EnableDumpWithoutRequestBody is a global wrapper methods which delegated
to the default client, create a request and EnableDumpWithoutRequestBody for request.
EnableDumpWithoutResponse is a global wrapper methods which delegated
to the default client, create a request and EnableDumpWithoutResponse for request.
EnableDumpWithoutResponseBody is a global wrapper methods which delegated
to the default client, create a request and EnableDumpWithoutResponseBody for request.
EnableForceChunkedEncoding is a global wrapper methods which delegated
to the default client, create a request and EnableForceChunkedEncoding for request.
EnableForceHTTP1 is a global wrapper methods which delegated
to the default client's Client.EnableForceHTTP1.
EnableForceHTTP2 is a global wrapper methods which delegated
to the default client's Client.EnableForceHTTP2.
EnableForceHTTP3 is a global wrapper methods which delegated
to the default client's Client.EnableForceHTTP3.
EnableForceMultipart is a global wrapper methods which delegated
to the default client, create a request and EnableForceMultipart for request.
EnableH2C is a global wrapper methods which delegated
to the default client's Client.EnableH2C.
EnableHTTP3 is a global wrapper methods which delegated
to the default client's Client.EnableHTTP3.
EnableInsecureSkipVerify is a global wrapper methods which delegated
to the default client's Client.EnableInsecureSkipVerify.
EnableKeepAlives is a global wrapper methods which delegated
to the default client's Client.EnableKeepAlives.
EnableTrace is a global wrapper methods which delegated
to the default client, create a request and EnableTrace for request.
EnableTraceAll is a global wrapper methods which delegated
to the default client's Client.EnableTraceAll.
Get is a global wrapper methods which delegated
to the default client, create a request and Get for request.
GetClient is a global wrapper methods which delegated
to the default client's Client.GetClient.
GetCookies is a global wrapper methods which delegated
to the default client's Client.GetCookies.
GetTLSClientConfig is a global wrapper methods which delegated
to the default client's Client.GetTLSClientConfig.
Head is a global wrapper methods which delegated
to the default client, create a request and Head for request.
ImpersonateChrome is a global wrapper methods which delegated
to the default client's Client.ImpersonateChrome.
ImpersonateChrome is a global wrapper methods which delegated
to the default client's Client.ImpersonateChrome.
ImpersonateChrome is a global wrapper methods which delegated
to the default client's Client.ImpersonateChrome.
MaxRedirectPolicy specifies the max number of redirect
MustDelete is a global wrapper methods which delegated
to the default client, create a request and MustDelete for request.
MustGet is a global wrapper methods which delegated
to the default client, create a request and MustGet for request.
MustHead is a global wrapper methods which delegated
to the default client, create a request and MustHead for request.
MustOptions is a global wrapper methods which delegated
to the default client, create a request and MustOptions for request.
MustPatch is a global wrapper methods which delegated
to the default client, create a request and MustPatch for request.
MustPost is a global wrapper methods which delegated
to the default client, create a request and Get for request.
MustPut is a global wrapper methods which delegated
to the default client, create a request and MustPut for request.
NewRequest is a global wrapper methods which delegated
to the default client's Client.NewRequest.
NewTransport is an alias of T
NoRedirectPolicy disable redirect behaviour
OnAfterResponse is a global wrapper methods which delegated
to the default client's Client.OnAfterResponse.
OnBeforeRequest is a global wrapper methods which delegated
to the default client's Client.OnBeforeRequest.
Options is a global wrapper methods which delegated
to the default client, create a request and Options for request.
Patch is a global wrapper methods which delegated
to the default client, create a request and Patch for request.
Post is a global wrapper methods which delegated
to the default client, create a request and Post for request.
Put is a global wrapper methods which delegated
to the default client, create a request and Put for request.
R is a global wrapper methods which delegated
to the default client's Client.R().
SameDomainRedirectPolicy allows redirect only if the redirected domain
is the same as original domain, e.g. redirect to "www.imroc.cc" from
"imroc.cc" is allowed, but redirect to "google.com" is not allowed.
SameHostRedirectPolicy allows redirect only if the redirected host
is the same as original host, e.g. redirect to "www.imroc.cc" from
"imroc.cc" is not the allowed.
SensitiveHeadersRedirectPolicy strips the given sensitive headers when the
redirect target is a different domain. This is useful for custom authentication
headers (e.g. "X-API-Key", "X-Auth-Token") that are not automatically stripped
by the standard library on cross-domain redirects.
By default, Go's net/http only strips "Authorization", "Cookie", and
"Proxy-Authorization" on cross-domain redirects. Custom headers set via
SetCommonHeader or SetHeader are forwarded to the redirect target, which can
lead to credential leakage (CWE-200).
For example:
client.SetRedirectPolicy(req.SensitiveHeadersRedirectPolicy("X-API-Key", "X-Auth-Token"))
SetAutoDecodeAllContentType is a global wrapper methods which delegated
to the default client's Client.SetAutoDecodeAllContentType.
SetAutoDecodeContentType is a global wrapper methods which delegated
to the default client's Client.SetAutoDecodeContentType.
SetAutoDecodeContentTypeFunc is a global wrapper methods which delegated
to the default client's Client.SetAutoDecodeAllTypeFunc.
SetBaseURL is a global wrapper methods which delegated
to the default client's Client.SetBaseURL.
SetBasicAuth is a global wrapper methods which delegated
to the default client, create a request and SetBasicAuth for request.
SetBearerAuthToken is a global wrapper methods which delegated
to the default client, create a request and SetBearerAuthToken for request.
SetBody is a global wrapper methods which delegated
to the default client, create a request and SetBody for request.
SetBodyBytes is a global wrapper methods which delegated
to the default client, create a request and SetBodyBytes for request.
SetBodyJsonBytes is a global wrapper methods which delegated
to the default client, create a request and SetBodyJsonBytes for request.
SetBodyJsonMarshal is a global wrapper methods which delegated
to the default client, create a request and SetBodyJsonMarshal for request.
SetBodyJsonString is a global wrapper methods which delegated
to the default client, create a request and SetBodyJsonString for request.
SetBodyString is a global wrapper methods which delegated
to the default client, create a request and SetBodyString for request.
SetBodyXmlBytes is a global wrapper methods which delegated
to the default client, create a request and SetBodyXmlBytes for request.
SetBodyXmlMarshal is a global wrapper methods which delegated
to the default client, create a request and SetBodyXmlMarshal for request.
SetBodyXmlString is a global wrapper methods which delegated
to the default client, create a request and SetBodyXmlString for request.
SetCertFromFile is a global wrapper methods which delegated
to the default client's Client.SetCertFromFile.
SetCerts is a global wrapper methods which delegated
to the default client's Client.SetCerts.
SetCommonBasicAuth is a global wrapper methods which delegated
to the default client's Client.SetCommonBasicAuth.
SetCommonBearerAuthToken is a global wrapper methods which delegated
to the default client's Client.SetCommonBearerAuthToken.
SetCommonContentType is a global wrapper methods which delegated
to the default client's Client.SetCommonContentType.
SetCommonCookies is a global wrapper methods which delegated
to the default client's Client.SetCommonCookies.
SetCommonDigestAuth is a global wrapper methods which delegated
to the default client's Client.SetCommonDigestAuth.
SetCommonDumpOptions is a global wrapper methods which delegated
to the default client's Client.SetCommonDumpOptions.
SetCommonError is a global wrapper methods which delegated
to the default client's Client.SetCommonErrorResult.
Deprecated: Use SetCommonErrorResult instead.
SetCommonErrorResult is a global wrapper methods which delegated
to the default client's Client.SetCommonError.
SetCommonFormData is a global wrapper methods which delegated
to the default client's Client.SetCommonFormData.
SetCommonFormDataFromValues is a global wrapper methods which delegated
to the default client's Client.SetCommonFormDataFromValues.
SetCommonHeader is a global wrapper methods which delegated
to the default client's Client.SetCommonHeader.
SetCommonHeaderOrder is a global wrapper methods which delegated
to the default client's Client.SetCommonHeaderOrder.
SetCommonHeaders is a global wrapper methods which delegated
to the default client's Client.SetCommonHeaders.
SetCommonPathParam is a global wrapper methods which delegated
to the default client's Client.SetCommonPathParam.
SetCommonPathParams is a global wrapper methods which delegated
to the default client's Client.SetCommonPathParams.
SetCommonPseudoHeaderOder is a global wrapper methods which delegated
to the default client's Client.SetCommonPseudoHeaderOder.
SetCommonQueryParam is a global wrapper methods which delegated
to the default client's Client.SetCommonQueryParam.
SetCommonQueryParams is a global wrapper methods which delegated
to the default client's Client.SetCommonQueryParams.
SetCommonQueryParamsFromStruct is a global wrapper methods which delegated
to the default client's Client.SetCommonQueryParamsFromStruct.
SetCommonQueryParamsFromValues is a global wrapper methods which delegated
to the default client's Client.SetCommonQueryParamsFromValues.
SetCommonQueryString is a global wrapper methods which delegated
to the default client's Client.SetCommonQueryString.
SetCommonRetryBackoffInterval is a global wrapper methods which delegated
to the default client's Client.SetCommonRetryBackoffInterval.
SetCommonRetryCondition is a global wrapper methods which delegated
to the default client's Client.SetCommonRetryCondition.
SetCommonRetryCount is a global wrapper methods which delegated
to the default client's Client.SetCommonRetryCount.
SetCommonRetryFixedInterval is a global wrapper methods which delegated
to the default client's Client.SetCommonRetryFixedInterval.
SetCommonRetryHook is a global wrapper methods which delegated
to the default client's Client.SetCommonRetryHook.
SetCommonRetryInterval is a global wrapper methods which delegated
to the default client's Client.SetCommonRetryInterval.
SetContentType is a global wrapper methods which delegated
to the default client, create a request and SetContentType for request.
SetContext is a global wrapper methods which delegated
to the default client, create a request and SetContext for request.
SetCookieJar is a global wrapper methods which delegated
to the default client's Client.SetCookieJar.
SetCookies is a global wrapper methods which delegated
to the default client, create a request and SetCookies for request.
SetDefaultClient override the global default Client.
SetDial is a global wrapper methods which delegated
to the default client's Client.SetDial.
SetDialTLS is a global wrapper methods which delegated
to the default client's Client.SetDialTLS.
SetDigestAuth is a global wrapper methods which delegated
to the default client, create a request and SetDigestAuth for request.
SetDownloadCallback is a global wrapper methods which delegated
to the default client, create a request and SetDownloadCallback for request.
SetDownloadCallbackWithInterval is a global wrapper methods which delegated
to the default client, create a request and SetDownloadCallbackWithInterval for request.
SetDumpOptions is a global wrapper methods which delegated
to the default client, create a request and SetDumpOptions for request.
SetError is a global wrapper methods which delegated
to the default client, create a request and SetErrorResult for request.
Deprecated: Use SetErrorResult instead.
SetErrorResult is a global wrapper methods which delegated
to the default client, create a request and SetErrorResult for request.
SetFile is a global wrapper methods which delegated
to the default client, create a request and SetFile for request.
SetFileBytes is a global wrapper methods which delegated
to the default client, create a request and SetFileBytes for request.
SetFileReader is a global wrapper methods which delegated
to the default client, create a request and SetFileReader for request.
SetFiles is a global wrapper methods which delegated
to the default client, create a request and SetFiles for request.
SetFileUpload is a global wrapper methods which delegated
to the default client, create a request and SetFileUpload for request.
SetFormData is a global wrapper methods which delegated
to the default client, create a request and SetFormData for request.
SetFormDataAnyType is a global wrapper methods which delegated
to the default client, create a request and SetFormDataAnyType for request.
SetFormDataFromValues is a global wrapper methods which delegated
to the default client, create a request and SetFormDataFromValues for request.
SetHeader is a global wrapper methods which delegated
to the default client, create a request and SetHeader for request.
SetHeaderOrder is a global wrapper methods which delegated
to the default client, create a request and SetHeaderOrder for request.
SetHeaders is a global wrapper methods which delegated
to the default client, create a request and SetHeaders for request.
SetHosts is a global wrapper methods which delegated
to the default client's Client.SetHosts.
SetHTTP2ConnectionFlow is a global wrapper methods which delegated
to the default client's Client.SetHTTP2ConnectionFlow.
SetHTTP2HeaderPriority is a global wrapper methods which delegated
to the default client's Client.SetHTTP2HeaderPriority.
SetHTTP2MaxHeaderListSize is a global wrapper methods which delegated
to the default client's Client.SetHTTP2MaxHeaderListSize.
SetHTTP2PingTimeout is a global wrapper methods which delegated
to the default client's Client.SetHTTP2PingTimeout.
SetHTTP2PriorityFrames is a global wrapper methods which delegated
to the default client's Client.SetHTTP2PriorityFrames.
SetHTTP2ReadIdleTimeout is a global wrapper methods which delegated
to the default client's Client.SetHTTP2ReadIdleTimeout.
SetHTTP2SettingsFrame is a global wrapper methods which delegated
to the default client's Client.SetHTTP2SettingsFrame.
SetHTTP2StrictMaxConcurrentStreams is a global wrapper methods which delegated
to the default client's Client.SetHTTP2StrictMaxConcurrentStreams.
SetHTTP2WriteByteTimeout is a global wrapper methods which delegated
to the default client's Client.SetHTTP2WriteByteTimeout.
SetJsonMarshal is a global wrapper methods which delegated
to the default client's Client.SetJsonMarshal.
SetJsonUnmarshal is a global wrapper methods which delegated
to the default client's Client.SetJsonUnmarshal.
SetLogger is a global wrapper methods which delegated
to the default client's Client.SetLogger.
SetMaxResponseSize is a global wrapper methods which delegated
to the default client's Client.SetMaxResponseSize.
SetMultipartBoundaryFunc is a global wrapper methods which delegated
to the default client's Client.SetMultipartBoundaryFunc.
SetOrderedFormData is a global wrapper methods which delegated
to the default client, create a request and SetOrderedFormData for request.
SetOutput is a global wrapper methods which delegated
to the default client, create a request and SetOutput for request.
SetOutputDirectory is a global wrapper methods which delegated
to the default client's Client.SetOutputDirectory.
SetOutputFile is a global wrapper methods which delegated
to the default client, create a request and SetOutputFile for request.
SetPathParam is a global wrapper methods which delegated
to the default client, create a request and SetPathParam for request.
SetPathParams is a global wrapper methods which delegated
to the default client, create a request and SetPathParams for request.
SetProxy is a global wrapper methods which delegated
to the default client's Client.SetProxy.
SetProxyURL is a global wrapper methods which delegated
to the default client's Client.SetProxyURL.
SetPseudoHeaderOrder is a global wrapper methods which delegated
to the default client, create a request and SetPseudoHeaderOrder for request.
SetQueryParam is a global wrapper methods which delegated
to the default client, create a request and SetQueryParam for request.
SetQueryParams is a global wrapper methods which delegated
to the default client, create a request and SetQueryParams for request.
SetQueryParamsAnyType is a global wrapper methods which delegated
to the default client, create a request and SetQueryParamsAnyType for request.
SetQueryParamsFromStruct is a global wrapper methods which delegated
to the default client, create a request and SetQueryParamsFromStruct for request.
SetQueryParamsFromValues is a global wrapper methods which delegated
to the default client, create a request and SetQueryParamsFromValues for request.
SetQueryString is a global wrapper methods which delegated
to the default client, create a request and SetQueryString for request.
SetRedirectPolicy is a global wrapper methods which delegated
to the default client's Client.SetRedirectPolicy.
SetResolver is a global wrapper methods which delegated
to the default client's Client.SetResolver.
SetResponseBodyTransformer is a global wrapper methods which delegated
to the default client's Client.SetResponseBodyTransformer.
SetResult is a global wrapper methods which delegated
to the default client, create a request and SetSuccessResult for request.
Deprecated: Use SetSuccessResult instead.
SetResultStateCheckFunc is a global wrapper methods which delegated
to the default client's Client.SetCommonResultStateCheckFunc.
SetRetryBackoffInterval is a global wrapper methods which delegated
to the default client, create a request and SetRetryBackoffInterval for request.
SetRetryCondition is a global wrapper methods which delegated
to the default client, create a request and SetRetryCondition for request.
SetRetryCount is a global wrapper methods which delegated
to the default client, create a request and SetRetryCount for request.
SetRetryFixedInterval is a global wrapper methods which delegated
to the default client, create a request and SetRetryFixedInterval for request.
SetRetryHook is a global wrapper methods which delegated
to the default client, create a request and SetRetryHook for request.
SetRetryInterval is a global wrapper methods which delegated
to the default client, create a request and SetRetryInterval for request.
SetRootCertFromString is a global wrapper methods which delegated
to the default client's Client.SetRootCertFromString.
SetRootCertsFromFile is a global wrapper methods which delegated
to the default client's Client.SetRootCertsFromFile.
SetScheme is a global wrapper methods which delegated
to the default client's Client.SetScheme.
SetSuccessResult is a global wrapper methods which delegated
to the default client, create a request and SetSuccessResult for request.
SetTimeout is a global wrapper methods which delegated
to the default client's Client.SetTimeout.
SetTLSClientConfig is a global wrapper methods which delegated
to the default client's Client.SetTLSClientConfig.
SetTLSFingerprint is a global wrapper methods which delegated
to the default client's Client.SetTLSFingerprint.
SetTLSFingerprint360 is a global wrapper methods which delegated
to the default client's Client.SetTLSFingerprint360.
SetTLSFingerprintAndroid is a global wrapper methods which delegated
to the default client's Client.SetTLSFingerprintAndroid.
SetTLSFingerprintChrome is a global wrapper methods which delegated
to the default client's Client.SetTLSFingerprintChrome.
SetTLSFingerprintEdge is a global wrapper methods which delegated
to the default client's Client.SetTLSFingerprintEdge.
SetTLSFingerprintFirefox is a global wrapper methods which delegated
to the default client's Client.SetTLSFingerprintFirefox.
SetTLSFingerprintIOS is a global wrapper methods which delegated
to the default client's Client.SetTLSFingerprintIOS.
SetTLSFingerprintQQ is a global wrapper methods which delegated
to the default client's Client.SetTLSFingerprintQQ.
SetTLSFingerprintRandomized is a global wrapper methods which delegated
to the default client's Client.SetTLSFingerprintRandomized.
SetTLSFingerprintSafari is a global wrapper methods which delegated
to the default client's Client.SetTLSFingerprintSafari.
SetTLSHandshakeTimeout is a global wrapper methods which delegated
to the default client's Client.SetTLSHandshakeTimeout.
SetUnixSocket is a global wrapper methods which delegated
to the default client's Client.SetUnixSocket.
SetUploadCallback is a global wrapper methods which delegated
to the default client, create a request and SetUploadCallback for request.
SetUploadCallbackWithInterval is a global wrapper methods which delegated
to the default client, create a request and SetUploadCallbackWithInterval for request.
SetURL is a global wrapper methods which delegated
to the default client, create a request and SetURL for request.
SetUserAgent is a global wrapper methods which delegated
to the default client's Client.SetUserAgent.
SetXmlMarshal is a global wrapper methods which delegated
to the default client's Client.SetXmlMarshal.
SetXmlUnmarshal is a global wrapper methods which delegated
to the default client's Client.SetXmlUnmarshal.
T create a Transport.
WrapRoundTrip is a global wrapper methods which delegated
to the default client's Client.WrapRoundTrip.
WrapRoundTripFunc is a global wrapper methods which delegated
to the default client's Client.WrapRoundTripFunc.
Package-Level Variables (total 2)
ErrResponseBodyTooLarge is returned when a response body exceeds the limit
configured via Client.SetMaxResponseSize or Request.SetMaxResponseSize.
Use errors.Is(err, ErrResponseBodyTooLarge) or errors.As with
*ResponseBodyTooLargeError for inspection.
NoBody is an io.ReadCloser with no bytes. Read always returns EOF
and Close always returns nil. It can be used in an outgoing client
request to explicitly signal that a request has zero bytes.
An alternative, however, is to simply set Request.Body to nil.
Package-Level Constants (total 5)
ErrorState indicates the response is in error state,
and result will be unmarshalled if Request.SetErrorResult
or Client.SetCommonErrorResult is called.
HeaderOderKey is the key of header order, which specifies the order
of the http header.
PseudoHeaderOderKey is the key of pseudo header order, which specifies
the order of the http2 and http3 pseudo header.
SuccessState indicates the response is in success state,
and result will be unmarshalled if Request.SetSuccessResult
is called.
UnknownState indicates the response is in unknown state,
and handler will be invoked if Request.SetUnknownResultHandlerFunc
or Client.SetCommonUnknownResultHandlerFunc is called.
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.