package req

import (
	
	
	
	
	
	
	urlpkg 
	
	
	
	
	

	
	
	
	
)

// 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.
type Request struct {
	PathParams      map[string]string
	QueryParams     urlpkg.Values
	FormData        urlpkg.Values
	OrderedFormData []string
	Headers         http.Header
	Cookies         []*http.Cookie
	Result          any
	Error           any
	RawRequest      *http.Request
	StartTime       time.Time
	RetryAttempt    int
	RawURL          string // read only
	Method          string
	Body            []byte
	GetBody         GetContentFunc
	contentLength   int64
	// 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

	isMultiPart              bool
	disableAutoReadResponse  bool
	forceChunkedEncoding     bool
	isSaveResponse           bool
	close                    bool
	error                    error
	client                   *Client
	uploadCallback           UploadCallback
	uploadCallbackInterval   time.Duration
	downloadCallback         DownloadCallback
	downloadCallbackInterval time.Duration
	// maxResponseSize, when non-nil, overrides Client.maxResponseSize for this
	// request. A pointed-to value of 0 means no limit for this request.
	maxResponseSize    *int64
	unReplayableBody   io.ReadCloser
	retryOption        *RetryOption
	bodyReadCloser     io.ReadCloser
	dumpOptions        *DumpOptions
	marshalBody        any
	ctx                context.Context
	uploadFiles        []*FileUpload
	uploadReader       []io.ReadCloser
	outputFile         string
	output             io.Writer
	trace              *clientTrace
	dumpBuffer         *bytes.Buffer
	responseReturnTime time.Time
	afterResponse      []ResponseMiddleware
}

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

func ( *Request) ( string) string {
	if .Headers == nil {
		return ""
	}
	return .Headers.Get()
}

// TraceInfo returns the trace information, only available if trace is enabled
// (see Request.EnableTrace and Client.EnableTraceAll).
func ( *Request) () TraceInfo {
	 := .trace

	if  == nil {
		return TraceInfo{}
	}

	 := TraceInfo{
		IsConnReused:  .gotConnInfo.Reused,
		IsConnWasIdle: .gotConnInfo.WasIdle,
		ConnIdleTime:  .gotConnInfo.IdleTime,
	}

	 := .endTime
	if .IsZero() { // in case timeout
		 = .responseReturnTime
	}

	if !.tlsHandshakeStart.IsZero() {
		if !.tlsHandshakeDone.IsZero() {
			.TLSHandshakeTime = .tlsHandshakeDone.Sub(.tlsHandshakeStart)
		} else {
			.TLSHandshakeTime = .Sub(.tlsHandshakeStart)
		}
	}

	if .gotConnInfo.Reused {
		.TotalTime = .Sub(.getConn)
	} else {
		if .dnsStart.IsZero() {
			.TotalTime = .Sub(.StartTime)
		} else {
			.TotalTime = .Sub(.dnsStart)
		}
	}

	 := .dnsDone
	if .IsZero() {
		 = 
	}

	if !.dnsStart.IsZero() {
		.DNSLookupTime = .Sub(.dnsStart)
	}

	// Only calculate on successful connections
	if !.connectDone.IsZero() {
		.TCPConnectTime = .connectDone.Sub()
	}

	// Only calculate on successful connections
	if !.gotConn.IsZero() {
		.ConnectTime = .gotConn.Sub(.getConn)
	}

	// Only calculate on successful connections
	if !.gotFirstResponseByte.IsZero() {
		.FirstResponseTime = .gotFirstResponseByte.Sub(.gotConn)
		.ResponseTime = .Sub(.gotFirstResponseByte)
	}

	// Capture remote address info when connection is non-nil
	if .gotConnInfo.Conn != nil {
		.RemoteAddr = .gotConnInfo.Conn.RemoteAddr()
		.LocalAddr = .gotConnInfo.Conn.LocalAddr()
	}

	return 
}

// HeaderToString get all header as string.
func ( *Request) () string {
	return convertHeaderToString(.Headers)
}

// SetURL set the url for request.
func ( *Request) ( string) *Request {
	.RawURL = 
	return 
}

// SetFormDataFromValues set the form data from url.Values, will not
// been used if request method does not allow payload.
func ( *Request) ( urlpkg.Values) *Request {
	if .FormData == nil {
		.FormData = urlpkg.Values{}
	}
	for ,  := range  {
		for ,  := range  {
			.FormData.Add(, )
		}
	}
	return 
}

// SetFormData set the form data from a map, will not been used
// if request method does not allow payload.
func ( *Request) ( map[string]string) *Request {
	if .FormData == nil {
		.FormData = urlpkg.Values{}
	}
	for ,  := range  {
		.FormData.Set(, )
	}
	return 
}

// SetOrderedFormData set the ordered form data from key-values pairs.
func ( *Request) ( ...string) *Request {
	.OrderedFormData = append(.OrderedFormData, ...)
	return 
}

// 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) ( map[string]any) *Request {
	if .FormData == nil {
		.FormData = urlpkg.Values{}
	}
	for ,  := range  {
		.FormData.Set(, fmt.Sprint())
	}
	return 
}

// SetCookies set http cookies for the request.
func ( *Request) ( ...*http.Cookie) *Request {
	.Cookies = append(.Cookies, ...)
	return 
}

// SetQueryString set URL query parameters for the request using
// raw query string.
func ( *Request) ( string) *Request {
	,  := urlpkg.ParseQuery(strings.TrimSpace())
	if  != nil {
		.client.log.Warnf("failed to parse query string (%s): %v", , )
		return 
	}
	if .QueryParams == nil {
		.QueryParams = make(urlpkg.Values)
	}
	for ,  := range  {
		for ,  := range  {
			.QueryParams.Add(, )
		}
	}
	return 
}

// SetQueryParamsFromValues sets query parameters from a url.Values map.
// This method allows direct configuration of query parameters from url.Values,
// which is commonly used with libraries like go-querystring.
func ( *Request) ( urlpkg.Values) *Request {
	if .QueryParams == nil {
		.QueryParams = make(urlpkg.Values)
	}
	for ,  := range  {
		for ,  := range  {
			.QueryParams.Add(, )
		}
	}
	return 
}

// SetQueryParamsFromStruct sets query parameters from a struct using go-querystring.
// This method provides a higher-level abstraction by allowing users to directly pass
// a struct to configure query parameters. The struct should use `url` tags to specify
// parameter names.
func ( *Request) ( any) *Request {
	,  := query.Values()
	if  != nil {
		.client.log.Warnf("failed to convert struct to query parameters: %v", )
		return 
	}
	return .SetQueryParamsFromValues()
}

// SetFileReader set up a multipart form with a reader to upload file.
func ( *Request) (,  string,  io.Reader) *Request {
	if ,  := .(io.ReadCloser);  {
		.unReplayableBody = 
	} else {
		.unReplayableBody = io.NopCloser()
	}
	.SetFileUpload(FileUpload{
		ParamName: ,
		FileName:  ,
		GetFileContent: func() (io.ReadCloser, error) {
			return .unReplayableBody, nil
		},
	})
	return 
}

// SetFileBytes set up a multipart form with given []byte to upload.
func ( *Request) (,  string,  []byte) *Request {
	.SetFileUpload(FileUpload{
		ParamName:   ,
		FileName:    ,
		FileSize:    int64(len()),
		ContentType: http.DetectContentType(),
		GetFileContent: func() (io.ReadCloser, error) {
			return io.NopCloser(bytes.NewReader()), nil
		},
	})
	return 
}

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

// SetFile set up a multipart form from file path to upload,
// which read file from filePath automatically to upload.
func ( *Request) (,  string) *Request {
	,  := os.Open()
	if  != nil {
		.client.log.Errorf("failed to open %s: %v", , )
		.appendError()
		return 
	}
	,  := os.Stat()
	if  != nil {
		.Close()
		.client.log.Errorf("failed to stat file %s: %v", , )
		.appendError()
		return 
	}
	 := make([]byte, 512)
	,  := .Read()
	.Close()
	if  != nil &&  != io.EOF {
		.client.log.Errorf("failed to read %s: %v", , )
		.appendError()
		return 
	}
	.isMultiPart = true
	return .SetFileUpload(FileUpload{
		ParamName: ,
		FileName:  filepath.Base(),
		GetFileContent: func() (io.ReadCloser, error) {
			return os.Open()
		},
		FileSize:    .Size(),
		ContentType: http.DetectContentType([:]),
	})
}

var (
	errMissingParamName   = errors.New("missing param name in multipart file upload")
	errMissingFileName    = errors.New("missing filename in multipart file upload")
	errMissingFileContent = errors.New("missing file content in multipart file upload")
)

// SetFileUpload set the fully customized multipart file upload options.
func ( *Request) ( ...FileUpload) *Request {
	.isMultiPart = true
	for ,  := range  {
		 := true
		if .ParamName == "" {
			.appendError(errMissingParamName)
			 = false
		}
		if .FileName == "" {
			.appendError(errMissingFileName)
			 = false
		}
		if .GetFileContent == nil {
			.appendError(errMissingFileContent)
			 = false
		}
		if  {
			.uploadFiles = append(.uploadFiles, &)
		}
	}
	return 
}

// SetUploadCallback set the UploadCallback which will be invoked at least
// every 200ms during file upload, usually used to show upload progress.
func ( *Request) ( UploadCallback) *Request {
	return .SetUploadCallbackWithInterval(, 200*time.Millisecond)
}

// SetUploadCallbackWithInterval set the UploadCallback which will be invoked at least
// every `minInterval` during file upload, usually used to show upload progress.
func ( *Request) ( UploadCallback,  time.Duration) *Request {
	if  == nil {
		return 
	}
	.forceChunkedEncoding = true
	.uploadCallback = 
	.uploadCallbackInterval = 
	return 
}

// SetDownloadCallback set the DownloadCallback which will be invoked at least
// every 200ms during file upload, usually used to show download progress.
func ( *Request) ( DownloadCallback) *Request {
	return .SetDownloadCallbackWithInterval(, 200*time.Millisecond)
}

// SetDownloadCallbackWithInterval set the DownloadCallback which will be invoked at least
// every `minInterval` during file upload, usually used to show download progress.
func ( *Request) ( DownloadCallback,  time.Duration) *Request {
	if  == nil {
		return 
	}
	.downloadCallback = 
	.downloadCallbackInterval = 
	return 
}

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

// 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) ( any) *Request {
	if  == nil {
		return 
	}
	.Result = util.GetPointer()
	return 
}

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

// 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) ( any) *Request {
	if  == nil {
		return 
	}
	.Error = util.GetPointer()
	return 
}

// SetBearerAuthToken set bearer auth token for the request.
func ( *Request) ( string) *Request {
	return .SetHeader(header.Authorization, "Bearer "+)
}

// SetBasicAuth set basic auth for the request.
func ( *Request) (,  string) *Request {
	return .SetHeader(header.Authorization, util.BasicAuthHeaderValue(, ))
}

// 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) (,  string) *Request {
	.OnAfterResponse(handleDigestAuthFunc(, ))
	return 
}

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

// SetHeaders set headers from a map for the request.
func ( *Request) ( map[string]string) *Request {
	for ,  := range  {
		.SetHeader(, )
	}
	return 
}

// SetHeader set a header for the request.
func ( *Request) (,  string) *Request {
	if .Headers == nil {
		.Headers = make(http.Header)
	}
	.Headers.Set(, )
	return 
}

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

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

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

// SetHeaderOrder set the order of the http header (case-insensitive).
// For example:
//
//	client.R().SetHeaderOrder(
//	    "custom-header",
//	    "cookie",
//	    "user-agent",
//	    "accept-encoding",
//	)
func ( *Request) ( ...string) *Request {
	if .Headers == nil {
		.Headers = make(http.Header)
	}
	.Headers[HeaderOderKey] = append(.Headers[HeaderOderKey], ...)
	return 
}

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

// SetOutputFile set the file that response Body will be downloaded to.
func ( *Request) ( string) *Request {
	.isSaveResponse = true
	.outputFile = 
	return 
}

// SetOutput set the io.Writer that response Body will be downloaded to.
func ( *Request) ( io.Writer) *Request {
	if  == nil {
		.client.log.Warnf("nil io.Writer is not allowed in SetOutput")
		return 
	}
	.output = 
	.isSaveResponse = true
	return 
}

// SetQueryParams set URL query parameters from a map for the request.
func ( *Request) ( map[string]string) *Request {
	for ,  := range  {
		.SetQueryParam(, )
	}
	return 
}

// 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) ( map[string]any) *Request {
	for ,  := range  {
		.SetQueryParam(, fmt.Sprint())
	}
	return 
}

// SetQueryParam set an URL query parameter for the request.
func ( *Request) (,  string) *Request {
	if .QueryParams == nil {
		.QueryParams = make(urlpkg.Values)
	}
	.QueryParams.Set(, )
	return 
}

// AddQueryParam add a URL query parameter for the request.
func ( *Request) (,  string) *Request {
	if .QueryParams == nil {
		.QueryParams = make(urlpkg.Values)
	}
	.QueryParams.Add(, )
	return 
}

// AddQueryParams add one or more values of specified URL query parameter for the request.
func ( *Request) ( string,  ...string) *Request {
	if .QueryParams == nil {
		.QueryParams = make(urlpkg.Values)
	}
	 := .QueryParams[]
	 = append(, ...)
	.QueryParams[] = 
	return 
}

// SetPathParams set URL path parameters from a map for the request.
func ( *Request) ( map[string]string) *Request {
	for ,  := range  {
		.SetPathParam(, )
	}
	return 
}

// SetPathParam set a URL path parameter for the request.
func ( *Request) (,  string) *Request {
	if .PathParams == nil {
		.PathParams = make(map[string]string)
	}
	.PathParams[] = 
	return 
}

func ( *Request) ( error) {
	.error = errors.Join(.error, )
}

var errRetryableWithUnReplayableBody = errors.New("retryable request should not have unreplayable Body (io.Reader)")

func ( *Request) ( error) *Response {
	 := &Response{Request: }
	.Err = 
	return 
}

// 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) ( ...context.Context) *Response {
	if len() > 0 && [0] != nil {
		.ctx = [0]
	}

	defer func() {
		.responseReturnTime = time.Now()
	}()
	if .error != nil {
		return .newErrorResponse(.error)
	}
	if .retryOption != nil && .retryOption.MaxRetries != 0 && .unReplayableBody != nil { // retryable request should not have unreplayable Body
		return .newErrorResponse(errRetryableWithUnReplayableBody)
	}
	,  := .do()
	return 
}

func ( *Request) ( *Response,  error) bool {
	if errors.Is(, context.Canceled) || .retryOption == nil ||
		(.RetryAttempt >= .retryOption.MaxRetries && .retryOption.MaxRetries >= 0) {
		return false
	}
	 :=  != nil
	if  := len(.retryOption.RetryConditions);  > 0 {
		for  :=  - 1;  >= 0; -- {
			 = .retryOption.RetryConditions[](, )
			if  {
				break
			}
		}
	}
	return 
}

func ( *Request) ( *Response,  error) {
	.RetryAttempt++
	if  := len(.retryOption.RetryHooks);  > 0 {
		for  :=  - 1;  >= 0; -- {
			.retryOption.RetryHooks[](, )
		}
	}
	time.Sleep(.retryOption.GetRetryInterval(, .RetryAttempt))

	if .dumpBuffer != nil {
		.dumpBuffer.Reset()
	}
	if .trace != nil {
		.trace = &clientTrace{}
	}
	if  != nil {
		.body = nil
		.result = nil
		.error = nil
	}
}

// tryRetry attempts retry after an error. Returns true if the request loop should continue.
func ( *Request) ( **Response,  error) bool {
	if * == nil {
		* = &Response{Request: }
	}
	if  != nil {
		(*).Err = 
	}
	if !.shouldRetry(*, ) {
		return false
	}
	.prepareRetry(*, )
	return true
}

func ( *Request) () ( *Response,  error) {
	defer func() {
		if  == nil {
			 = &Response{Request: }
		}
		if  != nil && .Err == nil {
			.Err = 
		}
	}()

:
	for {
		if .Headers == nil {
			.Headers = make(http.Header)
		}
		for ,  := range .client.udBeforeRequest {
			if  = (.client, );  != nil {
				if .tryRetry(&, ) {
					continue 
				}
				return
			}
		}
		for ,  := range .client.beforeRequest {
			if  = (.client, );  != nil {
				return
			}
		}

		if .client.wrappedRoundTrip != nil {
			,  = .client.wrappedRoundTrip.RoundTrip()
		} else {
			,  = .client.roundTrip()
		}

		// Determine if the error is from a canceled context.
		// Store it here so it doesn't get lost when processing the AfterResponse middleware.
		 := errors.Is(, context.Canceled)

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

		if  {
			return
		}
		if !.tryRetry(&, ) {
			return
		}
	}
}

// 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) (,  string) (*Response, error) {
	.Method = 
	.RawURL = 
	 := .Do()
	if .Err != nil && .client.onError != nil {
		.client.onError(.client, , , .Err)
	}
	return , .Err
}

// MustGet like Get, panic if error happens, should only be used to
// test without error handling.
func ( *Request) ( string) *Response {
	,  := .Get()
	if  != nil {
		panic()
	}
	return 
}

// Get fires http request with GET method and the specified URL.
func ( *Request) ( string) (*Response, error) {
	return .Send(http.MethodGet, )
}

// MustPost like Post, panic if error happens. should only be used to
// test without error handling.
func ( *Request) ( string) *Response {
	,  := .Post()
	if  != nil {
		panic()
	}
	return 
}

// Post fires http request with POST method and the specified URL.
func ( *Request) ( string) (*Response, error) {
	return .Send(http.MethodPost, )
}

// MustPut like Put, panic if error happens, should only be used to
// test without error handling.
func ( *Request) ( string) *Response {
	,  := .Put()
	if  != nil {
		panic()
	}
	return 
}

// Put fires http request with PUT method and the specified URL.
func ( *Request) ( string) (*Response, error) {
	return .Send(http.MethodPut, )
}

// MustPatch like Patch, panic if error happens, should only be used
// to test without error handling.
func ( *Request) ( string) *Response {
	,  := .Patch()
	if  != nil {
		panic()
	}
	return 
}

// Patch fires http request with PATCH method and the specified URL.
func ( *Request) ( string) (*Response, error) {
	return .Send(http.MethodPatch, )
}

// MustDelete like Delete, panic if error happens, should only be used
// to test without error handling.
func ( *Request) ( string) *Response {
	,  := .Delete()
	if  != nil {
		panic()
	}
	return 
}

// Delete fires http request with DELETE method and the specified URL.
func ( *Request) ( string) (*Response, error) {
	return .Send(http.MethodDelete, )
}

// MustOptions like Options, panic if error happens, should only be
// used to test without error handling.
func ( *Request) ( string) *Response {
	,  := .Options()
	if  != nil {
		panic()
	}
	return 
}

// Options fires http request with OPTIONS method and the specified URL.
func ( *Request) ( string) (*Response, error) {
	return .Send(http.MethodOptions, )
}

// MustHead like Head, panic if error happens, should only be used
// to test without error handling.
func ( *Request) ( string) *Response {
	,  := .Send(http.MethodHead, )
	if  != nil {
		panic()
	}
	return 
}

// Head fires http request with HEAD method and the specified URL.
func ( *Request) ( string) (*Response, error) {
	return .Send(http.MethodHead, )
}

// MustQuery like Query, panic if error happens, should only be used
// to test without error handling.
func ( *Request) ( string) *Response {
	,  := .Query()
	if  != nil {
		panic()
	}
	return 
}

// Query fires http request with QUERY method and the specified URL. QUERY is a
// safe, idempotent method that carries the query as request content, defined in
// RFC 10008.
func ( *Request) ( string) (*Response, error) {
	return .Send("QUERY", )
}

// SetBody set the request Body, accepts string, []byte, io.Reader, map and struct.
func ( *Request) ( any) *Request {
	if  == nil {
		return 
	}
	switch b := .(type) {
	case io.ReadCloser:
		.unReplayableBody = 
		.GetBody = func() (io.ReadCloser, error) {
			return .unReplayableBody, nil
		}
	case io.Reader:
		.unReplayableBody = io.NopCloser()
		.GetBody = func() (io.ReadCloser, error) {
			return .unReplayableBody, nil
		}
	case []byte:
		.SetBodyBytes()
	case string:
		.SetBodyString()
	case func() (io.ReadCloser, error):
		.GetBody = 
	case GetContentFunc:
		.GetBody = 
	default:
		 := reflect.TypeOf()
		switch .Kind() {
		case reflect.Ptr, reflect.Struct, reflect.Map, reflect.Slice, reflect.Array:
			.marshalBody = 
		default:
			.SetBodyString(fmt.Sprint())
		}
	}
	return 
}

// SetBodyBytes set the request Body as []byte.
func ( *Request) ( []byte) *Request {
	.Body = 
	.GetBody = func() (io.ReadCloser, error) {
		return io.NopCloser(bytes.NewReader()), nil
	}
	return 
}

// SetBodyString set the request Body as string.
func ( *Request) ( string) *Request {
	return .SetBodyBytes([]byte())
}

// SetBodyJsonString set the request Body as string and set Content-Type header
// as "application/json; charset=utf-8"
func ( *Request) ( string) *Request {
	return .SetBodyJsonBytes([]byte())
}

// SetBodyJsonBytes set the request Body as []byte and set Content-Type header
// as "application/json; charset=utf-8"
func ( *Request) ( []byte) *Request {
	.SetContentType(header.JsonContentType)
	return .SetBodyBytes()
}

// SetBodyJsonMarshal set the request Body that marshaled from object, and
// set Content-Type header as "application/json; charset=utf-8"
func ( *Request) ( any) *Request {
	,  := .client.jsonMarshal()
	if  != nil {
		.appendError()
		return 
	}
	return .SetBodyJsonBytes()
}

// SetBodyXmlString set the request Body as string and set Content-Type header
// as "text/xml; charset=utf-8"
func ( *Request) ( string) *Request {
	return .SetBodyXmlBytes([]byte())
}

// SetBodyXmlBytes set the request Body as []byte and set Content-Type header
// as "text/xml; charset=utf-8"
func ( *Request) ( []byte) *Request {
	.SetContentType(header.XmlContentType)
	return .SetBodyBytes()
}

// SetBodyXmlMarshal set the request Body that marshaled from object, and
// set Content-Type header as "text/xml; charset=utf-8"
func ( *Request) ( any) *Request {
	,  := .client.xmlMarshal()
	if  != nil {
		.appendError()
		return 
	}
	return .SetBodyXmlBytes()
}

// SetContentType set the `Content-Type` for the request.
func ( *Request) ( string) *Request {
	return .SetHeader(header.ContentType, )
}

// Context method returns the Context if its already set in request
// otherwise it creates new one using `context.Background()`.
func ( *Request) () context.Context {
	if .ctx == nil {
		.ctx = context.Background()
	}
	return .ctx
}

// 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) ( context.Context) *Request {
	if  != nil {
		.ctx = 
	}
	return 
}

// 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) (,  any) *Request {
	.ctx = context.WithValue(.Context(), , )
	return 
}

// GetContextData returns the context data of specified key, which set by SetContextData.
func ( *Request) ( any) any {
	return .Context().Value()
}

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

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

// SetMaxResponseSize sets the maximum allowed size of the response body in bytes
// for this request, overriding Client.SetMaxResponseSize. A value of 0 or less
// disables the limit for this request even if the client has a limit configured.
//
// See Client.SetMaxResponseSize for behavior details.
func ( *Request) ( int64) *Request {
	if  < 0 {
		 = 0
	}
	.maxResponseSize = &
	return 
}

// getMaxResponseSize returns the effective max response body size for this
// request (request override, else client setting). 0 means no limit.
func ( *Request) () int64 {
	if .maxResponseSize != nil {
		return *.maxResponseSize
	}
	if .client != nil {
		return .client.maxResponseSize
	}
	return 0
}

// DisableTrace disables trace.
func ( *Request) () *Request {
	.trace = nil
	return 
}

// EnableTrace enables trace (http3 currently does not support trace).
func ( *Request) () *Request {
	if .trace == nil {
		.trace = &clientTrace{}
	}
	return 
}

func ( *Request) () *bytes.Buffer {
	if .dumpBuffer == nil {
		.dumpBuffer = new(bytes.Buffer)
	}
	return .dumpBuffer
}

func ( *Request) () *DumpOptions {
	if .dumpOptions == nil {
		.dumpOptions = &DumpOptions{
			RequestHeader:  true,
			RequestBody:    true,
			ResponseHeader: true,
			ResponseBody:   true,
			Output:         .getDumpBuffer(),
		}
	}
	return .dumpOptions
}

// EnableDumpTo enables dump and save to the specified io.Writer.
func ( *Request) ( io.Writer) *Request {
	.getDumpOptions().Output = 
	return .EnableDump()
}

// EnableDumpToFile enables dump and save to the specified filename.
func ( *Request) ( string) *Request {
	,  := os.Create()
	if  != nil {
		.appendError()
		return 
	}
	.getDumpOptions().Output = 
	return .EnableDump()
}

// SetDumpOptions sets DumpOptions at request level.
func ( *Request) ( *DumpOptions) *Request {
	if  == nil {
		return 
	}
	if .Output == nil {
		.Output = .getDumpBuffer()
	}
	if .dumpOptions != nil {
		*.dumpOptions = *
	} else {
		.dumpOptions = 
	}
	return 
}

// EnableDump enables dump, including all content for the request and response by default.
func ( *Request) () *Request {
	return .SetContext(context.WithValue(.Context(), dump.DumperKey, newDumper(.getDumpOptions())))
}

// EnableDumpWithoutBody enables dump only header for the request and response.
func ( *Request) () *Request {
	 := .getDumpOptions()
	.RequestBody = false
	.ResponseBody = false
	return .EnableDump()
}

// EnableDumpWithoutHeader enables dump only Body for the request and response.
func ( *Request) () *Request {
	 := .getDumpOptions()
	.RequestHeader = false
	.ResponseHeader = false
	return .EnableDump()
}

// EnableDumpWithoutResponse enables dump only request.
func ( *Request) () *Request {
	 := .getDumpOptions()
	.ResponseHeader = false
	.ResponseBody = false
	return .EnableDump()
}

// EnableDumpWithoutRequest enables dump only response.
func ( *Request) () *Request {
	 := .getDumpOptions()
	.RequestHeader = false
	.RequestBody = false
	return .EnableDump()
}

// EnableDumpWithoutRequestBody enables dump with request Body excluded,
// can be used in upload request to avoid dump the unreadable binary content.
func ( *Request) () *Request {
	 := .getDumpOptions()
	.RequestBody = false
	return .EnableDump()
}

// EnableDumpWithoutResponseBody enables dump with response Body excluded,
// can be used in download request to avoid dump the unreadable binary content.
func ( *Request) () *Request {
	 := .getDumpOptions()
	.ResponseBody = false
	return .EnableDump()
}

// EnableForceChunkedEncoding enables force using chunked encoding when uploading.
func ( *Request) () *Request {
	.forceChunkedEncoding = true
	return 
}

// DisableForceChunkedEncoding disables force using chunked encoding when uploading.
func ( *Request) () *Request {
	.forceChunkedEncoding = false
	return 
}

// EnableForceMultipart enables force using multipart to upload form data.
func ( *Request) () *Request {
	.isMultiPart = true
	return 
}

// DisableForceMultipart disables force using multipart to upload form data.
func ( *Request) () *Request {
	.isMultiPart = false
	return 
}

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

// GetRetryOption returns the retry configuration of this request.
// It returns nil if retry has not been configured (neither via
// Client.SetCommonRetry* nor Request.SetRetry*).
//
// The returned value is the live option used by this request: mutations
// affect subsequent retries on the same request. Treat it as read-only
// unless you intentionally want to change retry behavior from middleware.
//
// This is useful in middleware to inspect MaxRetries together with
// Request.RetryAttempt, e.g. to report errors only after the configured
// retry budget is exhausted:
//
//	client.OnAfterResponse(func(c *req.Client, resp *req.Response) error {
//	    ro := resp.Request.GetRetryOption()
//	    if ro == nil {
//	        return nil
//	    }
//	    // Cover HTTP error statuses and transport failures (resp.Err with
//	    // no Response). Client OnAfterResponse still runs after failed Do.
//	    failed := resp.IsErrorState() || resp.Err != nil
//	    // RetryAttempt >= MaxRetries only detects budget exhaustion. Retries
//	    // may also stop earlier when a RetryCondition returns false; in that
//	    // case RetryAttempt can be less than MaxRetries on a terminal failure.
//	    if failed && ro.MaxRetries >= 0 &&
//	        resp.Request.RetryAttempt >= ro.MaxRetries {
//	        // report once after final failure
//	    }
//	    return nil
//	})
func ( *Request) () *RetryOption {
	return .retryOption
}

// SetRetryCount enables retry and set the maximum retry count.
// It will retry infinitely if count is negative.
func ( *Request) ( int) *Request {
	.getRetryOption().MaxRetries = 
	return 
}

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

// SetRetryFixedInterval set retry to use a fixed interval.
func ( *Request) ( time.Duration) *Request {
	.getRetryOption().GetRetryInterval = func( *Response,  int) time.Duration {
		return 
	}
	return 
}

// SetRetryBackoffInterval set retry to use a capped exponential backoff with jitter.
// https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
func ( *Request) (,  time.Duration) *Request {
	.getRetryOption().GetRetryInterval = backoffInterval(, )
	return 
}

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

// AddRetryHook adds a retry hook which will be executed before a retry.
func ( *Request) ( RetryHookFunc) *Request {
	 := .getRetryOption()
	.RetryHooks = append(.RetryHooks, )
	return 
}

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

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

// SetClient change the client of request dynamically.
func ( *Request) ( *Client) *Request {
	if  != nil {
		.client = 
	}
	return 
}

// GetClient returns the current client used by request.
func ( *Request) () *Client {
	return .client
}

// EnableCloseConnection closes the connection after sending this
// request and reading its response if set to true in HTTP/1.1 and
// HTTP/2.
//
// Setting this field prevents reuse of TCP connections between
// requests to the same hosts event if EnableKeepAlives() were called.
func ( *Request) () *Request {
	.close = true
	return 
}