package req

import (
	
	
	
	
	
	
	
	
	
	
	
	
	
	urlpkg 
	
	
	
	

	utls 
	

	
	
	

	
)

// DefaultClient returns the global default Client.
func () *Client {
	return defaultClient
}

// SetDefaultClient override the global default Client.
func ( *Client) {
	if  != nil {
		defaultClient = 
	}
}

var defaultClient = C()

// Client is the req's http client.
type Client struct {
	BaseURL               string
	PathParams            map[string]string
	QueryParams           urlpkg.Values
	FormData              urlpkg.Values
	DebugLog              bool
	AllowGetMethodPayload bool
	*Transport
	digestAuth              *digestAuth
	cookiejarFactory        func() http.CookieJar
	trace                   bool
	disableAutoReadResponse bool
	maxResponseSize         int64 // 0 means no limit
	commonErrorType         reflect.Type
	retryOption             *RetryOption
	jsonMarshal             func(v any) ([]byte, error)
	jsonUnmarshal           func(data []byte, v any) error
	xmlMarshal              func(v any) ([]byte, error)
	xmlUnmarshal            func(data []byte, v any) error
	multipartBoundaryFunc   func() string
	outputDirectory         string
	scheme                  string
	log                     Logger
	dumpOptions             *DumpOptions
	httpClient              *http.Client
	beforeRequest           []RequestMiddleware
	udBeforeRequest         []RequestMiddleware
	afterResponse           []ResponseMiddleware
	wrappedRoundTrip        RoundTripper
	roundTripWrappers       []RoundTripWrapper
	responseBodyTransformer func(rawBody []byte, req *Request, resp *Response) (transformedBody []byte, err error)
	resultStateCheckFunc    func(resp *Response) ResultState
	onError                 ErrorHook
}

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

// R create a new request.
func ( *Client) () *Request {
	return &Request{
		client:      ,
		retryOption: .retryOption.Clone(),
	}
}

// Get create a new GET request, accepts 0 or 1 url.
func ( *Client) ( ...string) *Request {
	 := .R()
	if len() > 0 {
		.RawURL = [0]
	}
	.Method = http.MethodGet
	return 
}

// Post create a new POST request.
func ( *Client) ( ...string) *Request {
	 := .R()
	if len() > 0 {
		.RawURL = [0]
	}
	.Method = http.MethodPost
	return 
}

// Patch create a new PATCH request.
func ( *Client) ( ...string) *Request {
	 := .R()
	if len() > 0 {
		.RawURL = [0]
	}
	.Method = http.MethodPatch
	return 
}

// Delete create a new DELETE request.
func ( *Client) ( ...string) *Request {
	 := .R()
	if len() > 0 {
		.RawURL = [0]
	}
	.Method = http.MethodDelete
	return 
}

// Put create a new PUT request.
func ( *Client) ( ...string) *Request {
	 := .R()
	if len() > 0 {
		.RawURL = [0]
	}
	.Method = http.MethodPut
	return 
}

// Head create a new HEAD request.
func ( *Client) ( ...string) *Request {
	 := .R()
	if len() > 0 {
		.RawURL = [0]
	}
	.Method = http.MethodHead
	return 
}

// Options create a new OPTIONS request.
func ( *Client) ( ...string) *Request {
	 := .R()
	if len() > 0 {
		.RawURL = [0]
	}
	.Method = http.MethodOptions
	return 
}

// GetTransport return the underlying transport.
func ( *Client) () *Transport {
	return .Transport
}

// SetResponseBodyTransformer set the response body transformer, which can modify the
// response body before unmarshalled if auto-read response body is not disabled.
func ( *Client) ( func( []byte,  *Request,  *Response) ( []byte,  error)) *Client {
	.responseBodyTransformer = 
	return 
}

// 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) ( any) *Client {
	return .SetCommonErrorResult()
}

// 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) ( any) *Client {
	if  != nil {
		.commonErrorType = util.GetType()
	}
	return 
}

// ResultState represents the state of the result.
type ResultState int

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
)

// 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) ( func( *Response) ResultState) *Client {
	.resultStateCheckFunc = 
	return 
}

// SetCommonFormDataFromValues set the form data from url.Values for requests
// fired from the client which request method allows payload.
func ( *Client) ( urlpkg.Values) *Client {
	if .FormData == nil {
		.FormData = urlpkg.Values{}
	}
	for ,  := range  {
		for ,  := range  {
			.FormData.Add(, )
		}
	}
	return 
}

// SetCommonFormData set the form data from map for requests fired from the client
// which request method allows payload.
func ( *Client) ( map[string]string) *Client {
	if .FormData == nil {
		.FormData = urlpkg.Values{}
	}
	for ,  := range  {
		.FormData.Set(, )
	}
	return 
}

// 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) ( func() string) *Client {
	.multipartBoundaryFunc = 
	return 
}

// SetBaseURL set the default base URL, will be used if request URL is
// a relative URL.
func ( *Client) ( string) *Client {
	.BaseURL = strings.TrimRight(, "/")
	return 
}

// SetOutputDirectory set output directory that response will
// be downloaded to.
func ( *Client) ( string) *Client {
	.outputDirectory = 
	return 
}

// SetCertFromFile helps to set client certificates from cert and key file.
func ( *Client) (,  string) *Client {
	,  := tls.LoadX509KeyPair(, )
	if  != nil {
		.log.Errorf("failed to load client cert: %v", )
		return 
	}
	 := .GetTLSClientConfig()
	.Certificates = append(.Certificates, )
	return 
}

// SetCerts set client certificates.
func ( *Client) ( ...tls.Certificate) *Client {
	 := .GetTLSClientConfig()
	.Certificates = append(.Certificates, ...)
	return 
}

func ( *Client) ( []byte) {
	 := .GetTLSClientConfig()
	if .RootCAs == nil {
		.RootCAs = x509.NewCertPool()
	}
	.RootCAs.AppendCertsFromPEM()
}

// SetRootCertFromString set root certificates from string.
func ( *Client) ( string) *Client {
	.appendRootCertData([]byte())
	return 
}

// SetRootCertsFromFile set root certificates from files.
func ( *Client) ( ...string) *Client {
	for ,  := range  {
		,  := os.ReadFile()
		if  != nil {
			.log.Errorf("failed to read root cert file: %v", )
			return 
		}
		.appendRootCertData()
	}
	return 
}

// GetTLSClientConfig return the underlying tls.Config.
func ( *Client) () *tls.Config {
	if .TLSClientConfig == nil {
		.TLSClientConfig = &tls.Config{
			NextProtos: []string{"h2", "http/1.1"},
		}
	}
	return .TLSClientConfig
}

// 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) ( ...RedirectPolicy) *Client {
	if len() == 0 {
		return 
	}
	.httpClient.CheckRedirect = func( *http.Request,  []*http.Request) error {
		for ,  := range  {
			if  == nil {
				continue
			}
			 := (, )
			if  != nil {
				return 
			}
		}
		if .DebugLog {
			.log.Debugf("<redirect> %s %s", .Method, .URL.String())
		}
		return nil
	}
	return 
}

// 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) () *Client {
	.Transport.DisableKeepAlives = true
	return 
}

// EnableKeepAlives enables HTTP keep-alives (enabled by default).
func ( *Client) () *Client {
	.Transport.DisableKeepAlives = false
	return 
}

// 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) () *Client {
	.Transport.DisableCompression = true
	return 
}

// EnableCompression enables the compression (enabled by default).
func ( *Client) () *Client {
	.Transport.DisableCompression = false
	return 
}

// EnableAutoDecompress enables the automatic decompression (disabled by default).
func ( *Client) () *Client {
	.Transport.AutoDecompression = true
	return 
}

// DisableAutoDecompress disables the automatic decompression (disabled by default).
func ( *Client) () *Client {
	.Transport.AutoDecompression = false
	return 
}

// 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) ( *tls.Config) *Client {
	.TLSClientConfig = 
	return 
}

// EnableInsecureSkipVerify enable send https without verifying
// the server's certificates (disabled by default).
func ( *Client) () *Client {
	.GetTLSClientConfig().InsecureSkipVerify = true
	return 
}

// DisableInsecureSkipVerify disable send https without verifying
// the server's certificates (disabled by default).
func ( *Client) () *Client {
	.GetTLSClientConfig().InsecureSkipVerify = false
	return 
}

// SetCommonQueryParams set URL query parameters with a map
// for requests fired from the client.
func ( *Client) ( map[string]string) *Client {
	for ,  := range  {
		.SetCommonQueryParam(, )
	}
	return 
}

// AddCommonQueryParam add a URL query parameter with a key-value
// pair for requests fired from the client.
func ( *Client) (,  string) *Client {
	if .QueryParams == nil {
		.QueryParams = make(urlpkg.Values)
	}
	.QueryParams.Add(, )
	return 
}

// AddCommonQueryParams add one or more values of specified URL query parameter
// for requests fired from the client.
func ( *Client) ( string,  ...string) *Client {
	if .QueryParams == nil {
		.QueryParams = make(urlpkg.Values)
	}
	 := .QueryParams[]
	 = append(, ...)
	.QueryParams[] = 
	return 
}

func ( *Client) () map[string]string {
	if .PathParams == nil {
		.PathParams = make(map[string]string)
	}
	return .PathParams
}

// SetCommonPathParam set a path parameter for requests fired from the client.
func ( *Client) (,  string) *Client {
	.pathParams()[] = 
	return 
}

// SetCommonPathParams set path parameters for requests fired from the client.
func ( *Client) ( map[string]string) *Client {
	 := .pathParams()
	for ,  := range  {
		[] = 
	}
	return 
}

// SetCommonQueryParam set a URL query parameter with a key-value
// pair for requests fired from the client.
func ( *Client) (,  string) *Client {
	if .QueryParams == nil {
		.QueryParams = make(urlpkg.Values)
	}
	.QueryParams.Set(, )
	return 
}

// SetCommonQueryString set URL query parameters with a raw query string
// for requests fired from the client.
func ( *Client) ( string) *Client {
	,  := urlpkg.ParseQuery(strings.TrimSpace())
	if  != nil {
		.log.Warnf("failed to parse query string (%s): %v", , )
		return 
	}
	if .QueryParams == nil {
		.QueryParams = make(urlpkg.Values)
	}
	for ,  := range  {
		for ,  := range  {
			.QueryParams.Add(, )
		}
	}
	return 
}

// SetCommonQueryParamsFromValues set URL query parameters from a url.Values map
// for requests fired from the client.
func ( *Client) ( urlpkg.Values) *Client {
	if .QueryParams == nil {
		.QueryParams = make(urlpkg.Values)
	}
	for ,  := range  {
		for ,  := range  {
			.QueryParams.Add(, )
		}
	}
	return 
}

// SetCommonQueryParamsFromStruct set URL query parameters from a struct using go-querystring
// for requests fired from the client.
func ( *Client) ( any) *Client {
	,  := query.Values()
	if  != nil {
		.log.Warnf("failed to convert struct to query parameters: %v", )
		return 
	}
	return .SetCommonQueryParamsFromValues()
}

// SetCommonCookies set HTTP cookies for requests fired from the client.
func ( *Client) ( ...*http.Cookie) *Client {
	.Cookies = append(.Cookies, ...)
	return 
}

// DisableDebugLog disable debug level log (disabled by default).
func ( *Client) () *Client {
	.DebugLog = false
	return 
}

// EnableDebugLog enable debug level log (disabled by default).
func ( *Client) () *Client {
	.DebugLog = true
	return 
}

// 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) () *Client {
	return .EnableDumpAll().
		EnableDebugLog().
		EnableTraceAll()
}

// 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) ( string) *Client {
	if !util.IsStringEmpty() {
		.scheme = strings.TrimSpace()
	}
	return 
}

// GetLogger return the internal logger, usually used in middleware.
func ( *Client) () Logger {
	if .log != nil {
		return .log
	}
	.log = createDefaultLogger()
	return .log
}

// SetLogger set the customized logger for client, will disable log if set to nil.
func ( *Client) ( Logger) *Client {
	if  == nil {
		.log = &disableLogger{}
		return 
	}
	.log = 
	return 
}

// SetTimeout set timeout for requests fired from the client.
func ( *Client) ( time.Duration) *Client {
	.httpClient.Timeout = 
	return 
}

func ( *Client) () *DumpOptions {
	if .dumpOptions == nil {
		.dumpOptions = newDefaultDumpOptions()
	}
	return .dumpOptions
}

// EnableDumpAll enable dump for requests fired from the client, including
// all content for the request and response by default.
func ( *Client) () *Client {
	if .Dump != nil { // dump already started
		return 
	}
	.EnableDump(.getDumpOptions())
	return 
}

// EnableDumpAllToFile enable dump for requests fired from the
// client and output to the specified file.
func ( *Client) ( string) *Client {
	,  := os.Create()
	if  != nil {
		.log.Errorf("create dump file error: %v", )
		return 
	}
	.getDumpOptions().Output = 
	.EnableDumpAll()
	return 
}

// EnableDumpAllTo enable dump for requests fired from the
// client and output to the specified io.Writer.
func ( *Client) ( io.Writer) *Client {
	.getDumpOptions().Output = 
	.EnableDumpAll()
	return 
}

// 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) () *Client {
	 := .getDumpOptions()
	.Async = true
	.EnableDumpAll()
	return 
}

// 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) () *Client {
	 := .getDumpOptions()
	.RequestBody = false
	.EnableDumpAll()
	return 
}

// 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) () *Client {
	 := .getDumpOptions()
	.ResponseBody = false
	.EnableDumpAll()
	return 
}

// EnableDumpAllWithoutResponse enable dump for requests fired from
// the client without response, can be used if you only care about
// the request.
func ( *Client) () *Client {
	 := .getDumpOptions()
	.ResponseBody = false
	.ResponseHeader = false
	.EnableDumpAll()
	return 
}

// EnableDumpAllWithoutRequest enables dump for requests fired from
// the client without request, can be used if you only care about
// the response.
func ( *Client) () *Client {
	 := .getDumpOptions()
	.RequestHeader = false
	.RequestBody = false
	.EnableDumpAll()
	return 
}

// EnableDumpAllWithoutHeader enable dump for requests fired from
// the client without header, can be used if you only care about
// the body.
func ( *Client) () *Client {
	 := .getDumpOptions()
	.RequestHeader = false
	.ResponseHeader = false
	.EnableDumpAll()
	return 
}

// EnableDumpAllWithoutBody enable dump for requests fired from
// the client without body, can be used if you only care about
// the header.
func ( *Client) () *Client {
	 := .getDumpOptions()
	.RequestBody = false
	.ResponseBody = false
	.EnableDumpAll()
	return 
}

// 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) () *Client {
	return .OnBeforeRequest(func( *Client,  *Request) error {
		if .RetryAttempt == 0 { // Ignore on retry, no need to repeat enable dump.
			.EnableDump()
		}
		return nil
	})
}

// 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) () *Client {
	return .OnBeforeRequest(func( *Client,  *Request) error {
		if .RetryAttempt == 0 { // Ignore on retry, no need to repeat enable dump.
			.EnableDumpWithoutBody()
		}
		return nil
	})
}

// 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) () *Client {
	return .OnBeforeRequest(func( *Client,  *Request) error {
		if .RetryAttempt == 0 { // Ignore on retry, no need to repeat enable dump.
			.EnableDumpWithoutHeader()
		}
		return nil
	})
}

// 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) () *Client {
	return .OnBeforeRequest(func( *Client,  *Request) error {
		if .RetryAttempt == 0 { // Ignore on retry, no need to repeat enable dump.
			.EnableDumpWithoutRequest()
		}
		return nil
	})
}

// 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) () *Client {
	return .OnBeforeRequest(func( *Client,  *Request) error {
		if .RetryAttempt == 0 { // Ignore on retry, no need to repeat enable dump.
			.EnableDumpWithoutResponse()
		}
		return nil
	})
}

// 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) () *Client {
	return .OnBeforeRequest(func( *Client,  *Request) error {
		if .RetryAttempt == 0 { // Ignore on retry, no need to repeat enable dump.
			.EnableDumpWithoutResponseBody()
		}
		return nil
	})
}

// 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) () *Client {
	return .OnBeforeRequest(func( *Client,  *Request) error {
		if .RetryAttempt == 0 { // Ignore on retry, no need to repeat enable dump.
			.EnableDumpWithoutRequestBody()
		}
		return nil
	})
}

// NewRequest is the alias of R()
func ( *Client) () *Request {
	return .R()
}

func ( *Client) ( string) *ParallelDownload {
	return &ParallelDownload{
		url:    ,
		client: ,
	}
}

// DisableAutoReadResponse disable read response body automatically (enabled by default).
func ( *Client) () *Client {
	.disableAutoReadResponse = true
	return 
}

// EnableAutoReadResponse enable read response body automatically (enabled by default).
func ( *Client) () *Client {
	.disableAutoReadResponse = false
	return 
}

// SetMaxResponseSize sets the maximum allowed size of a response body in bytes.
//
// Enforcement:
//   - When Response.ContentLength is known and greater than the limit, the body
//     is closed without reading and a ResponseBodyTooLargeError is returned.
//     Closing early may prevent connection reuse for that request.
//   - Otherwise the body is wrapped so application reads stop at the limit.
//   - HEAD requests never fail the Content-Length early check (there is no body).
//
// The limit is applied to bytes delivered to the application after the transport
// has handled Content-Encoding (e.g. gzip decompression). For auto-decompressed
// responses ContentLength is typically -1, so only the streaming limit applies.
// Charset auto-decode, if enabled, also runs underneath the limit.
//
// A value of 0 or less disables the limit (default). This is useful for bounding
// memory use and network bandwidth when talking to untrusted or unexpectedly
// large endpoints.
func ( *Client) ( int64) *Client {
	if  < 0 {
		 = 0
	}
	.maxResponseSize = 
	return 
}

// SetAutoDecodeContentType set the content types that will be auto-detected and decode to utf-8
// (e.g. "json", "xml", "html", "text").
func ( *Client) ( ...string) *Client {
	.Transport.SetAutoDecodeContentType(...)
	return 
}

// SetAutoDecodeContentTypeFunc set the function that determines whether the specified `Content-Type` should be auto-detected and decode to utf-8.
func ( *Client) ( func( string) bool) *Client {
	.Transport.SetAutoDecodeContentTypeFunc()
	return 
}

// SetAutoDecodeAllContentType enable try auto-detect charset and decode all content type to utf-8.
func ( *Client) () *Client {
	.Transport.SetAutoDecodeAllContentType()
	return 
}

// DisableAutoDecode disable auto-detect charset and decode to utf-8 (enabled by default).
func ( *Client) () *Client {
	.Transport.DisableAutoDecode()
	return 
}

// EnableAutoDecode enable auto-detect charset and decode to utf-8 (enabled by default).
func ( *Client) () *Client {
	.Transport.EnableAutoDecode()
	return 
}

// SetUserAgent set the "User-Agent" header for requests fired from the client.
func ( *Client) ( string) *Client {
	return .SetCommonHeader(header.UserAgent, )
}

// SetCommonBearerAuthToken set the bearer auth token for requests fired from the client.
func ( *Client) ( string) *Client {
	return .SetCommonHeader(header.Authorization, "Bearer "+)
}

// SetCommonBasicAuth set the basic auth for requests fired from
// the client.
func ( *Client) (,  string) *Client {
	.SetCommonHeader(header.Authorization, util.BasicAuthHeaderValue(, ))
	return 
}

// 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) (,  string) *Client {
	.digestAuth = &digestAuth{
		Username:   ,
		Password:   ,
		HttpClient: .httpClient,
		cache:      make(map[string]*cchal),
	}
	.Transport.WrapRoundTripFunc(.digestAuth.HttpRoundTripWrapperFunc)
	return 
}

// SetCommonHeaders set headers for requests fired from the client.
func ( *Client) ( map[string]string) *Client {
	for ,  := range  {
		.SetCommonHeader(, )
	}
	return 
}

// SetCommonHeader set a header for requests fired from the client.
func ( *Client) (,  string) *Client {
	if .Headers == nil {
		.Headers = make(http.Header)
	}
	.Headers.Set(, )
	return 
}

// 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) (,  string) *Client {
	if .Headers == nil {
		.Headers = make(http.Header)
	}
	.Headers[] = append(.Headers[], )
	return 
}

// 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) ( map[string]string) *Client {
	for ,  := range  {
		.SetCommonHeaderNonCanonical(, )
	}
	return 
}

// 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) ( ...string) *Client {
	.Transport.WrapRoundTripFunc(func( http.RoundTripper) HttpRoundTripFunc {
		return func( *http.Request) ( *http.Response,  error) {
			if .Header == nil {
				.Header = make(http.Header)
			}
			.Header[HeaderOderKey] = 
			return .RoundTrip()
		}
	})
	return 
}

// 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) ( ...string) *Client {
	.Transport.WrapRoundTripFunc(func( http.RoundTripper) HttpRoundTripFunc {
		return func( *http.Request) ( *http.Response,  error) {
			if .Header == nil {
				.Header = make(http.Header)
			}
			.Header[PseudoHeaderOderKey] = 
			return .RoundTrip()
		}
	})
	return 
}

// SetHTTP2SettingsFrame set the ordered http2 settings frame.
func ( *Client) ( ...http2.Setting) *Client {
	.Transport.SetHTTP2SettingsFrame(...)
	return 
}

// SetHTTP2ConnectionFlow set the default http2 connection flow, which is the increment
// value of initial WINDOW_UPDATE frame.
func ( *Client) ( uint32) *Client {
	.Transport.SetHTTP2ConnectionFlow()
	return 
}

// SetHTTP2HeaderPriority set the header priority param.
func ( *Client) ( http2.PriorityParam) *Client {
	.Transport.SetHTTP2HeaderPriority()
	return 
}

// SetHTTP2PriorityFrames set the ordered http2 priority frames.
func ( *Client) ( ...http2.PriorityFrame) *Client {
	.Transport.SetHTTP2PriorityFrames(...)
	return 
}

// SetCommonContentType set the `Content-Type` header for requests fired
// from the client.
func ( *Client) ( string) *Client {
	.SetCommonHeader(header.ContentType, )
	return 
}

// DisableDumpAll disable dump for requests fired from the client.
func ( *Client) () *Client {
	.DisableDump()
	return 
}

// SetCommonDumpOptions configures the underlying Transport's DumpOptions
// for requests fired from the client.
func ( *Client) ( *DumpOptions) *Client {
	if  == nil {
		return 
	}
	if .Output == nil {
		if .dumpOptions != nil {
			.Output = .dumpOptions.Output
		} else {
			.Output = os.Stdout
		}
	}
	.dumpOptions = 
	if .Dump != nil {
		.Dump.SetOptions(dumpOptions{})
	}
	return 
}

// SetProxy set the proxy function.
func ( *Client) ( func(*http.Request) (*urlpkg.URL, error)) *Client {
	.Transport.SetProxy()
	return 
}

// 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) ( ErrorHook) *Client {
	.onError = 
	return 
}

// OnBeforeRequest add a request middleware which hooks before request sent.
func ( *Client) ( RequestMiddleware) *Client {
	.udBeforeRequest = append(.udBeforeRequest, )
	return 
}

// OnAfterResponse add a response middleware which hooks after response received.
func ( *Client) ( ResponseMiddleware) *Client {
	.afterResponse = append(.afterResponse, )
	return 
}

// SetProxyURL set proxy from the proxy URL.
func ( *Client) ( string) *Client {
	if  == "" {
		.log.Warnf("ignore empty proxy url in SetProxyURL")
		return 
	}
	,  := urlpkg.Parse()
	if  != nil {
		.log.Errorf("failed to parse proxy url %s: %v", , )
		return 
	}
	 := http.ProxyURL()
	.SetProxy()
	return 
}

// DisableTraceAll disable trace for requests fired from the client.
func ( *Client) () *Client {
	.trace = false
	return 
}

// EnableTraceAll enable trace for requests fired from the client (http3
// currently does not support trace).
func ( *Client) () *Client {
	.trace = true
	return 
}

// 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) ( http.CookieJar) *Client {
	.cookiejarFactory = nil
	.httpClient.Jar = 
	return 
}

// GetCookies get cookies from the underlying `http.Client`'s `CookieJar`.
func ( *Client) ( string) ([]*http.Cookie, error) {
	if .httpClient.Jar == nil {
		return nil, errors.New("cookie jar is not enabled")
	}
	,  := urlpkg.Parse()
	if  != nil {
		return nil, 
	}
	return .httpClient.Jar.Cookies(), nil
}

// 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) () *Client {
	.initCookieJar()
	.Cookies = nil
	return 
}

// SetJsonMarshal set the JSON marshal function which will be used
// to marshal request body.
func ( *Client) ( func( any) ([]byte, error)) *Client {
	.jsonMarshal = 
	return 
}

// SetJsonUnmarshal set the JSON unmarshal function which will be used
// to unmarshal response body.
func ( *Client) ( func( []byte,  any) error) *Client {
	.jsonUnmarshal = 
	return 
}

// SetXmlMarshal set the XML marshal function which will be used
// to marshal request body.
func ( *Client) ( func( any) ([]byte, error)) *Client {
	.xmlMarshal = 
	return 
}

// SetXmlUnmarshal set the XML unmarshal function which will be used
// to unmarshal response body.
func ( *Client) ( func( []byte,  any) error) *Client {
	.xmlUnmarshal = 
	return 
}

// 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) ( func( context.Context, ,  string) (net.Conn, error)) *Client {
	.Transport.SetDialTLS()
	return 
}

// SetDial set the customized `DialContext` function to Transport.
func ( *Client) ( func( context.Context, ,  string) (net.Conn, error)) *Client {
	.Transport.SetDial()
	return 
}

// SetTLSFingerprintChrome uses tls fingerprint of Chrome browser.
func ( *Client) () *Client {
	return .SetTLSFingerprint(utls.HelloChrome_Auto)
}

// SetTLSFingerprintFirefox uses tls fingerprint of Firefox browser.
func ( *Client) () *Client {
	return .SetTLSFingerprint(utls.HelloFirefox_Auto)
}

// SetTLSFingerprintEdge uses tls fingerprint of Edge browser.
func ( *Client) () *Client {
	return .SetTLSFingerprint(utls.HelloEdge_Auto)
}

// SetTLSFingerprintQQ uses tls fingerprint of QQ browser.
func ( *Client) () *Client {
	return .SetTLSFingerprint(utls.HelloQQ_Auto)
}

// SetTLSFingerprintSafari uses tls fingerprint of Safari browser.
func ( *Client) () *Client {
	return .SetTLSFingerprint(utls.HelloSafari_Auto)
}

// SetTLSFingerprint360 uses tls fingerprint of 360 browser.
func ( *Client) () *Client {
	return .SetTLSFingerprint(utls.Hello360_Auto)
}

// SetTLSFingerprintIOS uses tls fingerprint of IOS.
func ( *Client) () *Client {
	return .SetTLSFingerprint(utls.HelloIOS_Auto)
}

// SetTLSFingerprintAndroid uses tls fingerprint of Android.
func ( *Client) () *Client {
	return .SetTLSFingerprint(utls.HelloAndroid_11_OkHttp)
}

// SetTLSFingerprintRandomized uses randomized tls fingerprint.
func ( *Client) () *Client {
	return .SetTLSFingerprint(utls.HelloRandomized)
}

// uTLSConn is wrapper of UConn which implements the net.Conn interface.
type uTLSConn struct {
	*utls.UConn
}

func ( *uTLSConn) () tls.ConnectionState {
	 := .Conn.ConnectionState()
	return tls.ConnectionState{
		Version:                     .Version,
		HandshakeComplete:           .HandshakeComplete,
		DidResume:                   .DidResume,
		CipherSuite:                 .CipherSuite,
		NegotiatedProtocol:          .NegotiatedProtocol,
		NegotiatedProtocolIsMutual:  .NegotiatedProtocolIsMutual,
		ServerName:                  .ServerName,
		PeerCertificates:            .PeerCertificates,
		VerifiedChains:              .VerifiedChains,
		SignedCertificateTimestamps: .SignedCertificateTimestamps,
		OCSPResponse:                .OCSPResponse,
		TLSUnique:                   .TLSUnique,
	}
}

// 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) ( utls.ClientHelloID) *Client {
	.setTLSFingerprint(, nil)
	return 
}
func ( *Client) ( utls.ClientHelloID,  func(*uTLSConn) error) *Client {
	 := func( context.Context,  string,  net.Conn) ( net.Conn,  *tls.ConnectionState,  error) {
		 := strings.LastIndex(, ":")
		if  == -1 {
			 = len()
		}
		 := [:]
		 := .GetTLSClientConfig()
		 := &utls.Config{
			ServerName:                  ,
			Rand:                        .Rand,
			Time:                        .Time,
			RootCAs:                     .RootCAs,
			NextProtos:                  .NextProtos,
			ClientCAs:                   .ClientCAs,
			InsecureSkipVerify:          .InsecureSkipVerify,
			CipherSuites:                .CipherSuites,
			SessionTicketsDisabled:      .SessionTicketsDisabled,
			MinVersion:                  .MinVersion,
			MaxVersion:                  .MaxVersion,
			DynamicRecordSizingDisabled: .DynamicRecordSizingDisabled,
			KeyLogWriter:                .KeyLogWriter,
		}
		 := &uTLSConn{utls.UClient(, , )}
		if  != nil {
			if  = ();  != nil {
				return
			}
		}
		 = .HandshakeContext()
		if  != nil {
			return
		}
		 := .Conn.ConnectionState()
		 = 
		 = &tls.ConnectionState{
			Version:                     .Version,
			HandshakeComplete:           .HandshakeComplete,
			DidResume:                   .DidResume,
			CipherSuite:                 .CipherSuite,
			NegotiatedProtocol:          .NegotiatedProtocol,
			NegotiatedProtocolIsMutual:  .NegotiatedProtocolIsMutual,
			ServerName:                  .ServerName,
			PeerCertificates:            .PeerCertificates,
			VerifiedChains:              .VerifiedChains,
			SignedCertificateTimestamps: .SignedCertificateTimestamps,
			OCSPResponse:                .OCSPResponse,
			TLSUnique:                   .TLSUnique,
		}
		return
	}
	.Transport.SetTLSHandshake()
	return 
}

// SetTLSFingerprintSpec set the tls fingerprint for tls handshake using a custom
// ClientHelloSpec, which allows fine-grained control over the TLS fingerprint
// (e.g. for JA3/JA4 customization). Uses utls
// (https://github.com/refraction-networking/utls) to perform the tls handshake.
// Note this is valid for HTTP1 and HTTP2, not HTTP3.
func ( *Client) ( func() utls.ClientHelloSpec) *Client {
	.setTLSFingerprint(utls.HelloCustom, func( *uTLSConn) error {
		 := ()
		return .ApplyPreset(&)
	})
	return 
}

// 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) ( func( context.Context,  string,  net.Conn) ( net.Conn,  *tls.ConnectionState,  error)) *Client {
	.Transport.SetTLSHandshake()
	return 
}

// SetTLSHandshakeTimeout set the TLS handshake timeout.
func ( *Client) ( time.Duration) *Client {
	.Transport.SetTLSHandshakeTimeout()
	return 
}

// 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) () *Client {
	.Transport.EnableForceHTTP1()
	return 
}

// 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) () *Client {
	.Transport.EnableForceHTTP2()
	return 
}

// 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) () *Client {
	.Transport.EnableForceHTTP3()
	return 
}

// DisableForceHttpVersion disable force using specified http
// version (disabled by default).
func ( *Client) () *Client {
	.Transport.DisableForceHttpVersion()
	return 
}

// EnableH2C enables HTTP/2 over TCP without TLS.
func ( *Client) () *Client {
	.Transport.EnableH2C()
	return 
}

// DisableH2C disables HTTP/2 over TCP without TLS.
func ( *Client) () *Client {
	.Transport.DisableH2C()
	return 
}

// DisableAllowGetMethodPayload disable sending GET method requests with body.
func ( *Client) () *Client {
	.AllowGetMethodPayload = false
	return 
}

// EnableAllowGetMethodPayload allows sending GET method requests with body.
func ( *Client) () *Client {
	.AllowGetMethodPayload = true
	return 
}

func ( *Client) ( string) bool {
	return ( == http.MethodGet && !.AllowGetMethodPayload) ||  == http.MethodHead ||  == http.MethodOptions
}

// GetClient returns the underlying `http.Client`.
func ( *Client) () *http.Client {
	return .httpClient
}

func ( *Client) () *RetryOption {
	if .retryOption == nil {
		.retryOption = newDefaultRetryOption()
	}
	return .retryOption
}

// 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) ( int) *Client {
	.getRetryOption().MaxRetries = 
	return 
}

// 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) ( GetRetryIntervalFunc) *Client {
	.getRetryOption().GetRetryInterval = 
	return 
}

// SetCommonRetryFixedInterval set retry to use a fixed interval for requests
// fired from the client.
func ( *Client) ( time.Duration) *Client {
	.getRetryOption().GetRetryInterval = func( *Response,  int) time.Duration {
		return 
	}
	return 
}

// 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) (,  time.Duration) *Client {
	.getRetryOption().GetRetryInterval = backoffInterval(, )
	return 
}

// 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) ( RetryHookFunc) *Client {
	.getRetryOption().RetryHooks = []RetryHookFunc{}
	return 
}

// AddCommonRetryHook adds a retry hook for requests fired from the client,
// which will be executed before a retry.
func ( *Client) ( RetryHookFunc) *Client {
	 := .getRetryOption()
	.RetryHooks = append(.RetryHooks, )
	return 
}

// 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) ( RetryConditionFunc) *Client {
	.getRetryOption().RetryConditions = []RetryConditionFunc{}
	return 
}

// AddCommonRetryCondition adds a retry condition, which determines whether the
// request should retry.
func ( *Client) ( RetryConditionFunc) *Client {
	 := .getRetryOption()
	.RetryConditions = append(.RetryConditions, )
	return 
}

// SetUnixSocket set client to dial connection use unix socket.
// For example:
//
// client.SetUnixSocket("/var/run/custom.sock")
func ( *Client) ( string) *Client {
	return .SetDial(func( context.Context, ,  string) (net.Conn, error) {
		var  net.Dialer
		return .DialContext(, "unix", )
	})
}

// SetResolver sets a custom DNS resolver used when dialing HTTP/1 and HTTP/2
// connections. It is implemented via SetDial and a net.Dialer that uses r.
// If r is nil, the default resolver is used.
//
// Only valid for HTTP/1 and HTTP/2 (same limitation as SetDial). Calling
// SetDial, SetHosts, or SetUnixSocket replaces this dialer.
//
// For example, use a specific DNS server:
//
//	r := &net.Resolver{
//		PreferGo: true,
//		Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
//			var d net.Dialer
//			return d.DialContext(ctx, "udp", "1.1.1.1:53")
//		},
//	}
//	client.SetResolver(r)
func ( *Client) ( *net.Resolver) *Client {
	return .SetDial(func( context.Context, ,  string) (net.Conn, error) {
		 := net.Dialer{Resolver: }
		return .DialContext(, , )
	})
}

// SetHosts configures a static hostname-to-IP mapping used when dialing HTTP/1
// and HTTP/2 connections (like a hosts file). Hostnames not present in the map
// fail immediately with a "no such host" DNS error and do not consult the
// system resolver. This avoids long DNS timeouts when maintaining a custom
// host list (e.g. crawlers).
//
// Notes:
//   - Keys are hostnames only (no port). Matching is case-insensitive and
//     IDNA-normalized to match the dial address form used by the transport.
//   - Values must be literal IP addresses (IPv4 or IPv6). Optional surrounding
//     brackets on IPv6 (e.g. "[::1]") are accepted and normalized. Non-IP
//     values never fall through to system DNS; dialing that host returns a
//     clear error instead.
//   - IP-literal request addresses (e.g. https://1.2.3.4/) skip the map and
//     dial directly. Scoped IPv6 literals (e.g. https://[fe80::1%25eth0]/)
//     are supported.
//   - An empty or nil map makes every non-literal hostname fail closed.
//   - Proxy routing is rejected while SetHosts is active because a proxy can
//     resolve the destination remotely and bypass the static mapping.
//   - Only valid for HTTP/1 and HTTP/2 (same limitation as SetDial). SetDialTLS
//     still bypasses this dialer for HTTPS when set. Calling SetDial,
//     SetResolver, or SetUnixSocket replaces this dialer.
//   - The map is copied; later changes to the caller's map are ignored.
//
// For example:
//
//	client.SetHosts(map[string]string{
//		"api.internal": "10.0.0.5",
//		"db.internal":  "10.0.0.6",
//		"v6.internal":  "::1",
//	})
func ( *Client) ( map[string]string) *Client {
	 := make(map[string]string, len())
	 := make(map[string]string)
	for ,  := range  {
		 := hostsMapKey()
		if  == "" {
			continue
		}
		 := net.ParseIP(strings.Trim(, "[]"))
		if  == nil {
			[] = 
			continue
		}
		[] = .String()
	}
	.SetDial(func( context.Context, ,  string) (net.Conn, error) {
		, ,  := net.SplitHostPort()
		if  != nil {
			return nil, 
		}
		// IP literals need no DNS and are not subject to the hosts map.
		if ,  := netip.ParseAddr();  == nil {
			var  net.Dialer
			return .DialContext(, , )
		}
		 := hostsMapKey()
		if ,  := [];  {
			return nil, fmt.Errorf("req: SetHosts: invalid IP address %q for host %q", , )
		}
		,  := []
		if ! {
			return nil, &net.DNSError{
				Err:        "no such host",
				Name:       ,
				IsNotFound: true,
			}
		}
		var  net.Dialer
		return .DialContext(, , net.JoinHostPort(, ))
	})
	.Transport.rejectProxyWithSetHosts = true
	return 
}

// hostsMapKey normalizes a hostname for SetHosts lookup: trim, IDNA ToASCII,
// then lowercase so keys match dial addresses produced by the transport.
func hostsMapKey( string) string {
	 = strings.TrimSpace()
	if  == "" {
		return ""
	}
	if ,  := idnaASCII();  == nil {
		 = 
	}
	return strings.ToLower()
}

// DisableHTTP3 disables the http3 protocol.
func ( *Client) () *Client {
	.Transport.DisableHTTP3()
	return 
}

// EnableHTTP3 enables the http3 protocol.
func ( *Client) () *Client {
	.Transport.EnableHTTP3()
	return 
}

// 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) ( uint32) *Client {
	.Transport.SetHTTP2MaxHeaderListSize()
	return 
}

// 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) ( bool) *Client {
	.Transport.SetHTTP2StrictMaxConcurrentStreams()
	return 
}

// 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) ( time.Duration) *Client {
	.Transport.SetHTTP2ReadIdleTimeout()
	return 
}

// 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) ( time.Duration) *Client {
	.Transport.SetHTTP2PingTimeout()
	return 
}

// 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) ( time.Duration) *Client {
	.Transport.SetHTTP2WriteByteTimeout()
	return 
}

// 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) ( *http.Request) (*http.Response, error) {
	return .httpClient.Do()
}

// NewClient is the alias of C
func () *Client {
	return C()
}

// Clone copy and returns the Client
func ( *Client) () *Client {
	 := *

	// clone Transport
	.Transport = .Transport.Clone()
	.initTransport()

	// clone http.Client
	 := *.httpClient
	.Transport = .Transport
	.httpClient = &
	.initCookieJar()

	// clone client middleware
	if len(.roundTripWrappers) > 0 {
		.wrappedRoundTrip = roundTripImpl{&}
		for ,  := range .roundTripWrappers {
			.wrappedRoundTrip = (.wrappedRoundTrip)
		}
	}

	// clone other fields that may need to be cloned
	.PathParams = cloneMap(.PathParams)
	.QueryParams = cloneUrlValues(.QueryParams)
	.FormData = cloneUrlValues(.FormData)
	.beforeRequest = cloneSlice(.beforeRequest)
	.udBeforeRequest = cloneSlice(.udBeforeRequest)
	.afterResponse = cloneSlice(.afterResponse)
	.dumpOptions = .dumpOptions.Clone()
	.retryOption = .retryOption.Clone()
	return &
}

func memoryCookieJarFactory() http.CookieJar {
	,  := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
	return 
}

// C create a new client.
func () *Client {
	 := T()

	 := &http.Client{
		Transport: ,
		Timeout:   2 * time.Minute,
	}
	 := []RequestMiddleware{
		parseRequestHeader,
		parseRequestCookie,
		parseRequestURL,
		parseRequestBody,
	}
	 := []ResponseMiddleware{
		parseResponseBody,
		handleDownload,
	}
	 := &Client{
		AllowGetMethodPayload: true,
		beforeRequest:         ,
		afterResponse:         ,
		log:                   createDefaultLogger(),
		httpClient:            ,
		Transport:             ,
		jsonMarshal:           json.Marshal,
		jsonUnmarshal:         json.Unmarshal,
		xmlMarshal:            xml.Marshal,
		xmlUnmarshal:          xml.Unmarshal,
		cookiejarFactory:      memoryCookieJarFactory,
	}
	.SetRedirectPolicy(DefaultRedirectPolicy())
	.initCookieJar()

	.initTransport()
	return 
}

// 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) ( func() http.CookieJar) *Client {
	.cookiejarFactory = 
	.initCookieJar()
	return 
}

func ( *Client) () {
	if .cookiejarFactory == nil {
		return
	}
	 := .cookiejarFactory()
	if  != nil {
		.httpClient.Jar = 
	}
}

func ( *Client) () {
	.Debugf = func( string,  ...any) {
		if .DebugLog {
			.log.Debugf(, ...)
		}
	}
}

// RoundTripper is the interface of req's Client.
type RoundTripper interface {
	RoundTrip(*Request) (*Response, error)
}

// RoundTripFunc is a RoundTripper implementation, which is a simple function.
type RoundTripFunc func(req *Request) (resp *Response, err error)

// RoundTrip implements RoundTripper.
func ( RoundTripFunc) ( *Request) (*Response, error) {
	return ()
}

// RoundTripWrapper is client middleware function.
type RoundTripWrapper func(rt RoundTripper) RoundTripper

// RoundTripWrapperFunc is client middleware function, more convenient than RoundTripWrapper.
type RoundTripWrapperFunc func(rt RoundTripper) RoundTripFunc

func ( RoundTripWrapperFunc) () RoundTripWrapper {
	return func( RoundTripper) RoundTripper {
		return ()
	}
}

// WrapRoundTripFunc adds a client middleware function that will give the caller
// an opportunity to wrap the underlying http.RoundTripper.
func ( *Client) ( ...RoundTripWrapperFunc) *Client {
	var  []RoundTripWrapper
	for ,  := range  {
		 = append(, .wrapper())
	}
	return .WrapRoundTrip(...)
}

type roundTripImpl struct {
	*Client
}

func ( roundTripImpl) ( *Request) ( *Response,  error) {
	return .roundTrip()
}

// WrapRoundTrip adds a client middleware function that will give the caller
// an opportunity to wrap the underlying http.RoundTripper.
func ( *Client) ( ...RoundTripWrapper) *Client {
	if len() == 0 {
		return 
	}
	if .wrappedRoundTrip == nil {
		.roundTripWrappers = 
		.wrappedRoundTrip = roundTripImpl{}
	} else {
		.roundTripWrappers = append(.roundTripWrappers, ...)
	}
	for ,  := range  {
		.wrappedRoundTrip = (.wrappedRoundTrip)
	}
	return 
}

// RoundTrip implements RoundTripper
func ( *Client) ( *Request) ( *Response,  error) {
	 = &Response{Request: }
	defer func() {
		if  != nil {
			.Err = 
		} else {
			 = .Err
		}
	}()

	// setup trace
	if .trace == nil && .client.trace {
		.trace = &clientTrace{}
	}

	 := .ctx

	if .trace != nil {
		 = .trace.createContext(.Context())
	}

	// setup url and host
	var  string
	if  := .getHeader("Host");  != "" {
		 =  // Host header override
	} else {
		 = .URL.Host
	}

	// setup header
	 := int64(len(.Body))
	if .contentLength != 0 {
		 = .contentLength
	}

	var  io.ReadCloser
	if .GetBody != nil {
		, .Err = .GetBody()
		if .Err != nil {
			return
		}
	}
	 := .GetBody
	if .unReplayableBody != nil {
		 = nil
	}
	 := &http.Request{
		Method:        .Method,
		Header:        .Headers.Clone(),
		URL:           .URL,
		Host:          ,
		Proto:         "HTTP/1.1",
		ProtoMajor:    1,
		ProtoMinor:    1,
		ContentLength: ,
		Body:          ,
		GetBody:       ,
		Close:         .close,
	}
	for ,  := range .Cookies {
		.AddCookie()
	}
	if .isSaveResponse && .downloadCallback != nil {
		var  wrapResponseBodyFunc = func( io.ReadCloser) io.ReadCloser {
			return &callbackReader{
				ReadCloser: ,
				callback: func( int64) {
					.downloadCallback(DownloadInfo{
						Response:       ,
						DownloadedSize: ,
					})
				},
				lastTime: time.Now(),
				interval: .downloadCallbackInterval,
			}
		}
		if  == nil {
			 = context.Background()
		}
		 = context.WithValue(, wrapResponseBodyKey, )
	}
	if  != nil {
		 = .WithContext()
	}
	.RawRequest = 
	.StartTime = time.Now()

	var  *http.Response
	, .Err = .httpClient.Do(.RawRequest)
	.Response = 

	// Enforce response body size limit before any body consumption.
	if .Err == nil {
		if  := applyMaxResponseSize(, );  != nil {
			.Err = 
		}
	}

	// auto-read response body if possible
	if .Err == nil && !.disableAutoReadResponse && !.isSaveResponse && !.disableAutoReadResponse && .StatusCode > 199 {
		.ToBytes()
		// restore body for re-reads
		.Body = io.NopCloser(bytes.NewReader(.body))
	}

	for ,  := range .afterResponse {
		if  := (, );  != nil {
			.Err = 
		}
	}
	return
}

// applyMaxResponseSize rejects oversized responses early when Content-Length is
// known, and otherwise wraps the body so reads stop at the configured limit.
func applyMaxResponseSize( *Request,  *Response) error {
	 := .getMaxResponseSize()
	if  <= 0 || .Response == nil || .Body == nil {
		return nil
	}

	// HEAD keeps Content-Length from the resource header but has no body
	// (see transfer.go). Do not treat that advertised length as a body limit
	// violation — ParallelDownload relies on Head() + ContentLength for sizing.
	if .Method != http.MethodHead {
		// Known Content-Length over the limit: reject without reading the body so
		// bandwidth and memory are not wasted. Early close may prevent keep-alive reuse.
		if  := .ContentLength;  >  {
			_ = .Body.Close()
			.Body = http.NoBody
			return &ResponseBodyTooLargeError{Limit: , ContentLength: }
		}
	}

	.Body = &maxResponseBodyReader{
		r:     .Body,
		n:     ,
		limit: ,
	}
	return nil
}