req

package module
v3.60.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 28, 2025 License: MIT Imports: 66 Imported by: 0

README

req

custom version req from https://github.com/imroc/req/

定制内容

  • 移除default client, 这个会默认创建一个全局的客户端。
  • 移除request_wrapper 这个用来快速创建一个默认客户端的请求。
  • 支持自定义 Transport, 这也是为什么要定制一个版本的重要原因,支持这个就可以通过创建多个不同配置的客户端,而底层使用相同的连接池,从而极大节省系统资源。
  • 分别在Transport层模拟tls指纹,在client层模拟请求头。这两者需要分别显性设置。

Documentation

Index

Constants

View Source
const (
	// HeaderOderKey is the key of header order, which specifies the order
	// of the http header.
	HeaderOderKey = "__header_order__"
	// PseudoHeaderOderKey is the key of pseudo header order, which specifies
	// the order of the http2 and http3 pseudo header.
	PseudoHeaderOderKey = "__pseudo_header_order__"
)

Variables

View Source
var NoBody = noBody{}

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.

Functions

This section is empty.

Types

type Client

type Client struct {
	BaseURL               string
	PathParams            map[string]string
	QueryParams           urlpkg.Values
	FormData              urlpkg.Values
	DebugLog              bool
	AllowGetMethodPayload bool
	*Transport
	// contains filtered or unexported fields
}

Client is the req's http client.

func C

func C() *Client

C create a new client.

func NewClient

func NewClient() *Client

NewClient is the alias of C

func NewClientWithTransport

func NewClientWithTransport(t *Transport) *Client

func (*Client) AddCommonQueryParam

func (c *Client) AddCommonQueryParam(key, value string) *Client

AddCommonQueryParam add a URL query parameter with a key-value pair for requests fired from the client.

func (*Client) AddCommonQueryParams

func (c *Client) AddCommonQueryParams(key string, values ...string) *Client

AddCommonQueryParams add one or more values of specified URL query parameter for requests fired from the client.

func (*Client) AddCommonRetryCondition

func (c *Client) AddCommonRetryCondition(condition RetryConditionFunc) *Client

AddCommonRetryCondition adds a retry condition, which determines whether the request should retry.

func (*Client) AddCommonRetryHook

func (c *Client) AddCommonRetryHook(hook RetryHookFunc) *Client

AddCommonRetryHook adds a retry hook for requests fired from the client, which will be executed before a retry.

func (*Client) ClearCookies

func (c *Client) ClearCookies() *Client

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.

func (*Client) Clone

func (c *Client) Clone() *Client

Clone copy and returns the Client

func (*Client) Delete

func (c *Client) Delete(url ...string) *Request

Delete create a new DELETE request.

func (*Client) DevMode

func (c *Client) DevMode() *Client

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.

func (*Client) DisableAllowGetMethodPayload

func (c *Client) DisableAllowGetMethodPayload() *Client

DisableAllowGetMethodPayload disable sending GET method requests with body.

func (*Client) DisableAutoDecode

func (c *Client) DisableAutoDecode() *Client

DisableAutoDecode disable auto-detect charset and decode to utf-8 (enabled by default).

func (*Client) DisableAutoDecompress

func (c *Client) DisableAutoDecompress() *Client

DisableAutoDecompress disables the automatic decompression (disabled by default).

func (*Client) DisableAutoReadResponse

func (c *Client) DisableAutoReadResponse() *Client

DisableAutoReadResponse disable read response body automatically (enabled by default).

func (*Client) DisableCompression

func (c *Client) DisableCompression() *Client

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.

func (*Client) DisableDebugLog

func (c *Client) DisableDebugLog() *Client

DisableDebugLog disable debug level log (disabled by default).

func (*Client) DisableDumpAll

func (c *Client) DisableDumpAll() *Client

DisableDumpAll disable dump for requests fired from the client.

func (*Client) DisableForceHttpVersion

func (c *Client) DisableForceHttpVersion() *Client

DisableForceHttpVersion disable force using specified http version (disabled by default).

func (*Client) DisableH2C

func (c *Client) DisableH2C() *Client

DisableH2C disables HTTP/2 over TCP without TLS.

func (*Client) DisableHTTP3

func (c *Client) DisableHTTP3() *Client

DisableHTTP3 disables the http3 protocol.

func (*Client) DisableInsecureSkipVerify

func (c *Client) DisableInsecureSkipVerify() *Client

DisableInsecureSkipVerify disable send https without verifing the server's certificates (disabled by default).

func (*Client) DisableKeepAlives

func (c *Client) DisableKeepAlives() *Client

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.

func (*Client) DisableTraceAll

func (c *Client) DisableTraceAll() *Client

DisableTraceAll disable trace for requests fired from the client.

func (*Client) Do

func (c *Client) Do(req *http.Request) (*http.Response, error)

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.

func (*Client) EnableAllowGetMethodPayload

func (c *Client) EnableAllowGetMethodPayload() *Client

EnableAllowGetMethodPayload allows sending GET method requests with body.

func (*Client) EnableAutoDecode

func (c *Client) EnableAutoDecode() *Client

EnableAutoDecode enable auto-detect charset and decode to utf-8 (enabled by default).

func (*Client) EnableAutoDecompress

func (c *Client) EnableAutoDecompress() *Client

EnableAutoDecompress enables the automatic decompression (disabled by default).

func (*Client) EnableAutoReadResponse

func (c *Client) EnableAutoReadResponse() *Client

EnableAutoReadResponse enable read response body automatically (enabled by default).

func (*Client) EnableCompression

func (c *Client) EnableCompression() *Client

EnableCompression enables the compression (enabled by default).

func (*Client) EnableDebugLog

func (c *Client) EnableDebugLog() *Client

EnableDebugLog enable debug level log (disabled by default).

func (*Client) EnableDumpAll

func (c *Client) EnableDumpAll() *Client

EnableDumpAll enable dump for requests fired from the client, including all content for the request and response by default.

func (*Client) EnableDumpAllAsync

func (c *Client) EnableDumpAllAsync() *Client

EnableDumpAllAsync enable dump for requests fired from the client and output asynchronously, can be used for debugging in production environment without affecting performance.

func (*Client) EnableDumpAllTo

func (c *Client) EnableDumpAllTo(output io.Writer) *Client

EnableDumpAllTo enable dump for requests fired from the client and output to the specified io.Writer.

func (*Client) EnableDumpAllToFile

func (c *Client) EnableDumpAllToFile(filename string) *Client

EnableDumpAllToFile enable dump for requests fired from the client and output to the specified file.

func (*Client) EnableDumpAllWithoutBody

func (c *Client) EnableDumpAllWithoutBody() *Client

EnableDumpAllWithoutBody enable dump for requests fired from the client without body, can be used if you only care about the header.

func (*Client) EnableDumpAllWithoutHeader

func (c *Client) EnableDumpAllWithoutHeader() *Client

EnableDumpAllWithoutHeader enable dump for requests fired from the client without header, can be used if you only care about the body.

func (*Client) EnableDumpAllWithoutRequest

func (c *Client) EnableDumpAllWithoutRequest() *Client

EnableDumpAllWithoutRequest enables dump for requests fired from the client without request, can be used if you only care about the response.

func (*Client) EnableDumpAllWithoutRequestBody

func (c *Client) EnableDumpAllWithoutRequestBody() *Client

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.

func (*Client) EnableDumpAllWithoutResponse

func (c *Client) EnableDumpAllWithoutResponse() *Client

EnableDumpAllWithoutResponse enable dump for requests fired from the client without response, can be used if you only care about the request.

func (*Client) EnableDumpAllWithoutResponseBody

func (c *Client) EnableDumpAllWithoutResponseBody() *Client

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.

func (*Client) EnableDumpEachRequest

func (c *Client) EnableDumpEachRequest() *Client

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.

func (*Client) EnableDumpEachRequestWithoutBody

func (c *Client) EnableDumpEachRequestWithoutBody() *Client

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.

func (*Client) EnableDumpEachRequestWithoutHeader

func (c *Client) EnableDumpEachRequestWithoutHeader() *Client

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.

func (*Client) EnableDumpEachRequestWithoutRequest

func (c *Client) EnableDumpEachRequestWithoutRequest() *Client

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.

func (*Client) EnableDumpEachRequestWithoutRequestBody

func (c *Client) EnableDumpEachRequestWithoutRequestBody() *Client

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.

func (*Client) EnableDumpEachRequestWithoutResponse

func (c *Client) EnableDumpEachRequestWithoutResponse() *Client

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.

func (*Client) EnableDumpEachRequestWithoutResponseBody

func (c *Client) EnableDumpEachRequestWithoutResponseBody() *Client

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.

func (*Client) EnableForceHTTP1

func (c *Client) EnableForceHTTP1() *Client

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.

func (*Client) EnableForceHTTP2

func (c *Client) EnableForceHTTP2() *Client

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.

func (*Client) EnableForceHTTP3

func (c *Client) EnableForceHTTP3() *Client

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.

func (*Client) EnableH2C

func (c *Client) EnableH2C() *Client

EnableH2C enables HTTP/2 over TCP without TLS.

func (*Client) EnableHTTP3

func (c *Client) EnableHTTP3() *Client

EnableHTTP3 enables the http3 protocol.

func (*Client) EnableInsecureSkipVerify

func (c *Client) EnableInsecureSkipVerify() *Client

EnableInsecureSkipVerify enable send https without verifing the server's certificates (disabled by default).

func (*Client) EnableKeepAlives

func (c *Client) EnableKeepAlives() *Client

EnableKeepAlives enables HTTP keep-alives (enabled by default).

func (*Client) EnableTraceAll

func (c *Client) EnableTraceAll() *Client

EnableTraceAll enable trace for requests fired from the client (http3 currently does not support trace).

func (*Client) Get

func (c *Client) Get(url ...string) *Request

Get create a new GET request, accepts 0 or 1 url.

func (*Client) GetClient

func (c *Client) GetClient() *http.Client

GetClient returns the underlying `http.Client`.

func (*Client) GetCookies

func (c *Client) GetCookies(url string) ([]*http.Cookie, error)

GetCookies get cookies from the underlying `http.Client`'s `CookieJar`.

func (*Client) GetLogger

func (c *Client) GetLogger() Logger

GetLogger return the internal logger, usually used in middleware.

func (*Client) GetTLSClientConfig

func (c *Client) GetTLSClientConfig() *tls.Config

GetTLSClientConfig return the underlying tls.Config.

func (*Client) GetTransport

func (c *Client) GetTransport() *Transport

GetTransport return the underlying transport.

func (*Client) Head

func (c *Client) Head(url ...string) *Request

Head create a new HEAD request.

func (*Client) ImpersonateChrome

func (c *Client) ImpersonateChrome() *Client

ImpersonateChrome impersonates Chrome browser (version 120).

func (*Client) ImpersonateFirefox

func (c *Client) ImpersonateFirefox() *Client

ImpersonateFirefox impersonates Firefox browser (version 120).

func (*Client) ImpersonateSafari

func (c *Client) ImpersonateSafari() *Client

ImpersonateSafari impersonates Safari browser (version 16.6).

func (*Client) NewParallelDownload

func (c *Client) NewParallelDownload(url string) *ParallelDownload

func (*Client) NewRequest

func (c *Client) NewRequest() *Request

NewRequest is the alias of R()

func (*Client) OnAfterResponse

func (c *Client) OnAfterResponse(m ResponseMiddleware) *Client

OnAfterResponse add a response middleware which hooks after response received.

func (*Client) OnBeforeRequest

func (c *Client) OnBeforeRequest(m RequestMiddleware) *Client

OnBeforeRequest add a request middleware which hooks before request sent.

func (*Client) OnError

func (c *Client) OnError(hook ErrorHook) *Client

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).

func (*Client) Options

func (c *Client) Options(url ...string) *Request

Options create a new OPTIONS request.

func (*Client) Patch

func (c *Client) Patch(url ...string) *Request

Patch create a new PATCH request.

func (*Client) Post

func (c *Client) Post(url ...string) *Request

Post create a new POST request.

func (*Client) Put

func (c *Client) Put(url ...string) *Request

Put create a new PUT request.

func (*Client) R

func (c *Client) R() *Request

R create a new request.

func (*Client) SetAutoDecodeAllContentType

func (c *Client) SetAutoDecodeAllContentType() *Client

SetAutoDecodeAllContentType enable try auto-detect charset and decode all content type to utf-8.

func (*Client) SetAutoDecodeContentType

func (c *Client) SetAutoDecodeContentType(contentTypes ...string) *Client

SetAutoDecodeContentType set the content types that will be auto-detected and decode to utf-8 (e.g. "json", "xml", "html", "text").

func (*Client) SetAutoDecodeContentTypeFunc

func (c *Client) SetAutoDecodeContentTypeFunc(fn func(contentType string) bool) *Client

SetAutoDecodeContentTypeFunc set the function that determines whether the specified `Content-Type` should be auto-detected and decode to utf-8.

func (*Client) SetBaseURL

func (c *Client) SetBaseURL(u string) *Client

SetBaseURL set the default base URL, will be used if request URL is a relative URL.

func (*Client) SetCertFromFile

func (c *Client) SetCertFromFile(certFile, keyFile string) *Client

SetCertFromFile helps to set client certificates from cert and key file.

func (*Client) SetCerts

func (c *Client) SetCerts(certs ...tls.Certificate) *Client

SetCerts set client certificates.

func (*Client) SetCommonBasicAuth

func (c *Client) SetCommonBasicAuth(username, password string) *Client

SetCommonBasicAuth set the basic auth for requests fired from the client.

func (*Client) SetCommonBearerAuthToken

func (c *Client) SetCommonBearerAuthToken(token string) *Client

SetCommonBearerAuthToken set the bearer auth token for requests fired from the client.

func (*Client) SetCommonContentType

func (c *Client) SetCommonContentType(ct string) *Client

SetCommonContentType set the `Content-Type` header for requests fired from the client.

func (*Client) SetCommonCookies

func (c *Client) SetCommonCookies(cookies ...*http.Cookie) *Client

SetCommonCookies set HTTP cookies for requests fired from the client.

func (*Client) SetCommonDigestAuth

func (c *Client) SetCommonDigestAuth(username, password string) *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

func (*Client) SetCommonDumpOptions

func (c *Client) SetCommonDumpOptions(opt *DumpOptions) *Client

SetCommonDumpOptions configures the underlying Transport's DumpOptions for requests fired from the client.

func (*Client) SetCommonError deprecated

func (c *Client) SetCommonError(err interface{}) *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.

func (*Client) SetCommonErrorResult

func (c *Client) SetCommonErrorResult(err interface{}) *Client

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.

func (*Client) SetCommonFormData

func (c *Client) SetCommonFormData(data map[string]string) *Client

SetCommonFormData set the form data from map for requests fired from the client which request method allows payload.

func (*Client) SetCommonFormDataFromValues

func (c *Client) SetCommonFormDataFromValues(data urlpkg.Values) *Client

SetCommonFormDataFromValues set the form data from url.Values for requests fired from the client which request method allows payload.

func (*Client) SetCommonHeader

func (c *Client) SetCommonHeader(key, value string) *Client

SetCommonHeader set a header for requests fired from the client.

func (*Client) SetCommonHeaderNonCanonical

func (c *Client) SetCommonHeaderNonCanonical(key, value string) *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.

func (*Client) SetCommonHeaderOrder

func (c *Client) SetCommonHeaderOrder(keys ...string) *Client

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

func (*Client) SetCommonHeaders

func (c *Client) SetCommonHeaders(hdrs map[string]string) *Client

SetCommonHeaders set headers for requests fired from the client.

func (*Client) SetCommonHeadersNonCanonical

func (c *Client) SetCommonHeadersNonCanonical(hdrs map[string]string) *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.

func (*Client) SetCommonPathParam

func (c *Client) SetCommonPathParam(key, value string) *Client

SetCommonPathParam set a path parameter for requests fired from the client.

func (*Client) SetCommonPathParams

func (c *Client) SetCommonPathParams(pathParams map[string]string) *Client

SetCommonPathParams set path parameters for requests fired from the client.

func (*Client) SetCommonPseudoHeaderOder

func (c *Client) SetCommonPseudoHeaderOder(keys ...string) *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",
)

func (*Client) SetCommonQueryParam

func (c *Client) SetCommonQueryParam(key, value string) *Client

SetCommonQueryParam set a URL query parameter with a key-value pair for requests fired from the client.

func (*Client) SetCommonQueryParams

func (c *Client) SetCommonQueryParams(params map[string]string) *Client

SetCommonQueryParams set URL query parameters with a map for requests fired from the client.

func (*Client) SetCommonQueryString

func (c *Client) SetCommonQueryString(query string) *Client

SetCommonQueryString set URL query parameters with a raw query string for requests fired from the client.

func (*Client) SetCommonRetryBackoffInterval

func (c *Client) SetCommonRetryBackoffInterval(min, max time.Duration) *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/

func (*Client) SetCommonRetryCondition

func (c *Client) SetCommonRetryCondition(condition RetryConditionFunc) *Client

SetCommonRetryCondition sets the retry condition, which determines whether the request should retry. It will override other retry conditions if any been added before.

func (*Client) SetCommonRetryCount

func (c *Client) SetCommonRetryCount(count int) *Client

SetCommonRetryCount enables retry and set the maximum retry count for requests fired from the client. It will retry infinitely if count is negative.

func (*Client) SetCommonRetryFixedInterval

func (c *Client) SetCommonRetryFixedInterval(interval time.Duration) *Client

SetCommonRetryFixedInterval set retry to use a fixed interval for requests fired from the client.

func (*Client) SetCommonRetryHook

func (c *Client) SetCommonRetryHook(hook RetryHookFunc) *Client

SetCommonRetryHook set the retry hook which will be executed before a retry. It will override other retry hooks if any been added before.

func (*Client) SetCommonRetryInterval

func (c *Client) SetCommonRetryInterval(getRetryIntervalFunc GetRetryIntervalFunc) *Client

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
	 })

func (*Client) SetCookieJar

func (c *Client) SetCookieJar(jar http.CookieJar) *Client

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.

func (*Client) SetCookieJarFactory

func (c *Client) SetCookieJarFactory(factory func() *cookiejar.Jar) *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.

func (*Client) SetDial

func (c *Client) SetDial(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Client

SetDial set the customized `DialContext` function to Transport.

func (*Client) SetDialTLS

func (c *Client) SetDialTLS(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Client

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.

func (*Client) SetHTTP2ConnectionFlow

func (c *Client) SetHTTP2ConnectionFlow(flow uint32) *Client

SetHTTP2ConnectionFlow set the default http2 connection flow, which is the increment value of initial WINDOW_UPDATE frame.

func (*Client) SetHTTP2HeaderPriority

func (c *Client) SetHTTP2HeaderPriority(priority http2.PriorityParam) *Client

SetHTTP2HeaderPriority set the header priority param.

func (*Client) SetHTTP2MaxHeaderListSize

func (c *Client) SetHTTP2MaxHeaderListSize(max uint32) *Client

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.

func (*Client) SetHTTP2PingTimeout

func (c *Client) SetHTTP2PingTimeout(timeout time.Duration) *Client

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

func (*Client) SetHTTP2PriorityFrames

func (c *Client) SetHTTP2PriorityFrames(frames ...http2.PriorityFrame) *Client

SetHTTP2PriorityFrames set the ordered http2 priority frames.

func (*Client) SetHTTP2ReadIdleTimeout

func (c *Client) SetHTTP2ReadIdleTimeout(timeout time.Duration) *Client

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.

func (*Client) SetHTTP2SettingsFrame

func (c *Client) SetHTTP2SettingsFrame(settings ...http2.Setting) *Client

SetHTTP2SettingsFrame set the ordered http2 settings frame.

func (*Client) SetHTTP2StrictMaxConcurrentStreams

func (c *Client) SetHTTP2StrictMaxConcurrentStreams(strict bool) *Client

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.

func (*Client) SetHTTP2WriteByteTimeout

func (c *Client) SetHTTP2WriteByteTimeout(timeout time.Duration) *Client

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.

func (*Client) SetJsonMarshal

func (c *Client) SetJsonMarshal(fn func(v interface{}) ([]byte, error)) *Client

SetJsonMarshal set the JSON marshal function which will be used to marshal request body.

func (*Client) SetJsonUnmarshal

func (c *Client) SetJsonUnmarshal(fn func(data []byte, v interface{}) error) *Client

SetJsonUnmarshal set the JSON unmarshal function which will be used to unmarshal response body.

func (*Client) SetLogger

func (c *Client) SetLogger(log Logger) *Client

SetLogger set the customized logger for client, will disable log if set to nil.

func (*Client) SetMultipartBoundaryFunc

func (c *Client) SetMultipartBoundaryFunc(fn func() string) *Client

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).

func (*Client) SetOutputDirectory

func (c *Client) SetOutputDirectory(dir string) *Client

SetOutputDirectory set output directory that response will be downloaded to.

func (*Client) SetProxy

func (c *Client) SetProxy(proxy func(*http.Request) (*urlpkg.URL, error)) *Client

SetProxy set the proxy function.

func (*Client) SetProxyURL

func (c *Client) SetProxyURL(proxyUrl string) *Client

SetProxyURL set proxy from the proxy URL.

func (*Client) SetRedirectPolicy

func (c *Client) SetRedirectPolicy(policies ...RedirectPolicy) *Client

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.

func (*Client) SetResponseBodyTransformer

func (c *Client) SetResponseBodyTransformer(fn func(rawBody []byte, req *Request, resp *Response) (transformedBody []byte, err error)) *Client

SetResponseBodyTransformer set the response body transformer, which can modify the response body before unmarshalled if auto-read response body is not disabled.

func (*Client) SetResultStateCheckFunc

func (c *Client) SetResultStateCheckFunc(fn func(resp *Response) ResultState) *Client

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.

func (*Client) SetRootCertFromString

func (c *Client) SetRootCertFromString(pemContent string) *Client

SetRootCertFromString set root certificates from string.

func (*Client) SetRootCertsFromFile

func (c *Client) SetRootCertsFromFile(pemFiles ...string) *Client

SetRootCertsFromFile set root certificates from files.

func (*Client) SetScheme

func (c *Client) SetScheme(scheme string) *Client

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").

func (*Client) SetTLSClientConfig

func (c *Client) SetTLSClientConfig(conf *tls.Config) *Client

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.

func (*Client) SetTLSFingerprint

func (c *Client) SetTLSFingerprint(clientHelloID utls.ClientHelloID) *Client

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.

func (*Client) SetTLSFingerprint360

func (c *Client) SetTLSFingerprint360() *Client

SetTLSFingerprint360 uses tls fingerprint of 360 browser.

func (*Client) SetTLSFingerprintAndroid

func (c *Client) SetTLSFingerprintAndroid() *Client

SetTLSFingerprintAndroid uses tls fingerprint of Android.

func (*Client) SetTLSFingerprintChrome

func (c *Client) SetTLSFingerprintChrome() *Client

SetTLSFingerprintChrome uses tls fingerprint of Chrome browser.

func (*Client) SetTLSFingerprintEdge

func (c *Client) SetTLSFingerprintEdge() *Client

SetTLSFingerprintEdge uses tls fingerprint of Edge browser.

func (*Client) SetTLSFingerprintFirefox

func (c *Client) SetTLSFingerprintFirefox() *Client

SetTLSFingerprintFirefox uses tls fingerprint of Firefox browser.

func (*Client) SetTLSFingerprintIOS

func (c *Client) SetTLSFingerprintIOS() *Client

SetTLSFingerprintIOS uses tls fingerprint of IOS.

func (*Client) SetTLSFingerprintQQ

func (c *Client) SetTLSFingerprintQQ() *Client

SetTLSFingerprintQQ uses tls fingerprint of QQ browser.

func (*Client) SetTLSFingerprintRandomized

func (c *Client) SetTLSFingerprintRandomized() *Client

SetTLSFingerprintRandomized uses randomized tls fingerprint.

func (*Client) SetTLSFingerprintSafari

func (c *Client) SetTLSFingerprintSafari() *Client

SetTLSFingerprintSafari uses tls fingerprint of Safari browser.

func (*Client) SetTLSHandshake

func (c *Client) SetTLSHandshake(fn func(ctx context.Context, addr string, plainConn net.Conn) (conn net.Conn, tlsState *tls.ConnectionState, err error)) *Client

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.

func (*Client) SetTLSHandshakeTimeout

func (c *Client) SetTLSHandshakeTimeout(timeout time.Duration) *Client

SetTLSHandshakeTimeout set the TLS handshake timeout.

func (*Client) SetTimeout

func (c *Client) SetTimeout(d time.Duration) *Client

SetTimeout set timeout for requests fired from the client.

func (*Client) SetUnixSocket

func (c *Client) SetUnixSocket(file string) *Client

SetUnixSocket set client to dial connection use unix socket. For example:

client.SetUnixSocket("/var/run/custom.sock")

func (*Client) SetUserAgent

func (c *Client) SetUserAgent(userAgent string) *Client

SetUserAgent set the "User-Agent" header for requests fired from the client.

func (*Client) SetXmlMarshal

func (c *Client) SetXmlMarshal(fn func(v interface{}) ([]byte, error)) *Client

SetXmlMarshal set the XML marshal function which will be used to marshal request body.

func (*Client) SetXmlUnmarshal

func (c *Client) SetXmlUnmarshal(fn func(data []byte, v interface{}) error) *Client

SetXmlUnmarshal set the XML unmarshal function which will be used to unmarshal response body.

func (*Client) WrapRoundTrip

func (c *Client) WrapRoundTrip(wrappers ...RoundTripWrapper) *Client

WrapRoundTrip adds a client middleware function that will give the caller an opportunity to wrap the underlying http.RoundTripper.

func (*Client) WrapRoundTripFunc

func (c *Client) WrapRoundTripFunc(funcs ...RoundTripWrapperFunc) *Client

WrapRoundTripFunc adds a client middleware function that will give the caller an opportunity to wrap the underlying http.RoundTripper.

type ContentDisposition

type ContentDisposition struct {
	// contains filtered or unexported fields
}

ContentDisposition represents parameters in `Content-Disposition` MIME header of multipart request.

func (*ContentDisposition) Add

func (c *ContentDisposition) Add(key, value string) *ContentDisposition

Add adds a new key-value pair of Content-Disposition

type DownloadCallback

type DownloadCallback func(info DownloadInfo)

DownloadCallback is the callback which will be invoked during response body download.

type DownloadInfo

type DownloadInfo struct {
	// Response is the corresponding Response during download.
	Response *Response
	// downloaded body length in bytes.
	DownloadedSize int64
}

DownloadInfo is the information for each DownloadCallback call.

type DumpOptions

type DumpOptions struct {
	Output               io.Writer
	RequestOutput        io.Writer
	ResponseOutput       io.Writer
	RequestHeaderOutput  io.Writer
	RequestBodyOutput    io.Writer
	ResponseHeaderOutput io.Writer
	ResponseBodyOutput   io.Writer
	RequestHeader        bool
	RequestBody          bool
	ResponseHeader       bool
	ResponseBody         bool
	Async                bool
}

DumpOptions controls the dump behavior.

func (*DumpOptions) Clone

func (do *DumpOptions) Clone() *DumpOptions

Clone return a copy of DumpOptions

type ErrorHook

type ErrorHook func(client *Client, req *Request, resp *Response, err error)

type FileUpload

type FileUpload struct {
	// "name" parameter in `Content-Disposition`
	ParamName string
	// "filename" parameter in `Content-Disposition`
	FileName string
	// The file to be uploaded.
	GetFileContent GetContentFunc
	// Optional file length in bytes.
	FileSize int64
	// Optional Content-Type
	ContentType string

	// 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".
	ExtraContentDisposition *ContentDisposition
}

FileUpload represents a "form-data" multipart

type GetContentFunc

type GetContentFunc func() (io.ReadCloser, error)

type GetRetryIntervalFunc

type GetRetryIntervalFunc func(resp *Response, attempt int) time.Duration

GetRetryIntervalFunc is a function that determines how long should sleep between retry attempts.

type HttpRoundTripFunc

type HttpRoundTripFunc func(req *http.Request) (resp *http.Response, err error)

HttpRoundTripFunc is a http.RoundTripper implementation, which is a simple function.

func (HttpRoundTripFunc) RoundTrip

func (fn HttpRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type HttpRoundTripWrapper

type HttpRoundTripWrapper func(rt http.RoundTripper) http.RoundTripper

HttpRoundTripWrapper is transport middleware function.

type HttpRoundTripWrapperFunc

type HttpRoundTripWrapperFunc func(rt http.RoundTripper) HttpRoundTripFunc

HttpRoundTripWrapperFunc is transport middleware function, more convenient than HttpRoundTripWrapper.

type Logger

type Logger interface {
	Errorf(format string, v ...interface{})
	Warnf(format string, v ...interface{})
	Debugf(format string, v ...interface{})
}

Logger is the abstract logging interface, gives control to the Req users, choice of the logger.

func NewLogger

func NewLogger(output io.Writer, prefix string, flag int) Logger

NewLogger create a Logger wraps the *log.Logger

func NewLoggerFromStandardLogger

func NewLoggerFromStandardLogger(l *log.Logger) Logger

type ParallelDownload

type ParallelDownload struct {
	// contains filtered or unexported fields
}

func (*ParallelDownload) Do

func (pd *ParallelDownload) Do(ctx ...context.Context) error

func (*ParallelDownload) SetConcurrency

func (pd *ParallelDownload) SetConcurrency(concurrency int) *ParallelDownload

func (*ParallelDownload) SetFileMode

func (pd *ParallelDownload) SetFileMode(perm os.FileMode) *ParallelDownload

func (*ParallelDownload) SetOutput

func (pd *ParallelDownload) SetOutput(output io.Writer) *ParallelDownload

func (*ParallelDownload) SetOutputFile

func (pd *ParallelDownload) SetOutputFile(filename string) *ParallelDownload

func (*ParallelDownload) SetSegmentSize

func (pd *ParallelDownload) SetSegmentSize(segmentSize int64) *ParallelDownload

func (*ParallelDownload) SetTempRootDir

func (pd *ParallelDownload) SetTempRootDir(tempRootDir string) *ParallelDownload

type RedirectPolicy

type RedirectPolicy func(req *http.Request, via []*http.Request) error

RedirectPolicy represents the redirect policy for Client.

func AllowedDomainRedirectPolicy

func AllowedDomainRedirectPolicy(hosts ...string) RedirectPolicy

AllowedDomainRedirectPolicy allows redirect only if the redirected domain match one of the domain that specified.

func AllowedHostRedirectPolicy

func AllowedHostRedirectPolicy(hosts ...string) RedirectPolicy

AllowedHostRedirectPolicy allows redirect only if the redirected host match one of the host that specified.

func AlwaysCopyHeaderRedirectPolicy

func AlwaysCopyHeaderRedirectPolicy(headers ...string) RedirectPolicy

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"))

func DefaultRedirectPolicy

func DefaultRedirectPolicy() RedirectPolicy

DefaultRedirectPolicy allows up to 10 redirects

func MaxRedirectPolicy

func MaxRedirectPolicy(noOfRedirect int) RedirectPolicy

MaxRedirectPolicy specifies the max number of redirect

func NoRedirectPolicy

func NoRedirectPolicy() RedirectPolicy

NoRedirectPolicy disable redirect behaviour

func SameDomainRedirectPolicy

func SameDomainRedirectPolicy() RedirectPolicy

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.

func SameHostRedirectPolicy

func SameHostRedirectPolicy() RedirectPolicy

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.

type Request

type Request struct {
	PathParams      map[string]string
	QueryParams     urlpkg.Values
	FormData        urlpkg.Values
	OrderedFormData []string
	Headers         http.Header
	Cookies         []*http.Cookie
	Result          interface{}
	Error           interface{}
	RawRequest      *http.Request
	StartTime       time.Time
	RetryAttempt    int
	RawURL          string // read only
	Method          string
	Body            []byte
	GetBody         GetContentFunc
	// 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)
	URL *urlpkg.URL
	// contains filtered or unexported fields
}

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.

func (*Request) AddQueryParam

func (r *Request) AddQueryParam(key, value string) *Request

AddQueryParam add a URL query parameter for the request.

func (*Request) AddQueryParams

func (r *Request) AddQueryParams(key string, values ...string) *Request

AddQueryParams add one or more values of specified URL query parameter for the request.

func (*Request) AddRetryCondition

func (r *Request) AddRetryCondition(condition RetryConditionFunc) *Request

AddRetryCondition adds a retry condition, which determines whether the request should retry.

func (*Request) AddRetryHook

func (r *Request) AddRetryHook(hook RetryHookFunc) *Request

AddRetryHook adds a retry hook which will be executed before a retry.

func (*Request) Context

func (r *Request) Context() context.Context

Context method returns the Context if its already set in request otherwise it creates new one using `context.Background()`.

func (*Request) Delete

func (r *Request) Delete(url string) (*Response, error)

Delete fires http request with DELETE method and the specified URL.

func (*Request) DisableAutoReadResponse

func (r *Request) DisableAutoReadResponse() *Request

DisableAutoReadResponse disable read response body automatically (enabled by default).

func (*Request) DisableForceChunkedEncoding

func (r *Request) DisableForceChunkedEncoding() *Request

DisableForceChunkedEncoding disables force using chunked encoding when uploading.

func (*Request) DisableForceMultipart

func (r *Request) DisableForceMultipart() *Request

DisableForceMultipart disables force using multipart to upload form data.

func (*Request) DisableTrace

func (r *Request) DisableTrace() *Request

DisableTrace disables trace.

func (*Request) Do

func (r *Request) Do(ctx ...context.Context) *Response

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.

func (*Request) EnableAutoReadResponse

func (r *Request) EnableAutoReadResponse() *Request

EnableAutoReadResponse enable read response body automatically (enabled by default).

func (*Request) EnableCloseConnection

func (r *Request) EnableCloseConnection() *Request

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 re-use of TCP connections between requests to the same hosts event if EnableKeepAlives() were called.

func (*Request) EnableDump

func (r *Request) EnableDump() *Request

EnableDump enables dump, including all content for the request and response by default.

func (*Request) EnableDumpTo

func (r *Request) EnableDumpTo(output io.Writer) *Request

EnableDumpTo enables dump and save to the specified io.Writer.

func (*Request) EnableDumpToFile

func (r *Request) EnableDumpToFile(filename string) *Request

EnableDumpToFile enables dump and save to the specified filename.

func (*Request) EnableDumpWithoutBody

func (r *Request) EnableDumpWithoutBody() *Request

EnableDumpWithoutBody enables dump only header for the request and response.

func (*Request) EnableDumpWithoutHeader

func (r *Request) EnableDumpWithoutHeader() *Request

EnableDumpWithoutHeader enables dump only Body for the request and response.

func (*Request) EnableDumpWithoutRequest

func (r *Request) EnableDumpWithoutRequest() *Request

EnableDumpWithoutRequest enables dump only response.

func (*Request) EnableDumpWithoutRequestBody

func (r *Request) EnableDumpWithoutRequestBody() *Request

EnableDumpWithoutRequestBody enables dump with request Body excluded, can be used in upload request to avoid dump the unreadable binary content.

func (*Request) EnableDumpWithoutResponse

func (r *Request) EnableDumpWithoutResponse() *Request

EnableDumpWithoutResponse enables dump only request.

func (*Request) EnableDumpWithoutResponseBody

func (r *Request) EnableDumpWithoutResponseBody() *Request

EnableDumpWithoutResponseBody enables dump with response Body excluded, can be used in download request to avoid dump the unreadable binary content.

func (*Request) EnableForceChunkedEncoding

func (r *Request) EnableForceChunkedEncoding() *Request

EnableForceChunkedEncoding enables force using chunked encoding when uploading.

func (*Request) EnableForceMultipart

func (r *Request) EnableForceMultipart() *Request

EnableForceMultipart enables force using multipart to upload form data.

func (*Request) EnableTrace

func (r *Request) EnableTrace() *Request

EnableTrace enables trace (http3 currently does not support trace).

func (*Request) Get

func (r *Request) Get(url string) (*Response, error)

Get fires http request with GET method and the specified URL.

func (*Request) GetClient

func (r *Request) GetClient() *Client

GetClient returns the current client used by request.

func (*Request) GetContextData

func (r *Request) GetContextData(key any) any

GetContextData returns the context data of specified key, which set by SetContextData.

func (*Request) Head

func (r *Request) Head(url string) (*Response, error)

Head fires http request with HEAD method and the specified URL.

func (*Request) HeaderToString

func (r *Request) HeaderToString() string

HeaderToString get all header as string.

func (*Request) MustDelete

func (r *Request) MustDelete(url string) *Response

MustDelete like Delete, panic if error happens, should only be used to test without error handling.

func (*Request) MustGet

func (r *Request) MustGet(url string) *Response

MustGet like Get, panic if error happens, should only be used to test without error handling.

func (*Request) MustHead

func (r *Request) MustHead(url string) *Response

MustHead like Head, panic if error happens, should only be used to test without error handling.

func (*Request) MustOptions

func (r *Request) MustOptions(url string) *Response

MustOptions like Options, panic if error happens, should only be used to test without error handling.

func (*Request) MustPatch

func (r *Request) MustPatch(url string) *Response

MustPatch like Patch, panic if error happens, should only be used to test without error handling.

func (*Request) MustPost

func (r *Request) MustPost(url string) *Response

MustPost like Post, panic if error happens. should only be used to test without error handling.

func (*Request) MustPut

func (r *Request) MustPut(url string) *Response

MustPut like Put, panic if error happens, should only be used to test without error handling.

func (*Request) OnAfterResponse

func (r *Request) OnAfterResponse(m ResponseMiddleware) *Request

OnAfterResponse add a response middleware which hooks after response received.

func (*Request) Options

func (r *Request) Options(url string) (*Response, error)

Options fires http request with OPTIONS method and the specified URL.

func (*Request) Patch

func (r *Request) Patch(url string) (*Response, error)

Patch fires http request with PATCH method and the specified URL.

func (*Request) Post

func (r *Request) Post(url string) (*Response, error)

Post fires http request with POST method and the specified URL.

func (*Request) Put

func (r *Request) Put(url string) (*Response, error)

Put fires http request with PUT method and the specified URL.

func (*Request) Send

func (r *Request) Send(method, url string) (*Response, error)

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.

func (*Request) SetBasicAuth

func (r *Request) SetBasicAuth(username, password string) *Request

SetBasicAuth set basic auth for the request.

func (*Request) SetBearerAuthToken

func (r *Request) SetBearerAuthToken(token string) *Request

SetBearerAuthToken set bearer auth token for the request.

func (*Request) SetBody

func (r *Request) SetBody(body interface{}) *Request

SetBody set the request Body, accepts string, []byte, io.Reader, map and struct.

func (*Request) SetBodyBytes

func (r *Request) SetBodyBytes(body []byte) *Request

SetBodyBytes set the request Body as []byte.

func (*Request) SetBodyJsonBytes

func (r *Request) SetBodyJsonBytes(body []byte) *Request

SetBodyJsonBytes set the request Body as []byte and set Content-Type header as "application/json; charset=utf-8"

func (*Request) SetBodyJsonMarshal

func (r *Request) SetBodyJsonMarshal(v interface{}) *Request

SetBodyJsonMarshal set the request Body that marshaled from object, and set Content-Type header as "application/json; charset=utf-8"

func (*Request) SetBodyJsonString

func (r *Request) SetBodyJsonString(body string) *Request

SetBodyJsonString set the request Body as string and set Content-Type header as "application/json; charset=utf-8"

func (*Request) SetBodyString

func (r *Request) SetBodyString(body string) *Request

SetBodyString set the request Body as string.

func (*Request) SetBodyXmlBytes

func (r *Request) SetBodyXmlBytes(body []byte) *Request

SetBodyXmlBytes set the request Body as []byte and set Content-Type header as "text/xml; charset=utf-8"

func (*Request) SetBodyXmlMarshal

func (r *Request) SetBodyXmlMarshal(v interface{}) *Request

SetBodyXmlMarshal set the request Body that marshaled from object, and set Content-Type header as "text/xml; charset=utf-8"

func (*Request) SetBodyXmlString

func (r *Request) SetBodyXmlString(body string) *Request

SetBodyXmlString set the request Body as string and set Content-Type header as "text/xml; charset=utf-8"

func (*Request) SetClient

func (r *Request) SetClient(client *Client) *Request

SetClient change the client of request dynamically.

func (*Request) SetContentType

func (r *Request) SetContentType(contentType string) *Request

SetContentType set the `Content-Type` for the request.

func (*Request) SetContext

func (r *Request) SetContext(ctx context.Context) *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.

func (*Request) SetContextData

func (r *Request) SetContextData(key, val any) *Request

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.

func (*Request) SetCookies

func (r *Request) SetCookies(cookies ...*http.Cookie) *Request

SetCookies set http cookies for the request.

func (*Request) SetDigestAuth deprecated

func (r *Request) SetDigestAuth(username, password string) *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,

func (*Request) SetDownloadCallback

func (r *Request) SetDownloadCallback(callback DownloadCallback) *Request

SetDownloadCallback set the DownloadCallback which will be invoked at least every 200ms during file upload, usually used to show download progress.

func (*Request) SetDownloadCallbackWithInterval

func (r *Request) SetDownloadCallbackWithInterval(callback DownloadCallback, minInterval time.Duration) *Request

SetDownloadCallbackWithInterval set the DownloadCallback which will be invoked at least every `minInterval` during file upload, usually used to show download progress.

func (*Request) SetDumpOptions

func (r *Request) SetDumpOptions(opt *DumpOptions) *Request

SetDumpOptions sets DumpOptions at request level.

func (*Request) SetError deprecated

func (r *Request) SetError(err interface{}) *Request

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.

func (*Request) SetErrorResult

func (r *Request) SetErrorResult(err interface{}) *Request

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.

func (*Request) SetFile

func (r *Request) SetFile(paramName, filePath string) *Request

SetFile set up a multipart form from file path to upload, which read file from filePath automatically to upload.

func (*Request) SetFileBytes

func (r *Request) SetFileBytes(paramName, filename string, content []byte) *Request

SetFileBytes set up a multipart form with given []byte to upload.

func (*Request) SetFileReader

func (r *Request) SetFileReader(paramName, filename string, reader io.Reader) *Request

SetFileReader set up a multipart form with a reader to upload file.

func (*Request) SetFileUpload

func (r *Request) SetFileUpload(uploads ...FileUpload) *Request

SetFileUpload set the fully custimized multipart file upload options.

func (*Request) SetFiles

func (r *Request) SetFiles(files map[string]string) *Request

SetFiles set up a multipart form from a map to upload, which key is the parameter name, and value is the file path.

func (*Request) SetFormData

func (r *Request) SetFormData(data map[string]string) *Request

SetFormData set the form data from a map, will not been used if request method does not allow payload.

func (*Request) SetFormDataAnyType

func (r *Request) SetFormDataAnyType(data map[string]interface{}) *Request

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.

func (*Request) SetFormDataFromValues

func (r *Request) SetFormDataFromValues(data urlpkg.Values) *Request

SetFormDataFromValues set the form data from url.Values, will not been used if request method does not allow payload.

func (*Request) SetHeader

func (r *Request) SetHeader(key, value string) *Request

SetHeader set a header for the request.

func (*Request) SetHeaderNonCanonical

func (r *Request) SetHeaderNonCanonical(key, value string) *Request

SetHeaderNonCanonical set a header for the request which key is a non-canonical key (keep case unchanged), only valid for HTTP/1.1.

func (*Request) SetHeaderOrder

func (r *Request) SetHeaderOrder(keys ...string) *Request

SetHeaderOrder set the order of the http header (case-insensitive). For example:

client.R().SetHeaderOrder(
    "custom-header",
    "cookie",
    "user-agent",
    "accept-encoding",
)

func (*Request) SetHeaders

func (r *Request) SetHeaders(hdrs map[string]string) *Request

SetHeaders set headers from a map for the request.

func (*Request) SetHeadersNonCanonical

func (r *Request) SetHeadersNonCanonical(hdrs map[string]string) *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.

func (*Request) SetOrderedFormData

func (r *Request) SetOrderedFormData(kvs ...string) *Request

SetOrderedFormData set the ordered form data from key-values pairs.

func (*Request) SetOutput

func (r *Request) SetOutput(output io.Writer) *Request

SetOutput set the io.Writer that response Body will be downloaded to.

func (*Request) SetOutputFile

func (r *Request) SetOutputFile(file string) *Request

SetOutputFile set the file that response Body will be downloaded to.

func (*Request) SetPathParam

func (r *Request) SetPathParam(key, value string) *Request

SetPathParam set a URL path parameter for the request.

func (*Request) SetPathParams

func (r *Request) SetPathParams(params map[string]string) *Request

SetPathParams set URL path parameters from a map for the request.

func (*Request) SetPseudoHeaderOrder

func (r *Request) SetPseudoHeaderOrder(keys ...string) *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",
)

func (*Request) SetQueryParam

func (r *Request) SetQueryParam(key, value string) *Request

SetQueryParam set an URL query parameter for the request.

func (*Request) SetQueryParams

func (r *Request) SetQueryParams(params map[string]string) *Request

SetQueryParams set URL query parameters from a map for the request.

func (*Request) SetQueryParamsAnyType

func (r *Request) SetQueryParamsAnyType(params map[string]interface{}) *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.

func (*Request) SetQueryString

func (r *Request) SetQueryString(query string) *Request

SetQueryString set URL query parameters for the request using raw query string.

func (*Request) SetResult deprecated

func (r *Request) SetResult(result interface{}) *Request

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.

func (*Request) SetRetryBackoffInterval

func (r *Request) SetRetryBackoffInterval(min, max time.Duration) *Request

SetRetryBackoffInterval set retry to use a capped exponential backoff with jitter. https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/

func (*Request) SetRetryCondition

func (r *Request) SetRetryCondition(condition RetryConditionFunc) *Request

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).

func (*Request) SetRetryCount

func (r *Request) SetRetryCount(count int) *Request

SetRetryCount enables retry and set the maximum retry count. It will retry infinitely if count is negative.

func (*Request) SetRetryFixedInterval

func (r *Request) SetRetryFixedInterval(interval time.Duration) *Request

SetRetryFixedInterval set retry to use a fixed interval.

func (*Request) SetRetryHook

func (r *Request) SetRetryHook(hook RetryHookFunc) *Request

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).

func (*Request) SetRetryInterval

func (r *Request) SetRetryInterval(getRetryIntervalFunc GetRetryIntervalFunc) *Request

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
})

func (*Request) SetSuccessResult

func (r *Request) SetSuccessResult(result interface{}) *Request

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.

func (*Request) SetURL

func (r *Request) SetURL(url string) *Request

SetURL set the url for request.

func (*Request) SetUploadCallback

func (r *Request) SetUploadCallback(callback UploadCallback) *Request

SetUploadCallback set the UploadCallback which will be invoked at least every 200ms during file upload, usually used to show upload progress.

func (*Request) SetUploadCallbackWithInterval

func (r *Request) SetUploadCallbackWithInterval(callback UploadCallback, minInterval time.Duration) *Request

SetUploadCallbackWithInterval set the UploadCallback which will be invoked at least every `minInterval` during file upload, usually used to show upload progress.

func (*Request) TraceInfo

func (r *Request) TraceInfo() TraceInfo

TraceInfo returns the trace information, only available if trace is enabled (see Request.EnableTrace and Client.EnableTraceAll).

type RequestMiddleware

type RequestMiddleware func(client *Client, req *Request) error

RequestMiddleware type is for request middleware, called before a request is sent

type Response

type Response struct {
	// The underlying http.Response is embed into Response.
	*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.
	Err error
	// Request is the Response's related Request.
	Request *Request
	// contains filtered or unexported fields
}

Response is the http response.

func (*Response) Bytes

func (r *Response) Bytes() []byte

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.

func (*Response) Dump

func (r *Response) Dump() string

Dump return the string content that have been dumped for the request. `Request.Dump` or `Request.DumpXXX` MUST have been called.

func (*Response) Error deprecated

func (r *Response) Error() interface{}

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.

func (*Response) ErrorResult

func (r *Response) ErrorResult() interface{}

ErrorResult returns the automatically unmarshalled object when Request.SetErrorResult or Client.SetCommonErrorResult is called, and ResultState returns ErrorState. Otherwise, return nil.

func (*Response) GetContentType

func (r *Response) GetContentType() string

GetContentType return the `Content-Type` header value.

func (*Response) GetHeader

func (r *Response) GetHeader(key string) string

GetHeader returns the response header value by key.

func (*Response) GetHeaderValues

func (r *Response) GetHeaderValues(key string) []string

GetHeaderValues returns the response header values by key.

func (*Response) GetStatus

func (r *Response) GetStatus() string

GetStatus returns the response status.

func (*Response) GetStatusCode

func (r *Response) GetStatusCode() int

GetStatusCode returns the response status code.

func (*Response) HeaderToString

func (r *Response) HeaderToString() string

HeaderToString get all header as string.

func (*Response) Into

func (r *Response) Into(v interface{}) error

Into unmarshalls response body into the specified object according to response `Content-Type`.

func (*Response) IsError deprecated

func (r *Response) IsError() bool

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.

func (*Response) IsErrorState

func (r *Response) IsErrorState() bool

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.

func (*Response) IsSuccess deprecated

func (r *Response) IsSuccess() bool

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.

func (*Response) IsSuccessState

func (r *Response) IsSuccessState() bool

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.

func (*Response) ReceivedAt

func (r *Response) ReceivedAt() time.Time

ReceivedAt returns the timestamp that response we received.

func (*Response) Result deprecated

func (r *Response) Result() interface{}

Result returns the automatically unmarshalled object if Request.SetSuccessResult is called and ResultState returns SuccessState. Otherwise, return nil.

Deprecated: Use SuccessResult instead.

func (*Response) ResultState

func (r *Response) ResultState() ResultState

ResultState returns the result state. By default, it returns SuccessState if HTTP status `code >= 400`, and returns ErrorState if HTTP status `code >= 400`, otherwise returns UnknownState. You can also use Client.SetResultStateCheckFunc to customize the result state check logic.

func (*Response) SetBody

func (r *Response) SetBody(body []byte)

Set response body with byte array content

func (*Response) SetBodyString

func (r *Response) SetBodyString(body string)

Set response body with string content

func (*Response) String

func (r *Response) String() string

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.

func (*Response) SuccessResult

func (r *Response) SuccessResult() interface{}

SuccessResult returns the automatically unmarshalled object if Request.SetSuccessResult is called and ResultState returns SuccessState. Otherwise, return nil.

func (*Response) ToBytes

func (r *Response) ToBytes() (body []byte, err error)

ToBytes returns the response body as []byte, read body if not have been read.

func (*Response) ToString

func (r *Response) ToString() (string, error)

ToString returns the response body as string, read body if not have been read.

func (*Response) TotalTime

func (r *Response) TotalTime() time.Duration

TotalTime returns the total time of the request, from request we sent to response we received.

func (*Response) TraceInfo

func (r *Response) TraceInfo() TraceInfo

TraceInfo returns the TraceInfo from Request.

func (*Response) Unmarshal

func (r *Response) Unmarshal(v interface{}) error

Unmarshal unmarshalls response body into the specified object according to response `Content-Type`.

func (*Response) UnmarshalJson

func (r *Response) UnmarshalJson(v interface{}) error

UnmarshalJson unmarshalls JSON response body into the specified object.

func (*Response) UnmarshalXml

func (r *Response) UnmarshalXml(v interface{}) error

UnmarshalXml unmarshalls XML response body into the specified object.

type ResponseMiddleware

type ResponseMiddleware func(client *Client, resp *Response) error

ResponseMiddleware type is for response middleware, called after a response has been received

type ResultState

type ResultState int

ResultState represents the state of the result.

const (
	// SuccessState indicates the response is in success state,
	// and result will be unmarshalled if Request.SetSuccessResult
	// is called.
	SuccessState ResultState = iota
	// ErrorState indicates the response is in error state,
	// and result will be unmarshalled if Request.SetErrorResult
	// or Client.SetCommonErrorResult is called.
	ErrorState
	// UnknownState indicates the response is in unknown state,
	// and handler will be invoked if Request.SetUnknownResultHandlerFunc
	// or Client.SetCommonUnknownResultHandlerFunc is called.
	UnknownState
)

type RetryConditionFunc

type RetryConditionFunc func(resp *Response, err error) bool

RetryConditionFunc is a retry condition, which determines whether the request should retry.

type RetryHookFunc

type RetryHookFunc func(resp *Response, err error)

RetryHookFunc is a retry hook which will be executed before a retry.

type RoundTripFunc

type RoundTripFunc func(req *Request) (resp *Response, err error)

RoundTripFunc is a RoundTripper implementation, which is a simple function.

func (RoundTripFunc) RoundTrip

func (fn RoundTripFunc) RoundTrip(req *Request) (*Response, error)

RoundTrip implements RoundTripper.

type RoundTripWrapper

type RoundTripWrapper func(rt RoundTripper) RoundTripper

RoundTripWrapper is client middleware function.

type RoundTripWrapperFunc

type RoundTripWrapperFunc func(rt RoundTripper) RoundTripFunc

RoundTripWrapperFunc is client middleware function, more convenient than RoundTripWrapper.

type RoundTripper

type RoundTripper interface {
	RoundTrip(*Request) (*Response, error)
}

RoundTripper is the interface of req's Client.

type TraceInfo

type TraceInfo struct {
	// DNSLookupTime is a duration that transport took to perform
	// DNS lookup.
	DNSLookupTime time.Duration

	// ConnectTime is a duration that took to obtain a successful connection.
	ConnectTime time.Duration

	// TCPConnectTime is a duration that took to obtain the TCP connection.
	TCPConnectTime time.Duration

	// TLSHandshakeTime is a duration that TLS handshake took place.
	TLSHandshakeTime time.Duration

	// 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).
	FirstResponseTime time.Duration

	// ResponseTime is a duration since first response byte from server to
	// request completion.
	ResponseTime time.Duration

	// TotalTime is a duration that total request took end-to-end.
	TotalTime time.Duration

	// IsConnReused is whether this connection has been previously
	// used for another HTTP request.
	IsConnReused bool

	// IsConnWasIdle is whether this connection was obtained from an
	// idle pool.
	IsConnWasIdle bool

	// ConnIdleTime is a duration how long the connection was previously
	// idle, if IsConnWasIdle is true.
	ConnIdleTime time.Duration

	// RemoteAddr returns the remote network address.
	RemoteAddr net.Addr

	// LocalAddr returns the local network address.
	LocalAddr net.Addr
}

TraceInfo represents the trace information.

func (TraceInfo) Blame

func (t TraceInfo) Blame() string

Blame return the human-readable reason of why request is slowing.

func (TraceInfo) String

func (t TraceInfo) String() string

String return the details of trace information.

type Transport

type Transport struct {
	Headers http.Header
	Cookies []*http.Cookie

	transport.Options
	// contains filtered or unexported fields
}

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 re-use. 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.

func NewTransport

func NewTransport() *Transport

NewTransport is an alias of T

func T

func T() *Transport

T create a Transport.

func (*Transport) CancelRequest deprecated

func (t *Transport) CancelRequest(req *http.Request)

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.

func (*Transport) Clone

func (t *Transport) Clone() *Transport

Clone returns a deep copy of t's exported fields.

func (*Transport) CloseIdleConnections

func (t *Transport) CloseIdleConnections()

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.

func (*Transport) DisableAutoDecode

func (t *Transport) DisableAutoDecode() *Transport

DisableAutoDecode disable auto-detect charset and decode to utf-8 (enabled by default).

func (*Transport) DisableDump

func (t *Transport) DisableDump()

DisableDump disables the dump.

func (*Transport) DisableForceHttpVersion

func (t *Transport) DisableForceHttpVersion() *Transport

DisableForceHttpVersion disable force using specified http version (disabled by default).

func (*Transport) DisableH2C

func (t *Transport) DisableH2C() *Transport

DisableH2C disables HTTP2 over TCP without TLS.

func (*Transport) DisableHTTP3

func (t *Transport) DisableHTTP3()

func (*Transport) EnableAutoDecode

func (t *Transport) EnableAutoDecode() *Transport

EnableAutoDecode enable auto-detect charset and decode to utf-8 (enabled by default).

func (*Transport) EnableDump

func (t *Transport) EnableDump(opt *DumpOptions)

EnableDump enables the dump for all requests with specified dump options.

func (*Transport) EnableForceHTTP1

func (t *Transport) EnableForceHTTP1() *Transport

EnableForceHTTP1 enable force using HTTP1 (disabled by default).

func (*Transport) EnableForceHTTP2

func (t *Transport) EnableForceHTTP2() *Transport

EnableForceHTTP2 enable force using HTTP2 for https requests (disabled by default).

func (*Transport) EnableForceHTTP3

func (t *Transport) EnableForceHTTP3() *Transport

EnableForceHTTP3 enable force using HTTP3 for https requests (disabled by default).

func (*Transport) EnableH2C

func (t *Transport) EnableH2C() *Transport

EnableH2C enables HTTP2 over TCP without TLS.

func (*Transport) EnableHTTP3

func (t *Transport) EnableHTTP3()

func (*Transport) GetMaxIdleConns

func (t *Transport) GetMaxIdleConns() int

GetMaxIdleConns returns MaxIdleConns.

func (*Transport) ImpersonateChrome

func (t *Transport) ImpersonateChrome() *Transport

ImpersonateChrome impersonates Chrome browser (version 120).

func (*Transport) ImpersonateFirefox

func (c *Transport) ImpersonateFirefox() *Transport

ImpersonateFirefox impersonates Firefox browser (version 120).

func (*Transport) ImpersonateSafari

func (c *Transport) ImpersonateSafari() *Transport

ImpersonateSafari impersonates Safari browser (version 16.6).

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error)

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.

func (*Transport) SetAutoDecodeAllContentType

func (t *Transport) SetAutoDecodeAllContentType() *Transport

SetAutoDecodeAllContentType enable try auto-detect charset and decode all content type to utf-8.

func (*Transport) SetAutoDecodeContentType

func (t *Transport) SetAutoDecodeContentType(contentTypes ...string)

SetAutoDecodeContentType set the content types that will be auto-detected and decode to utf-8 (e.g. "json", "xml", "html", "text").

func (*Transport) SetAutoDecodeContentTypeFunc

func (t *Transport) SetAutoDecodeContentTypeFunc(fn func(contentType string) bool) *Transport

SetAutoDecodeContentTypeFunc set the function that determines whether the specified `Content-Type` should be auto-detected and decode to utf-8.

func (*Transport) SetCommonHeaderOrder

func (t *Transport) SetCommonHeaderOrder(keys ...string) *Transport

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

func (*Transport) SetCommonPseudoHeaderOder

func (t *Transport) SetCommonPseudoHeaderOder(keys ...string) *Transport

func (*Transport) SetDebug

func (t *Transport) SetDebug(debugf func(format string, v ...interface{})) *Transport

SetDebug set the optional debug function.

func (*Transport) SetDial

func (t *Transport) SetDial(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Transport

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.

func (*Transport) SetDialTLS

func (t *Transport) SetDialTLS(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Transport

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.

func (*Transport) SetExpectContinueTimeout

func (t *Transport) SetExpectContinueTimeout(timeout time.Duration) *Transport

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.

func (*Transport) SetGetProxyConnectHeader

func (t *Transport) SetGetProxyConnectHeader(fn func(ctx context.Context, proxyURL *url.URL, target string) (http.Header, error)) *Transport

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.

func (*Transport) SetHTTP2ConnectionFlow

func (t *Transport) SetHTTP2ConnectionFlow(flow uint32) *Transport

SetHTTP2ConnectionFlow set the default http2 connection flow, which is the increment value of initial WINDOW_UPDATE frame.

func (*Transport) SetHTTP2HeaderPriority

func (t *Transport) SetHTTP2HeaderPriority(priority http2.PriorityParam) *Transport

SetHTTP2HeaderPriority set the header priority param.

func (*Transport) SetHTTP2MaxHeaderListSize

func (t *Transport) SetHTTP2MaxHeaderListSize(max uint32) *Transport

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.

func (*Transport) SetHTTP2PingTimeout

func (t *Transport) SetHTTP2PingTimeout(timeout time.Duration) *Transport

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

func (*Transport) SetHTTP2PriorityFrames

func (t *Transport) SetHTTP2PriorityFrames(frames ...http2.PriorityFrame) *Transport

SetHTTP2PriorityFrames set the ordered http2 priority frames.

func (*Transport) SetHTTP2ReadIdleTimeout

func (t *Transport) SetHTTP2ReadIdleTimeout(timeout time.Duration) *Transport

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.

func (*Transport) SetHTTP2SettingsFrame

func (t *Transport) SetHTTP2SettingsFrame(settings ...http2.Setting) *Transport

SetHTTP2SettingsFrame set the ordered http2 settings frame.

func (*Transport) SetHTTP2StrictMaxConcurrentStreams

func (t *Transport) SetHTTP2StrictMaxConcurrentStreams(strict bool) *Transport

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.

func (*Transport) SetHTTP2WriteByteTimeout

func (t *Transport) SetHTTP2WriteByteTimeout(timeout time.Duration) *Transport

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.

func (*Transport) SetIdleConnTimeout

func (t *Transport) SetIdleConnTimeout(timeout time.Duration) *Transport

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.

func (*Transport) SetMaxConnsPerHost

func (t *Transport) SetMaxConnsPerHost(max int) *Transport

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.

func (*Transport) SetMaxIdleConns

func (t *Transport) SetMaxIdleConns(max int) *Transport

SetMaxIdleConns set the MaxIdleConns, which controls the maximum number of idle (keep-alive) connections across all hosts. Zero means no limit.

func (*Transport) SetMaxResponseHeaderBytes

func (t *Transport) SetMaxResponseHeaderBytes(max int64) *Transport

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.

func (*Transport) SetProxy

func (t *Transport) SetProxy(proxy func(*http.Request) (*url.URL, error)) *Transport

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", and "socks5" are supported. If the scheme is empty, "http" is assumed.

If Proxy is nil or returns a nil *URL, no proxy is used.

func (*Transport) SetProxyConnectHeader

func (t *Transport) SetProxyConnectHeader(header http.Header) *Transport

SetProxyConnectHeader set the ProxyConnectHeader, which optionally specifies headers to send to proxies during CONNECT requests. To set the header dynamically, see SetGetProxyConnectHeader.

func (*Transport) SetReadBufferSize

func (t *Transport) SetReadBufferSize(size int) *Transport

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.

func (*Transport) SetResponseHeaderTimeout

func (t *Transport) SetResponseHeaderTimeout(timeout time.Duration) *Transport

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.

func (*Transport) SetTLSClientConfig

func (t *Transport) SetTLSClientConfig(cfg *tls.Config) *Transport

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.

func (*Transport) SetTLSFingerprint

func (t *Transport) SetTLSFingerprint(clientHelloID utls.ClientHelloID) *Transport

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.

func (*Transport) SetTLSHandshake

func (t *Transport) SetTLSHandshake(fn func(ctx context.Context, addr string, plainConn net.Conn) (conn net.Conn, tlsState *tls.ConnectionState, err error)) *Transport

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.

func (*Transport) SetTLSHandshakeTimeout

func (t *Transport) SetTLSHandshakeTimeout(timeout time.Duration) *Transport

SetTLSHandshakeTimeout set the TLSHandshakeTimeout, which specifies the maximum amount of time waiting to wait for a TLS handshake.

Zero means no timeout.

func (*Transport) SetWriteBufferSize

func (t *Transport) SetWriteBufferSize(size int) *Transport

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.

func (*Transport) WrapRoundTrip

func (t *Transport) WrapRoundTrip(wrappers ...HttpRoundTripWrapper) *Transport

WrapRoundTrip adds a transport middleware function that will give the caller an opportunity to wrap the underlying http.RoundTripper.

func (*Transport) WrapRoundTripFunc

func (t *Transport) WrapRoundTripFunc(funcs ...HttpRoundTripWrapperFunc) *Transport

WrapRoundTripFunc adds a transport middleware function that will give the caller an opportunity to wrap the underlying http.RoundTripper.

type UploadCallback

type UploadCallback func(info UploadInfo)

UploadCallback is the callback which will be invoked during multipart upload.

type UploadInfo

type UploadInfo struct {
	// parameter name in multipart upload
	ParamName string
	// filename in multipart upload
	FileName string
	// total file length in bytes.
	FileSize int64
	// uploaded file length in bytes.
	UploadedSize int64
}

UploadInfo is the information for each UploadCallback call.

Directories

Path Synopsis
Package internal contains HTTP internals shared by net/http and net/http/httputil.
Package internal contains HTTP internals shared by net/http and net/http/httputil.
bisect
Package bisect can be used by compilers and other programs to serve as a target for the bisect debugging tool.
Package bisect can be used by compilers and other programs to serve as a target for the bisect debugging tool.
godebug
Package godebug makes the settings in the $GODEBUG environment variable available to other packages.
Package godebug makes the settings in the $GODEBUG environment variable available to other packages.
godebugs
Package godebugs provides a table of known GODEBUG settings, for use by a variety of other packages, including internal/godebug, runtime, runtime/metrics, and cmd/go/internal/load.
Package godebugs provides a table of known GODEBUG settings, for use by a variety of other packages, including internal/godebug, runtime, runtime/metrics, and cmd/go/internal/load.
socks
Package socks provides a SOCKS version 5 client implementation.
Package socks provides a SOCKS version 5 client implementation.
testcert
Package testcert contains a test-only localhost certificate.
Package testcert contains a test-only localhost certificate.
pkg
tls

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL