// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// HTTP client implementation. See RFC 7230 through 7235.
//
// This is the low-level Transport implementation of http.RoundTripper.
// The high-level interface is in client.go.

package req

import (
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	_ 

	
	
	
	
	
	
	
	h2internal 
	
	
	
	
	
	
	reqtls 
	htmlcharset 
	

	
)

// httpVersion represents http version.
type httpVersion string

const (
	// h1 represents "HTTP/1.1"
	h1 httpVersion = "1.1"
	// h2 represents "HTTP/2.0"
	h2 httpVersion = "2"
	// h3 represents "HTTP/3.0"
	h3 httpVersion = "3"
)

// defaultMaxIdleConnsPerHost is the default value of Transport's
// MaxIdleConnsPerHost.
const defaultMaxIdleConnsPerHost = 2

// Transport is an implementation of http.RoundTripper that supports HTTP,
// HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT).
//
// By default, Transport caches connections for future reuse.
// This may leave many open connections when accessing many hosts.
// This behavior can be managed using Transport's CloseIdleConnections method
// and the MaxIdleConnsPerHost and DisableKeepAlives fields.
//
// Transports should be reused instead of created as needed.
// Transports are safe for concurrent use by multiple goroutines.
//
// A Transport is a low-level primitive for making HTTP and HTTPS requests.
// For high-level functionality, such as cookies and redirects, see Client.
//
// Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2
// for HTTPS URLs, depending on whether the server supports HTTP/2,
// and how the Transport is configured. The DefaultTransport supports HTTP/2.
// To explicitly enable HTTP/2 on a transport, use golang.org/x/net/http2
// and call ConfigureTransport. See the package docs for more about HTTP/2.
//
// Responses with status codes in the 1xx range are either handled
// automatically (100 expect-continue) or ignored. The one
// exception is HTTP status code 101 (Switching Protocols), which is
// considered a terminal status and returned by RoundTrip. To see the
// ignored 1xx responses, use the httptrace trace package's
// ClientTrace.Got1xxResponse.
//
// Transport only retries a request upon encountering a network error
// if the request is idempotent and either has no body or has its
// Request.GetBody defined. HTTP requests are considered idempotent if
// they have HTTP methods GET, HEAD, OPTIONS, or TRACE; or if their
// Header map contains an "Idempotency-Key" or "X-Idempotency-Key"
// entry. If the idempotency key value is a zero-length slice, the
// request is treated as idempotent but the header is not sent on the
// wire.
type Transport struct {
	Headers http.Header
	Cookies []*http.Cookie

	idleMu       sync.Mutex
	closeIdle    bool                                // user has requested to close all idle conns
	idleConn     map[connectMethodKey][]*persistConn // most recently used at end
	idleConnWait map[connectMethodKey]wantConnQueue  // waiting getConns
	idleLRU      connLRU

	reqMu       sync.Mutex
	reqCanceler map[*http.Request]context.CancelCauseFunc

	connsPerHostMu   sync.Mutex
	connsPerHost     map[connectMethodKey]int
	connsPerHostWait map[connectMethodKey]wantConnQueue // waiting getConns
	dialsInProgress  wantConnQueue

	altSvcJar        altsvc.Jar
	pendingAltSvcs   map[string]*pendingAltSvc
	pendingAltSvcsMu sync.Mutex

	// Force using specific http version
	forceHttpVersion httpVersion

	// rejectProxyWithSetHosts prevents proxy-side DNS from bypassing the
	// fail-closed static host mapping installed by Client.SetHosts.
	rejectProxyWithSetHosts bool

	transport.Options

	t2 *h2internal.Transport // non-nil if http2 wired up
	t3 *http3.Transport

	// disableAutoDecode, if true, prevents auto detect response
	// body's charset and decode it to utf-8
	disableAutoDecode bool

	// autoDecodeContentType specifies an optional function for determine
	// whether the response body should been auto decode to utf-8.
	// Only valid when DisableAutoDecode is true.
	autoDecodeContentType func(contentType string) bool
	wrappedRoundTrip      http.RoundTripper
	httpRoundTripWrappers []HttpRoundTripWrapper
}

// NewTransport is an alias of T
func () *Transport {
	return T()
}

// T create a Transport.
func () *Transport {
	 := &Transport{
		Options: transport.Options{
			Proxy:                 http.ProxyFromEnvironment,
			MaxIdleConns:          100,
			IdleConnTimeout:       90 * time.Second,
			TLSHandshakeTimeout:   10 * time.Second,
			ExpectContinueTimeout: 1 * time.Second,
			TLSClientConfig:       &tls.Config{NextProtos: []string{"http/1.1", "h2"}},
		},
	}
	.t2 = &h2internal.Transport{Options: &.Options}
	return 
}

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

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

// HttpRoundTripWrapper is transport middleware function.
type HttpRoundTripWrapper func(rt http.RoundTripper) http.RoundTripper

// HttpRoundTripWrapperFunc is transport middleware function, more convenient than HttpRoundTripWrapper.
type HttpRoundTripWrapperFunc func(rt http.RoundTripper) HttpRoundTripFunc

func ( HttpRoundTripWrapperFunc) () HttpRoundTripWrapper {
	return func( http.RoundTripper) http.RoundTripper {
		return ()
	}
}

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

// WrapRoundTrip adds a transport middleware function that will give the caller
// an opportunity to wrap the underlying http.RoundTripper.
func ( *Transport) ( ...HttpRoundTripWrapper) *Transport {
	if len() == 0 {
		return 
	}
	if .wrappedRoundTrip == nil {
		.httpRoundTripWrappers = 
		 := func( *http.Request) (*http.Response, error) {
			return .roundTrip()
		}
		.wrappedRoundTrip = HttpRoundTripFunc()
	} else {
		.httpRoundTripWrappers = append(.httpRoundTripWrappers, ...)
	}

	for ,  := range  {
		.wrappedRoundTrip = (.wrappedRoundTrip)
	}
	return 
}

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

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

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

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

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

// GetMaxIdleConns returns MaxIdleConns.
func ( *Transport) () int {
	return .MaxIdleConns
}

// SetMaxIdleConns set the MaxIdleConns, which controls the maximum number of idle (keep-alive)
// connections across all hosts. Zero means no limit.
func ( *Transport) ( int) *Transport {
	.MaxIdleConns = 
	return 
}

// 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) ( int) *Transport {
	.MaxConnsPerHost = 
	return 
}

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

// SetTLSHandshakeTimeout set the TLSHandshakeTimeout, which specifies the
// maximum amount of time waiting to wait for a TLS handshake.
//
// Zero means no timeout.
func ( *Transport) ( time.Duration) *Transport {
	.TLSHandshakeTimeout = 
	return 
}

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

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

// 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) ( func( context.Context,  *url.URL,  string) (http.Header, error)) *Transport {
	.GetProxyConnectHeader = 
	return 
}

// SetProxyConnectHeader set the ProxyConnectHeader, which optionally specifies headers to
// send to proxies during CONNECT requests.
// To set the header dynamically, see SetGetProxyConnectHeader.
func ( *Transport) ( http.Header) *Transport {
	.ProxyConnectHeader = 
	return 
}

// 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) ( int) *Transport {
	.ReadBufferSize = 
	return 
}

// 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) ( int) *Transport {
	.WriteBufferSize = 
	return 
}

// 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) ( int64) *Transport {
	.MaxResponseHeaderBytes = 
	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 ( *Transport) ( uint32) *Transport {
	.t2.MaxHeaderListSize = 
	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 ( *Transport) ( bool) *Transport {
	.t2.StrictMaxConcurrentStreams = 
	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 ( *Transport) ( time.Duration) *Transport {
	.t2.ReadIdleTimeout = 
	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 ( *Transport) ( time.Duration) *Transport {
	.t2.PingTimeout = 
	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 ( *Transport) ( time.Duration) *Transport {
	.t2.WriteByteTimeout = 
	return 
}

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

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

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

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

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

// SetDebug set the optional debug function.
func ( *Transport) ( func( string,  ...any)) *Transport {
	.Debugf = 
	return 
}

// SetProxy set the http proxy, only valid for HTTP1 and HTTP2, which specifies a function
// to return a proxy for a given Request. If the function returns a non-nil error, the request
// is aborted with the provided error.
//
// The proxy type is determined by the URL scheme. "http",
// "https", "socks5", "socks5h", "socks4", and "socks4a" are
// supported. If the scheme is empty, "http" is assumed.
// "socks5" is treated the same as "socks5h".
// "socks4" resolves domain names locally to IPv4; "socks4a" lets the
// proxy resolve domain names. SOCKS4 only supports IPv4 destinations.
//
// If Proxy is nil or returns a nil *URL, no proxy is used.
func ( *Transport) ( func(*http.Request) (*url.URL, error)) *Transport {
	.Proxy = 
	return 
}

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

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

type pendingAltSvc struct {
	CurrentIndex int
	Entries      []*altsvc.AltSvc
	Mu           sync.Mutex
	LastTime     time.Time
	Transport    http.RoundTripper
}

// EnableForceHTTP1 enable force using HTTP1 (disabled by default).
func ( *Transport) () *Transport {
	.forceHttpVersion = h1
	return 
}

// EnableForceHTTP2 enable force using HTTP2 for https requests
// (disabled by default).
func ( *Transport) () *Transport {
	.forceHttpVersion = h2
	return 
}

// EnableH2C enables HTTP2 over TCP without TLS.
func ( *Transport) () *Transport {
	.Options.EnableH2C = true
	.t2.AllowHTTP = true
	.DialTLSContext = func( context.Context, ,  string) (net.Conn, error) {
		return net.Dial(, )
	}
	return 
}

// DisableH2C disables HTTP2 over TCP without TLS.
func ( *Transport) () *Transport {
	.Options.EnableH2C = false
	.t2.AllowHTTP = false
	.t2.DialTLSContext = nil
	return 
}

// EnableForceHTTP3 enable force using HTTP3 for https requests
// (disabled by default).
func ( *Transport) () *Transport {
	.EnableHTTP3()
	if .t3 != nil {
		.forceHttpVersion = h3
	}
	return 
}

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

func ( *Transport) () {
	.altSvcJar = nil
	.pendingAltSvcs = nil
	.t3 = nil
}

func ( *Transport) () {
	if .t3 != nil {
		return
	}

	 := runtime.Version()
	 := strings.Split(, ".")

	if len() < 2 || [0] != "go1" {
		if .Debugf != nil {
			.Debugf("bad go version format: %s", )
		}
		return
	}

	if .altSvcJar == nil {
		.altSvcJar = altsvc.NewAltSvcJar()
	}
	if .pendingAltSvcs == nil {
		.pendingAltSvcs = make(map[string]*pendingAltSvc)
	}
	 := &http3.Transport{
		Options: &.Options,
	}
	.t3 = 
}

type wrapResponseBodyKeyType int

const wrapResponseBodyKey wrapResponseBodyKeyType = iota

type wrapResponseBodyFunc func(rc io.ReadCloser) io.ReadCloser

func ( *Transport) ( *http.Response,  *http.Request) {
	if ,  := .Context().Value(wrapResponseBodyKey).(wrapResponseBodyFunc);  {
		.wrapResponseBody(, )
	}
	.autoDecodeResponseBody()
	dump.WrapResponseBodyIfNeeded(, , .Dump)
}

var allowedProtocols = map[string]bool{
	"h3": true,
}

func ( *Transport) ( *http.Request,  string) {
	 := netutil.AuthorityKey(.URL)
	 := .altSvcJar.GetAltSvc()
	if  != nil {
		return
	}

	.pendingAltSvcsMu.Lock()
	defer .pendingAltSvcsMu.Unlock()
	,  := .pendingAltSvcs[]
	if  {
		return
	}
	,  := altsvcutil.ParseHeader()
	if  != nil {
		if .Debugf != nil {
			.Debugf("failed to parse alt-svc header: %s", .Error())
		}
		return
	}
	var  []*altsvc.AltSvc
	for ,  := range  {
		if allowedProtocols[.Protocol] {
			 = append(, )
		}
	}
	if len() > 0 {
		 := &pendingAltSvc{
			Entries: ,
		}
		.pendingAltSvcs[] = 
		go .handlePendingAltSvc(.URL, )
	}
}

func ( *Transport) ( *url.URL,  *pendingAltSvc) {
	for  := .CurrentIndex;  < len(.Entries); ++ {
		switch .Entries[].Protocol {
		case "h3": // only support h3 in alt-svc for now
			 := altsvcutil.ConvertURL(.Entries[], )
			 := .Host
			 := .t3.AddConn(context.Background(), )
			if  != nil {
				if .Debugf != nil {
					.Debugf("failed to get http3 connection: %s", .Error())
				}
			} else {
				.CurrentIndex = 
				.Transport = .t3
				if .Debugf != nil {
					.Debugf("detected that the server %s supports http3, will try to use http3 protocol in subsequent requests", )
				}
				return
			}
		}
	}
}

func ( *Transport) ( *http.Response,  wrapResponseBodyFunc) {
	switch b := .Body.(type) {
	case *gzipReader:
		.body.body = (.body.body)
	case compress.CompressReader:
		.SetUnderlyingBody((.GetUnderlyingBody()))
	default:
		.Body = (.Body)
	}
}

func ( *Transport) ( *http.Response) {
	if .disableAutoDecode || .Header.Get("Accept-Encoding") != "" {
		return
	}
	 := .Header.Get("Content-Type")
	var  func( string) bool
	if .autoDecodeContentType != nil {
		 = .autoDecodeContentType
	} else {
		 = autoDecodeText
	}
	if !() {
		return
	}
	, ,  := mime.ParseMediaType()
	if  != nil {
		if .Debugf != nil {
			.Debugf("failed to parse content type %q: %v", , )
		}
	} else if ,  := ["charset"];  {
		 = strings.ToLower()
		if strings.Contains(, "utf-8") || strings.Contains(, "utf8") { // do not decode utf-8
			return
		}
		,  := htmlcharset.Lookup()
		if  == nil {
			,  = ianaindex.MIME.Encoding()
			if  != nil ||  == nil {
				if .Debugf != nil {
					.Debugf("ignore charset %s which is detected in Content-Type but not supported", )
				}
				return
			}
		}
		if .Debugf != nil {
			.Debugf("charset %s detected in Content-Type, auto-decode to utf-8", )
		}
		 := .NewDecoder().Reader(.Body)
		.Body = &decodeReaderCloser{.Body, }
		return
	}
	.Body = newAutoDecodeReadCloser(.Body, )
}

func ( *Transport) () int {
	if .WriteBufferSize > 0 {
		return .WriteBufferSize
	}
	return 4 << 10
}

func ( *Transport) () int {
	if .ReadBufferSize > 0 {
		return .ReadBufferSize
	}
	return 4 << 10
}

// Clone returns a deep copy of t's exported fields.
func ( *Transport) () *Transport {
	 := &Transport{
		Headers:                 .Headers.Clone(),
		Cookies:                 cloneSlice(.Cookies),
		Options:                 .Options.Clone(),
		disableAutoDecode:       .disableAutoDecode,
		autoDecodeContentType:   .autoDecodeContentType,
		forceHttpVersion:        .forceHttpVersion,
		rejectProxyWithSetHosts: .rejectProxyWithSetHosts,
		httpRoundTripWrappers:   .httpRoundTripWrappers,
	}
	if len(.httpRoundTripWrappers) > 0 { // clone transport middleware
		 := func( *http.Request) (*http.Response, error) {
			return .roundTrip()
		}
		.wrappedRoundTrip = HttpRoundTripFunc()
		for ,  := range .httpRoundTripWrappers {
			.wrappedRoundTrip = (.wrappedRoundTrip)
		}
	}
	if .t2 != nil {
		.t2 = &h2internal.Transport{
			Options:                    &.Options,
			MaxHeaderListSize:          .t2.MaxHeaderListSize,
			StrictMaxConcurrentStreams: .t2.StrictMaxConcurrentStreams,
			ReadIdleTimeout:            .t2.ReadIdleTimeout,
			PingTimeout:                .t2.PingTimeout,
			WriteByteTimeout:           .t2.WriteByteTimeout,
			ConnectionFlow:             .t2.ConnectionFlow,
			Settings:                   cloneSlice(.t2.Settings),
			HeaderPriority:             .t2.HeaderPriority,
			PriorityFrames:             cloneSlice(.t2.PriorityFrames),
		}
	}
	if .t3 != nil {
		.EnableHTTP3()
	}
	return 
}

// EnableDump enables the dump for all requests with specified dump options.
func ( *Transport) ( *DumpOptions) {
	 := newDumper()
	.Dump = 
	go .Start()
}

// DisableDump disables the dump.
func ( *Transport) () {
	if .Dump != nil {
		.Dump.Stop()
		.Dump = nil
	}
}

func ( *Transport) () bool {
	return .DialTLSContext != nil
}

// transportRequest is a wrapper around a *Request that adds
// optional extra headers to write and stores any error to return
// from roundTrip.
type transportRequest struct {
	*http.Request                        // original request, not to be mutated
	extra         http.Header            // extra headers to write, or nil
	trace         *httptrace.ClientTrace // optional

	ctx    context.Context // canceled when we are done with the request
	cancel context.CancelCauseFunc

	mu  sync.Mutex // guards err
	err error      // first setError value for mapRoundTripError to consider
}

func ( *transportRequest) () http.Header {
	if .extra == nil {
		.extra = make(http.Header)
	}
	return .extra
}

func ( *transportRequest) ( error) {
	.mu.Lock()
	if .err == nil {
		.err = 
	}
	.mu.Unlock()
}

func ( *Transport) ( *http.Request,  *altsvc.AltSvc) ( *http.Response,  error) {
	 := .Clone(.Context())
	.URL = altsvcutil.ConvertURL(, .URL)
	switch .Protocol {
	case "h3":
		,  = .t3.RoundTrip()
	case "h2":
		,  = .t2.RoundTrip()
	default:
		// impossible!
		panic(fmt.Sprintf("unknown protocol %q", .Protocol))
	}
	return
}

func ( *Transport) ( *http.Request) ( *http.Response,  error) {
	if .altSvcJar == nil {
		return
	}
	 := netutil.AuthorityKey(.URL)
	.pendingAltSvcsMu.Lock()
	,  := .pendingAltSvcs[]
	.pendingAltSvcsMu.Unlock()
	if  && .Transport != nil {
		.Mu.Lock()
		if .Transport != nil {
			.LastTime = time.Now()
			 := .Clone(.Context())
			.URL = altsvcutil.ConvertURL(.Entries[.CurrentIndex], .URL)
			,  = .Transport.RoundTrip()
			if  != nil {
				.Transport = nil
				if .CurrentIndex+1 < len(.Entries) {
					.CurrentIndex++
					go .handlePendingAltSvc(.URL, )
				}
			} else {
				.altSvcJar.SetAltSvc(, .Entries[.CurrentIndex])
				.pendingAltSvcsMu.Lock()
				delete(.pendingAltSvcs, )
				.pendingAltSvcsMu.Unlock()
			}
		}
		.Mu.Unlock()
		return
	}
	if  := .altSvcJar.GetAltSvc();  != nil {
		return .roundTripAltSvc(, )
	}
	return
}

func validateHeaders( http.Header) string {
	for ,  := range  {
		if !httpguts.ValidHeaderFieldName() {
			return fmt.Sprintf("field name %q", )
		}
		for ,  := range  {
			if !httpguts.ValidHeaderFieldValue() {
				// Don't include the value in the error,
				// because it may be sensitive.
				return fmt.Sprintf("field value for %q", )
			}
		}
	}
	return ""
}

// roundTrip implements a http.RoundTripper over HTTP.
func ( *Transport) ( *http.Request) ( *http.Response,  error) {
	 := .Context()
	 := httptrace.ContextClientTrace()

	if .URL == nil {
		closeBody()
		return nil, errors.New("http: nil Request.URL")
	}

	,  = .checkAltSvc()
	if  != nil ||  != nil {
		return
	}

	 := .URL.Scheme
	 :=  == "http" ||  == "https"

	if  {
		// Validate the outgoing headers.
		if  := validateHeaders(.Header);  != "" {
			closeBody()
			return nil, fmt.Errorf("net/http: invalid header %s", )
		}

		// Validate the outgoing trailers too.
		if  := validateHeaders(.Trailer);  != "" {
			closeBody()
			return nil, fmt.Errorf("net/http: invalid trailer %s", )
		}
	}

	if .Header == nil {
		.Header = make(http.Header)
	}

	if .forceHttpVersion != "" {
		switch .forceHttpVersion {
		case h3:
			return .t3.RoundTrip()
		case h2:
			return .t2.RoundTrip()
		}
	}

	 := 
	 = setupRewindBody()

	if  == "https" && .forceHttpVersion != h1 {
		,  := .t2.RoundTripOnlyCachedConn()
		if  != h2internal.ErrNoCachedConn && !h2internal.CanRetryError() {
			return , 
		}
		,  = rewindBody()
		if  != nil {
			return nil, 
		}
		if .t3 != nil {
			,  = .t3.RoundTripOnlyCachedConn()
			if  != http3.ErrNoCachedConn {
				return , 
			}
			,  = rewindBody()
			if  != nil {
				return nil, 
			}
		}
	}

	if ! {
		closeBody()
		return nil, badStringError("unsupported protocol scheme", )
	}
	if .Method != "" && !validMethod(.Method) {
		closeBody()
		return nil, fmt.Errorf("net/http: invalid method %q", .Method)
	}
	if .URL.Host == "" {
		closeBody()
		return nil, errors.New("http: no Host in request URL")
	}

	// Transport request context.
	//
	// If RoundTrip returns an error, it cancels this context before returning.
	//
	// If RoundTrip returns no error:
	//   - For an HTTP/1 request, persistConn.readLoop cancels this context
	//     after reading the request body.
	//   - For an HTTP/2 request, RoundTrip cancels this context after the HTTP/2
	//     RoundTripper returns.
	,  := context.WithCancelCause(.Context())

	// Convert Request.Cancel into context cancellation.
	if .Cancel != nil {
		go awaitLegacyCancel(, , )
	}

	// Convert Transport.CancelRequest into context cancellation.
	//
	// This is lamentably expensive. CancelRequest has been deprecated for a long time
	// and doesn't work on HTTP/2 requests. Perhaps we should drop support for it entirely.
	 = .prepareTransportCancel(, )

	defer func() {
		if  != nil {
			()
		}
	}()

	for {
		select {
		case <-.Done():
			closeBody()
			return nil, context.Cause()
		default:
		}

		// treq gets modified by roundTrip, so we need to recreate for each retry.
		 := &transportRequest{Request: , trace: , ctx: , cancel: }
		,  := .connectMethodForRequest()
		if  != nil {
			closeBody()
			return nil, 
		}

		// Get the cached or newly-created connection to either the
		// host (for http or https), the http proxy, or the http proxy
		// pre-CONNECTed to https server. In any case, we'll be ready
		// to send it requests.
		,  := .getConn(, )
		if  != nil {
			closeBody()
			return nil, 
		}

		var  *http.Response
		if .forceHttpVersion != h1 && .alt != nil {
			// HTTP/2 path.
			,  = .alt.RoundTrip()
		} else {
			,  = .roundTrip()
		}
		if  == nil {
			if .alt != nil {
				// HTTP/2 requests are not cancelable with CancelRequest,
				// so we have no further need for the request context.
				//
				// On the HTTP/1 path, roundTrip takes responsibility for
				// canceling the context after the response body is read.
				(errRequestDone)
			}

			.Request = 
			return , nil
		}

		// Failed. Clean up and determine whether to retry.
		if h2internal.IsNoCachedConnError() {
			if .removeIdleConn() {
				.decConnsPerHost(.cacheKey)
			}
		} else if !.shouldRetryRequest(, ) {
			// Issue 16465: return underlying net.Conn.Read error from peek,
			// as we've historically done.
			if ,  := .(nothingWrittenError);  {
				 = .error
			}
			if ,  := .(transportReadFromServerError);  {
				 = .err
			}
			if ,  := .Body.(*readTrackingBody);  && !.didClose {
				// Issue 49621: Close the request body if pconn.roundTrip
				// didn't do so already. This can happen if the pconn
				// write loop exits without reading the write request.
				closeBody()
			}
			return nil, 
		}
		testHookRoundTripRetried()

		// Rewind the body if we're able to.
		,  = rewindBody()
		if  != nil {
			return nil, 
		}
	}
}

func awaitLegacyCancel( context.Context,  context.CancelCauseFunc,  *http.Request) {
	select {
	case <-.Cancel:
		(common.ErrRequestCanceled)
	case <-.Done():
	}
}

var errCannotRewind = errors.New("net/http: cannot rewind body after connection loss")

type readTrackingBody struct {
	io.ReadCloser
	didRead  bool
	didClose bool
}

func ( *readTrackingBody) ( []byte) (int, error) {
	.didRead = true
	return .ReadCloser.Read()
}

func ( *readTrackingBody) () error {
	.didClose = true
	return .ReadCloser.Close()
}

// setupRewindBody returns a new request with a custom body wrapper
// that can report whether the body needs rewinding.
// This lets rewindBody avoid an error result when the request
// does not have GetBody but the body hasn't been read at all yet.
func setupRewindBody( *http.Request) *http.Request {
	if .Body == nil || .Body == NoBody {
		return 
	}
	 := *
	.Body = &readTrackingBody{ReadCloser: .Body}
	return &
}

// rewindBody returns a new request with the body rewound.
// It returns req unmodified if the body does not need rewinding.
// rewindBody takes care of closing req.Body when appropriate
// (in all cases except when rewindBody returns req unmodified).
func rewindBody( *http.Request) ( *http.Request,  error) {
	if .Body == nil || .Body == NoBody || (!.Body.(*readTrackingBody).didRead && !.Body.(*readTrackingBody).didClose) {
		return , nil // nothing to rewind
	}
	if !.Body.(*readTrackingBody).didClose {
		closeBody()
	}
	if .GetBody == nil {
		return nil, errCannotRewind
	}
	,  := .GetBody()
	if  != nil {
		return nil, 
	}
	 := *
	.Body = &readTrackingBody{ReadCloser: }
	return &, nil
}

// shouldRetryRequest reports whether we should retry sending a failed
// HTTP request on a new connection. The non-nil input error is the
// error from roundTrip.
func ( *persistConn) ( *http.Request,  error) bool {
	if h2internal.IsNoCachedConnError() {
		// Issue 16582: if the user started a bunch of
		// requests at once, they can all pick the same conn
		// and violate the server's max concurrent streams.
		// Instead, match the HTTP/1 behavior for now and dial
		// again to get a new TCP connection, rather than failing
		// this request.
		return true
	}
	if  == errMissingHost {
		// User error.
		return false
	}
	if !.isReused() {
		// This was a fresh connection. There's no reason the server
		// should've hung up on us.
		//
		// Also, if we retried now, we could loop forever
		// creating new connections and retrying if the server
		// is just hanging up on us because it doesn't like
		// our request (as opposed to sending an error).
		return false
	}
	if ,  := .(nothingWrittenError);  {
		// We never wrote anything, so it's safe to retry, if there's no body or we
		// can "rewind" the body with GetBody.
		return outgoingLength() == 0 || .GetBody != nil
	}
	if !isReplayable() {
		// Don't retry non-idempotent requests.
		return false
	}
	if ,  := .(transportReadFromServerError);  {
		// We got some non-EOF net.Conn.Read failure reading
		// the 1st response byte from the server.
		return true
	}
	if  == errServerClosedIdle {
		// The server replied with io.EOF while we were trying to
		// read the response. Probably an unfortunately keep-alive
		// timeout, just as the client was writing a request.
		return true
	}
	return false // conservatively
}

// 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) () {
	.idleMu.Lock()
	 := .idleConn
	.idleConn = nil
	.closeIdle = true // close newly idle connections
	.idleLRU = connLRU{}
	.idleMu.Unlock()
	for ,  := range  {
		for ,  := range  {
			.close(errCloseIdleConns)
		}
	}
	.connsPerHostMu.Lock()
	.dialsInProgress.all(func( *wantConn) {
		if .cancelCtx != nil && !.waiting() {
			.cancelCtx()
		}
	})
	.connsPerHostMu.Unlock()

	if  := .t2;  != nil {
		.CloseIdleConnections()
	}
}

// prepareTransportCancel sets up state to convert Transport.CancelRequest into context cancellation.
func ( *Transport) ( *http.Request,  context.CancelCauseFunc) context.CancelCauseFunc {
	// Historically, RoundTrip has not modified the Request in any way.
	// We could avoid the need to keep a map of all in-flight requests by adding
	// a field to the Request containing its cancel func, and setting that field
	// while the request is in-flight. Callers aren't supposed to reuse a Request
	// until after the response body is closed, so this wouldn't violate any
	// concurrency guarantees.
	 := func( error) {
		()
		.reqMu.Lock()
		delete(.reqCanceler, )
		.reqMu.Unlock()
	}
	.reqMu.Lock()
	if .reqCanceler == nil {
		.reqCanceler = make(map[*http.Request]context.CancelCauseFunc)
	}
	.reqCanceler[] = 
	.reqMu.Unlock()
	return 
}

// 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) ( *http.Request) {
	.reqMu.Lock()
	 := .reqCanceler[]
	.reqMu.Unlock()
	if  != nil {
		(common.ErrRequestCanceled)
	}
}

// resetProxyConfig is used by tests.
func resetProxyConfig() {
}

func ( *Transport) ( *transportRequest) ( connectMethod,  error) {
	.targetScheme = .URL.Scheme
	.targetAddr = canonicalAddr(.URL)
	if .Proxy != nil {
		.proxyURL,  = .Proxy(.Request)
		if  == nil && .proxyURL != nil && .rejectProxyWithSetHosts {
			 = errors.New("req: SetHosts cannot be used with a proxy")
		}
	}
	.onlyH1 = .forceHttpVersion == h1 || requestRequiresHTTP1(.Request)
	return , 
}

// proxyAuth returns the Proxy-Authorization header to set
// on requests, if applicable.
func ( *connectMethod) () string {
	if .proxyURL == nil {
		return ""
	}
	if  := .proxyURL.User;  != nil {
		 := .Username()
		,  := .Password()
		return "Basic " + basicAuth(, )
	}
	return ""
}

// error values for debugging and testing, not seen by users.
var (
	errKeepAlivesDisabled = errors.New("http: putIdleConn: keep alives disabled")
	errConnBroken         = errors.New("http: putIdleConn: connection is in bad state")
	errCloseIdle          = errors.New("http: putIdleConn: CloseIdleConnections was called")
	errTooManyIdle        = errors.New("http: putIdleConn: too many idle connections")
	errTooManyIdleHost    = errors.New("http: putIdleConn: too many idle connections for host")
	errCloseIdleConns     = errors.New("http: CloseIdleConnections called")
	errReadLoopExiting    = errors.New("http: persistConn.readLoop exiting")
	errIdleConnTimeout    = errors.New("http: idle connection timeout")

	// errServerClosedIdle is not seen by users for idempotent requests, but may be
	// seen by a user if the server shuts down an idle connection and sends its FIN
	// in flight with already-written POST body bytes from the client.
	// See https://github.com/golang/go/issues/19943#issuecomment-355607646
	errServerClosedIdle = errors.New("http: server closed idle connection")
)

// transportReadFromServerError is used by Transport.readLoop when the
// 1 byte peek read fails and we're actually anticipating a response.
// Usually this is just due to the inherent keep-alive shut down race,
// where the server closed the connection at the same time the client
// wrote. The underlying err field is usually io.EOF or some
// ECONNRESET sort of thing which varies by platform. But it might be
// the user's custom net.Conn.Read error too, so we carry it along for
// them to return from Transport.RoundTrip.
type transportReadFromServerError struct {
	err error
}

func ( transportReadFromServerError) () error { return .err }

func ( transportReadFromServerError) () string {
	return fmt.Sprintf("net/http: Transport failed to read from server: %v", .err)
}

func ( *Transport) ( *persistConn) {
	if  := .tryPutIdleConn();  != nil {
		.close()
	}
}

func ( *Transport) () int {
	if  := .MaxIdleConnsPerHost;  != 0 {
		return 
	}
	return defaultMaxIdleConnsPerHost
}

// tryPutIdleConn adds pconn to the list of idle persistent connections awaiting
// a new request.
// If pconn is no longer needed or not in a good state, tryPutIdleConn returns
// an error explaining why it wasn't registered.
// tryPutIdleConn does not close pconn. Use putOrCloseIdleConn instead for that.
func ( *Transport) ( *persistConn) error {
	if .DisableKeepAlives || .MaxIdleConnsPerHost < 0 {
		return errKeepAlivesDisabled
	}
	if .isBroken() {
		return errConnBroken
	}
	.markReused()

	.idleMu.Lock()
	defer .idleMu.Unlock()

	// HTTP/2 (pconn.alt != nil) connections do not come out of the idle list,
	// because multiple goroutines can use them simultaneously.
	// If this is an HTTP/2 connection being “returned,” we're done.
	if .alt != nil && .idleLRU.m[] != nil {
		return nil
	}

	// Deliver pconn to goroutine waiting for idle connection, if any.
	// (They may be actively dialing, but this conn is ready first.
	// Chrome calls this socket late binding.
	// See https://www.chromium.org/developers/design-documents/network-stack#TOC-Connection-Management.)
	 := .cacheKey
	if ,  := .idleConnWait[];  {
		 := false
		if .alt == nil {
			// HTTP/1.
			// Loop over the waiting list until we find a w that isn't done already, and hand it pconn.
			for .len() > 0 {
				 := .popFront()
				if .tryDeliver(, nil, time.Time{}) {
					 = true
					break
				}
			}
		} else {
			// HTTP/2.
			// Can hand the same pconn to everyone in the waiting list,
			// and we still won't be done: we want to put it in the idle
			// list unconditionally, for any future clients too.
			for .len() > 0 {
				 := .popFront()
				.tryDeliver(, nil, time.Time{})
			}
		}
		if .len() == 0 {
			delete(.idleConnWait, )
		} else {
			.idleConnWait[] = 
		}
		if  {
			return nil
		}
	}

	if .closeIdle {
		return errCloseIdle
	}
	if .idleConn == nil {
		.idleConn = make(map[connectMethodKey][]*persistConn)
	}
	 := .idleConn[]
	if len() >= .maxIdleConnsPerHost() {
		return errTooManyIdleHost
	}
	for ,  := range  {
		if  ==  {
			log.Fatalf("dup idle pconn %p in freelist", )
		}
	}
	.idleConn[] = append(, )
	.idleLRU.add()
	if .MaxIdleConns != 0 && .idleLRU.len() > .MaxIdleConns {
		 := .idleLRU.removeOldest()
		.close(errTooManyIdle)
		.removeIdleConnLocked()
	}

	// Set idle timer, but only for HTTP/1 (pconn.alt == nil).
	// The HTTP/2 implementation manages the idle timer itself
	// (see idleConnTimeout in h2_bundle.go).
	if .IdleConnTimeout > 0 && .alt == nil {
		if .idleTimer != nil {
			.idleTimer.Reset(.IdleConnTimeout)
		} else {
			.idleTimer = time.AfterFunc(.IdleConnTimeout, .closeConnIfStillIdle)
		}
	}
	.idleAt = time.Now()
	return nil
}

// queueForIdleConn queues w to receive the next idle connection for w.cm.
// As an optimization hint to the caller, queueForIdleConn reports whether
// it successfully delivered an already-idle connection.
func ( *Transport) ( *wantConn) ( bool) {
	if .DisableKeepAlives {
		return false
	}

	.idleMu.Lock()
	defer .idleMu.Unlock()

	// Stop closing connections that become idle - we might want one.
	// (That is, undo the effect of t.CloseIdleConnections.)
	.closeIdle = false

	if  == nil {
		// Happens in test hook.
		return false
	}

	// If IdleConnTimeout is set, calculate the oldest
	// persistConn.idleAt time we're willing to use a cached idle
	// conn.
	var  time.Time
	if .IdleConnTimeout > 0 {
		 = time.Now().Add(-.IdleConnTimeout)
	}

	// Look for most recently-used idle connection.
	if ,  := .idleConn[.key];  {
		 := false
		 := false
		for len() > 0 && ! {
			 := [len()-1]

			// See whether this connection has been idle too long, considering
			// only the wall time (the Round(0)), in case this is a laptop or VM
			// coming out of suspend with previously cached idle connections.
			 := !.IsZero() && .idleAt.Round(0).Before()
			if  {
				// Async cleanup. Launch in its own goroutine (as if a
				// time.AfterFunc called it); it acquires idleMu, which we're
				// holding, and does a synchronous net.Conn.Close.
				go .closeConnIfStillIdle()
			}
			if .isBroken() ||  {
				// If either persistConn.readLoop has marked the connection
				// broken, but Transport.removeIdleConn has not yet removed it
				// from the idle list, or if this persistConn is too old (it was
				// idle too long), then ignore it and look for another. In both
				// cases it's already in the process of being closed.
				 = [:len()-1]
				continue
			}
			 = .tryDeliver(, nil, .idleAt)
			if  {
				if .alt != nil {
					// HTTP/2: multiple clients can share pconn.
					// Leave it in the list.
				} else {
					// HTTP/1: only one client can use pconn.
					// Remove it from the list.
					.idleLRU.remove()
					 = [:len()-1]
				}
			}
			 = true
		}
		if len() > 0 {
			.idleConn[.key] = 
		} else {
			delete(.idleConn, .key)
		}
		if  {
			return 
		}
	}

	// Register to receive next connection that becomes idle.
	if .idleConnWait == nil {
		.idleConnWait = make(map[connectMethodKey]wantConnQueue)
	}
	 := .idleConnWait[.key]
	.cleanFrontNotWaiting()
	.pushBack()
	.idleConnWait[.key] = 
	return false
}

// removeIdleConn marks pconn as dead.
func ( *Transport) ( *persistConn) bool {
	.idleMu.Lock()
	defer .idleMu.Unlock()
	return .removeIdleConnLocked()
}

// t.idleMu must be held.
func ( *Transport) ( *persistConn) bool {
	if .idleTimer != nil {
		.idleTimer.Stop()
	}
	.idleLRU.remove()
	 := .cacheKey
	 := .idleConn[]
	var  bool
	switch len() {
	case 0:
		// Nothing
	case 1:
		if [0] ==  {
			delete(.idleConn, )
			 = true
		}
	default:
		for ,  := range  {
			if  !=  {
				continue
			}
			// Slide down, keeping most recently-used
			// conns at the end.
			copy([:], [+1:])
			.idleConn[] = [:len()-1]
			 = true
			break
		}
	}
	return 
}

var zeroDialer net.Dialer

func ( *Transport) ( context.Context, ,  string) (net.Conn, error) {
	if .DialContext != nil {
		,  := .DialContext(, , )
		if  == nil &&  == nil {
			 = errors.New("net/http: Transport.DialContext hook returned (nil, nil)")
		}
		return , 
	}
	return zeroDialer.DialContext(, , )
}

// A wantConn records state about a wanted connection
// (that is, an active call to getConn).
// The conn may be gotten by dialing or by finding an idle connection,
// or a cancellation may make the conn no longer wanted.
// These three options are racing against each other and use
// wantConn to coordinate and agree about the winning outcome.
type wantConn struct {
	cm  connectMethod
	key connectMethodKey // cm.key()

	// hooks for testing to know when dials are done
	// beforeDial is called in the getConn goroutine when the dial is queued.
	// afterDial is called when the dial is completed or canceled.
	beforeDial func()
	afterDial  func()

	mu        sync.Mutex      // protects ctx, done and sending of the result
	ctx       context.Context // context for dial, cleared after delivered or canceled
	cancelCtx context.CancelFunc
	done      bool             // true after delivered or canceled
	result    chan connOrError // channel to deliver connection or error
}

type connOrError struct {
	pc     *persistConn
	err    error
	idleAt time.Time
}

// waiting reports whether w is still waiting for an answer (connection or error).
func ( *wantConn) () bool {
	.mu.Lock()
	defer .mu.Unlock()

	return !.done
}

// getCtxForDial returns context for dial or nil if connection was delivered or canceled.
func ( *wantConn) () context.Context {
	.mu.Lock()
	defer .mu.Unlock()

	return .ctx
}

// tryDeliver attempts to deliver pc, err to w and reports whether it succeeded.
func ( *wantConn) ( *persistConn,  error,  time.Time) bool {
	.mu.Lock()
	defer .mu.Unlock()

	if .done {
		return false
	}
	if ( == nil) == ( == nil) {
		panic("net/http: internal error: misuse of tryDeliver")
	}
	.ctx = nil
	.done = true

	.result <- connOrError{pc: , err: , idleAt: }
	close(.result)

	return true
}

// cancel marks w as no longer wanting a result (for example, due to cancellation).
// If a connection has been delivered already, cancel returns it with t.putOrCloseIdleConn.
func ( *wantConn) ( *Transport,  error) {
	.mu.Lock()
	var  *persistConn
	if .done {
		if ,  := <-.result;  {
			 = .pc
		}
	} else {
		close(.result)
	}
	.ctx = nil
	.done = true
	.mu.Unlock()

	if  != nil {
		.putOrCloseIdleConn()
	}
}

// A wantConnQueue is a queue of wantConns.
type wantConnQueue struct {
	// This is a queue, not a deque.
	// It is split into two stages - head[headPos:] and tail.
	// popFront is trivial (headPos++) on the first stage, and
	// pushBack is trivial (append) on the second stage.
	// If the first stage is empty, popFront can swap the
	// first and second stages to remedy the situation.
	//
	// This two-stage split is analogous to the use of two lists
	// in Okasaki's purely functional queue but without the
	// overhead of reversing the list when swapping stages.
	head    []*wantConn
	headPos int
	tail    []*wantConn
}

// len returns the number of items in the queue.
func ( *wantConnQueue) () int {
	return len(.head) - .headPos + len(.tail)
}

// pushBack adds w to the back of the queue.
func ( *wantConnQueue) ( *wantConn) {
	.tail = append(.tail, )
}

// popFront removes and returns the wantConn at the front of the queue.
func ( *wantConnQueue) () *wantConn {
	if .headPos >= len(.head) {
		if len(.tail) == 0 {
			return nil
		}
		// Pick up tail as new head, clear tail.
		.head, .headPos, .tail = .tail, 0, .head[:0]
	}
	 := .head[.headPos]
	.head[.headPos] = nil
	.headPos++
	return 
}

// peekFront returns the wantConn at the front of the queue without removing it.
func ( *wantConnQueue) () *wantConn {
	if .headPos < len(.head) {
		return .head[.headPos]
	}
	if len(.tail) > 0 {
		return .tail[0]
	}
	return nil
}

// cleanFrontNotWaiting pops any wantConns that are no longer waiting from the head of the
// queue, reporting whether any were popped.
func ( *wantConnQueue) () ( bool) {
	for {
		 := .peekFront()
		if  == nil || .waiting() {
			return 
		}
		.popFront()
		 = true
	}
}

// cleanFrontCanceled pops any wantConns with canceled dials from the head of the queue.
func ( *wantConnQueue) () {
	for {
		 := .peekFront()
		if  == nil || .cancelCtx != nil {
			return
		}
		.popFront()
	}
}

// all iterates over all wantConns in the queue.
// The caller must not modify the queue while iterating.
func ( *wantConnQueue) ( func(*wantConn)) {
	for ,  := range .head[.headPos:] {
		()
	}
	for ,  := range .tail {
		()
	}
}

func ( *Transport) ( context.Context, ,  string) ( net.Conn,  error) {
	,  = .DialTLSContext(, , )

	if  == nil &&  == nil {
		 = errors.New("net/http: Transport.DialTLS or DialTLSContext returned (nil, nil)")
	}
	return
}

// getConn dials and creates a new persistConn to the target as
// specified in the connectMethod. This includes doing a proxy CONNECT
// and/or setting up TLS.  If this doesn't return an error, the persistConn
// is ready to write requests to.
func ( *Transport) ( *transportRequest,  connectMethod) ( *persistConn,  error) {
	 := .Request
	 := .trace
	 := .Context()
	if  != nil && .GetConn != nil {
		.GetConn(.addr())
	}

	// Detach from the request context's cancellation signal.
	// The dial should proceed even if the request is canceled,
	// because a future request may be able to make use of the connection.
	//
	// We retain the request context's values.
	,  := context.WithCancel(context.WithoutCancel())

	 := &wantConn{
		cm:         ,
		key:        .key(),
		ctx:        ,
		cancelCtx:  ,
		result:     make(chan connOrError, 1),
		beforeDial: testHookPrePendingDial,
		afterDial:  testHookPostPendingDial,
	}
	defer func() {
		if  != nil {
			.cancel(, )
		}
	}()

	// Queue for idle connection.
	if  := .queueForIdleConn(); ! {
		.queueForDial()
	}

	// Wait for completion or cancellation.
	select {
	case  := <-.result:
		// Trace success but only for HTTP/1.
		// HTTP/2 calls trace.GotConn itself.
		if .pc != nil && .pc.alt == nil &&  != nil && .GotConn != nil {
			 := httptrace.GotConnInfo{
				Conn:   .pc.conn,
				Reused: .pc.isReused(),
			}
			if !.idleAt.IsZero() {
				.WasIdle = true
				.IdleTime = time.Since(.idleAt)
			}
			.GotConn()
		}
		if .err != nil {
			// If the request has been canceled, that's probably
			// what caused r.err; if so, prefer to return the
			// cancellation error (see golang.org/issue/16049).
			select {
			case <-.ctx.Done():
				 := context.Cause(.ctx)
				if  == common.ErrRequestCanceled {
					 = errRequestCanceledConn
				}
				return nil, 
			default:
				// return below
			}
		}
		return .pc, .err
	case <-.ctx.Done():
		 := context.Cause(.ctx)
		if  == common.ErrRequestCanceled {
			 = errRequestCanceledConn
		}
		return nil, 
	}
}

// queueForDial queues w to wait for permission to begin dialing.
// Once w receives permission to dial, it will do so in a separate goroutine.
func ( *Transport) ( *wantConn) {
	.beforeDial()

	.connsPerHostMu.Lock()
	defer .connsPerHostMu.Unlock()

	if .MaxConnsPerHost <= 0 {
		.startDialConnForLocked()
		return
	}

	if  := .connsPerHost[.key];  < .MaxConnsPerHost {
		if .connsPerHost == nil {
			.connsPerHost = make(map[connectMethodKey]int)
		}
		.connsPerHost[.key] =  + 1
		.startDialConnForLocked()
		return
	}

	if .connsPerHostWait == nil {
		.connsPerHostWait = make(map[connectMethodKey]wantConnQueue)
	}
	 := .connsPerHostWait[.key]
	.cleanFrontNotWaiting()
	.pushBack()
	.connsPerHostWait[.key] = 
}

// startDialConnFor calls dialConn in a new goroutine.
// t.connsPerHostMu must be held.
func ( *Transport) ( *wantConn) {
	.dialsInProgress.cleanFrontCanceled()
	.dialsInProgress.pushBack()
	go func() {
		.dialConnFor()
		.connsPerHostMu.Lock()
		defer .connsPerHostMu.Unlock()
		.cancelCtx = nil
	}()
}

// dialConnFor dials on behalf of w and delivers the result to w.
// dialConnFor has received permission to dial w.cm and is counted in t.connCount[w.cm.key()].
// If the dial is canceled or unsuccessful, dialConnFor decrements t.connCount[w.cm.key()].
func ( *Transport) ( *wantConn) {
	defer .afterDial()
	 := .getCtxForDial()
	if  == nil {
		.decConnsPerHost(.key)
		return
	}

	,  := .dialConn(, .cm)
	 := .tryDeliver(, , time.Time{})
	if  == nil && (! || .alt != nil) {
		// pconn was not passed to w,
		// or it is HTTP/2 and can be shared.
		// Add to the idle connection pool.
		.putOrCloseIdleConn()
	}
	if  != nil {
		.decConnsPerHost(.key)
	}
}

// decConnsPerHost decrements the per-host connection count for key,
// which may in turn give a different waiting goroutine permission to dial.
func ( *Transport) ( connectMethodKey) {
	if .MaxConnsPerHost <= 0 {
		return
	}

	.connsPerHostMu.Lock()
	defer .connsPerHostMu.Unlock()
	 := .connsPerHost[]
	if  == 0 {
		// Shouldn't happen, but if it does, the counting is buggy and could
		// easily lead to a silent deadlock, so report the problem loudly.
		panic("net/http: internal error: connCount underflow")
	}

	// Can we hand this count to a goroutine still waiting to dial?
	// (Some goroutines on the wait list may have timed out or
	// gotten a connection another way. If they're all gone,
	// we don't want to kick off any spurious dial operations.)
	if  := .connsPerHostWait[]; .len() > 0 {
		 := false
		for .len() > 0 {
			 := .popFront()
			if .waiting() {
				.startDialConnForLocked()
				 = true
				break
			}
		}
		if .len() == 0 {
			delete(.connsPerHostWait, )
		} else {
			// q is a value (like a slice), so we have to store
			// the updated q back into the map.
			.connsPerHostWait[] = 
		}
		if  {
			return
		}
	}

	// Otherwise, decrement the recorded count.
	if --;  == 0 {
		delete(.connsPerHost, )
	} else {
		.connsPerHost[] = 
	}
}

// Add TLS to a persistent connection, i.e. negotiate a TLS session. If pconn is already a TLS
// tunnel, this function establishes a nested TLS session inside the encrypted channel.
// The remote endpoint's name may be overridden by TLSClientConfig.ServerName.
func ( *persistConn) ( context.Context,  string,  *httptrace.ClientTrace,  bool) error {
	// Initiate TLS and check remote host name against certificate.
	 := cloneTLSConfig(.t.TLSClientConfig)
	if .ServerName == "" {
		.ServerName = 
	}
	if .cacheKey.onlyH1 {
		.NextProtos = nil
	}
	 := .conn
	 := tls.Client(, )
	 := make(chan error, 2)
	var  *time.Timer // for canceling TLS handshake
	if  := .t.TLSHandshakeTimeout;  != 0 {
		 = time.AfterFunc(, func() {
			 <- tlsHandshakeTimeoutError{}
		})
	}
	go func() {
		if  != nil && .TLSHandshakeStart != nil {
			.TLSHandshakeStart()
		}
		 := .HandshakeContext()
		if  != nil {
			.Stop()
		}
		 <- 
	}()
	if  := <-;  != nil {
		.Close()
		if  == (tlsHandshakeTimeoutError{}) {
			// Now that we have closed the connection,
			// wait for the call to HandshakeContext to return.
			<-
		}
		if  != nil && .TLSHandshakeDone != nil {
			.TLSHandshakeDone(tls.ConnectionState{}, )
		}
		return 
	}
	 := .ConnectionState()
	if  != nil && .TLSHandshakeDone != nil {
		.TLSHandshakeDone(, nil)
	}
	.tlsState = &
	.conn = 
	if ! && .t.forceHttpVersion == h2 && .NegotiatedProtocol != h2internal.NextProtoTLS {
		return newHttp2NotSupportedError(.NegotiatedProtocol)
	}
	return nil
}

func newHttp2NotSupportedError( string) error {
	 := "server does not support http2"
	if  != "" {
		 += fmt.Sprintf(", you can use %s which is supported", )
	}
	return errors.New()
}

func ( *Transport) ( context.Context,  *httptrace.ClientTrace,  string,  *persistConn) error {
	 := make(chan error, 2)
	var  *time.Timer // for canceling TLS handshake
	if  := .TLSHandshakeTimeout;  != 0 {
		 = time.AfterFunc(, func() {
			 <- tlsHandshakeTimeoutError{}
		})
	}
	go func() {
		if  != nil && .TLSHandshakeStart != nil {
			.TLSHandshakeStart()
		}
		, ,  := .TLSHandshakeContext(, , .conn)
		if  != nil {
			if  != nil {
				.Stop()
			}
			if  != nil && .TLSHandshakeDone != nil {
				.TLSHandshakeDone(tls.ConnectionState{}, )
			}
		} else {
			.conn = 
			.tlsState = 
			if  != nil && .TLSHandshakeDone != nil {
				.TLSHandshakeDone(*, nil)
			}
		}
		 <- 
	}()
	if  := <-;  != nil {
		.conn.Close()
		return 
	}
	return nil
}

var testHookProxyConnectTimeout = context.WithTimeout

func ( *Transport) ( context.Context,  connectMethod) ( *persistConn,  error) {
	 = &persistConn{
		t:             ,
		cacheKey:      .key(),
		reqch:         make(chan requestAndChan, 1),
		writech:       make(chan writeRequest, 1),
		closech:       make(chan struct{}),
		writeErrCh:    make(chan error, 1),
		writeLoopDone: make(chan struct{}),
	}
	 := httptrace.ContextClientTrace()
	 := func( error) error {
		if .proxyURL != nil {
			// Return a typed error, per Issue 16997
			return &net.OpError{Op: "proxyconnect", Net: "tcp", Err: }
		}
		return 
	}
	if .scheme() == "https" && .hasCustomTLSDialer() {
		var  error
		.conn,  = .customDialTLS(, "tcp", .addr())
		if  != nil {
			return nil, ()
		}
		if ,  := .conn.(reqtls.Conn);  {
			// Handshake here, in case DialTLS didn't. TLSNextProto below
			// depends on it for knowing the connection state.
			if  != nil && .TLSHandshakeStart != nil {
				.TLSHandshakeStart()
			}
			if  := .HandshakeContext();  != nil {
				go .conn.Close()
				if  != nil && .TLSHandshakeDone != nil {
					.TLSHandshakeDone(tls.ConnectionState{}, )
				}
				return nil, 
			}
			 := .ConnectionState()
			if  != nil && .TLSHandshakeDone != nil {
				.TLSHandshakeDone(, nil)
			}
			.tlsState = &
			if .proxyURL == nil && .t.forceHttpVersion == h2 && .NegotiatedProtocol != h2internal.NextProtoTLS {
				return nil, newHttp2NotSupportedError(.NegotiatedProtocol)
			}
		}
	} else {
		,  := .dial(, "tcp", .addr())
		if  != nil {
			return nil, ()
		}
		.conn = 
		if .scheme() == "https" {
			var  string
			if , _,  = net.SplitHostPort(.addr());  != nil {
				return nil, ()
			}
			if .TLSHandshakeContext != nil && .proxyURL == nil {
				 = .customTlsHandshake(, , , )
				if  != nil {
					return nil, 
				}
			} else {
				if  = .addTLS(, , , .proxyURL != nil);  != nil {
					return nil, ()
				}
			}
		}
	}

	if .Debugf != nil && .proxyURL != nil {
		.Debugf("connect %s via proxy %s", .targetAddr, .proxyURL.String())
	}

	// Proxy setup.
	switch {
	case .proxyURL == nil:
		// Do nothing. Not using a proxy.
	case .proxyURL.Scheme == "socks5" || .proxyURL.Scheme == "socks5h":
		 := .conn
		 := socks.NewDialer("tcp", .RemoteAddr().String())
		if  := .proxyURL.User;  != nil {
			 := &socks.UsernamePassword{
				Username: .Username(),
			}
			.Password, _ = .Password()
			.AuthMethods = []socks.AuthMethod{
				socks.AuthMethodNotRequired,
				socks.AuthMethodUsernamePassword,
			}
			.Authenticate = .Authenticate
		}
		if ,  := .DialWithConn(, , "tcp", .targetAddr);  != nil {
			.Close()
			return nil, 
		}
	case .proxyURL.Scheme == "socks4" || .proxyURL.Scheme == "socks4a":
		 := .conn
		 := socks.NewDialer("tcp", .RemoteAddr().String())
		.Version = socks.Version4
		.Socks4A = .proxyURL.Scheme == "socks4a"
		if  := .proxyURL.User;  != nil {
			.UserID = .Username()
		}
		if ,  := .DialWithConn(, , "tcp", .targetAddr);  != nil {
			.Close()
			return nil, 
		}
	case .targetScheme == "http":
		.isProxy = true
		if  := .proxyAuth();  != "" {
			.mutateHeaderFunc = func( http.Header) {
				.Set("Proxy-Authorization", )
			}
		}
	case .targetScheme == "https":
		 := .conn
		var  http.Header
		if .GetProxyConnectHeader != nil {
			var  error
			,  = .GetProxyConnectHeader(, .proxyURL, .targetAddr)
			if  != nil {
				.Close()
				return nil, 
			}
		} else {
			 = .ProxyConnectHeader
		}
		if  == nil {
			 = make(http.Header)
		}
		if  := .proxyAuth();  != "" {
			 = .Clone()
			.Set("Proxy-Authorization", )
		}
		 := &http.Request{
			Method: "CONNECT",
			URL:    &url.URL{Opaque: .targetAddr},
			Host:   .targetAddr,
			Header: ,
		}

		// Set a (long) timeout here to make sure we don't block forever
		// and leak a goroutine if the connection stops replying after
		// the TCP connect.
		,  := testHookProxyConnectTimeout(, 1*time.Minute)
		defer ()

		 := make(chan struct{}) // closed after CONNECT write+read is done or fails
		var (
			 *http.Response
			  error // write or read error
		)
		// Write the CONNECT request & read the response.
		go func() {
			defer close()
			 = .Write()
			if  != nil {
				return
			}
			// Okay to use and discard buffered reader here, because
			// TLS server will not speak until spoken to.
			 := bufio.NewReader()
			,  = http.ReadResponse(, )
		}()
		select {
		case <-.Done():
			.Close()
			<-
			return nil, .Err()
		case <-:
			// resp or err now set
		}
		if  != nil {
			.Close()
			return nil, 
		}

		if .OnProxyConnectResponse != nil {
			 = .OnProxyConnectResponse(, .proxyURL, , )
			if  != nil {
				.Close()
				return nil, 
			}
		}

		if .StatusCode != 200 {
			, ,  := util.CutString(.Status, " ")
			.Close()
			if ! {
				return nil, errors.New("unknown status code")
			}
			return nil, errors.New()
		}
	}

	if .proxyURL != nil && .targetScheme == "https" {
		if .TLSHandshakeContext != nil {
			 := .customTlsHandshake(, , .tlsHost(), )
			if  != nil {
				return nil, 
			}
		} else {
			if  := .addTLS(, .tlsHost(), , false);  != nil {
				return nil, 
			}
		}
	}

	if  := .tlsState; .forceHttpVersion != h1 &&  != nil && .NegotiatedProtocolIsMutual && .NegotiatedProtocol != "" {
		if .NegotiatedProtocol == h2internal.NextProtoTLS {
			if ,  := .t2.AddConn(.conn, .targetAddr);  != nil {
				go .conn.Close()
				return nil, 
			} else if ! {
				go .conn.Close()
			}
			return &persistConn{t: , cacheKey: .cacheKey, alt: .t2}, nil
		}
	}

	.br = bufio.NewReaderSize(, .readBufferSize())
	.bw = bufio.NewWriterSize(persistConnWriter{}, .writeBufferSize())

	go .readLoop()
	go .writeLoop()
	return , nil
}

// persistConnWriter is the io.Writer written to by pc.bw.
// It accumulates the number of bytes written to the underlying conn,
// so the retry logic can determine whether any bytes made it across
// the wire.
// This is exactly 1 pointer field wide so it can go into an interface
// without allocation.
type persistConnWriter struct {
	pc *persistConn
}

func ( persistConnWriter) ( []byte) ( int,  error) {
	,  = .pc.conn.Write()
	.pc.nwrite += int64()
	return
}

// ReadFrom exposes persistConnWriter's underlying Conn to io.Copy and if
// the Conn implements io.ReaderFrom, it can take advantage of optimizations
// such as sendfile.
func ( persistConnWriter) ( io.Reader) ( int64,  error) {
	,  = io.Copy(.pc.conn, )
	.pc.nwrite += 
	return
}

var _ io.ReaderFrom = (*persistConnWriter)(nil)

// connectMethod is the map key (in its String form) for keeping persistent
// TCP connections alive for subsequent HTTP requests.
//
// A connect method may be of the following types:
//
//	connectMethod.key().String()      Description
//	------------------------------    -------------------------
//	|http|foo.com                     http directly to server, no proxy
//	|https|foo.com                    https directly to server, no proxy
//	|https,h1|foo.com                 https directly to server w/o HTTP/2, no proxy
//	http://proxy.com|https|foo.com    http to proxy, then CONNECT to foo.com
//	http://proxy.com|http             http to proxy, http to anywhere after that
//	socks5://proxy.com|http|foo.com   socks5 to proxy, then http to foo.com
//	socks5://proxy.com|https|foo.com  socks5 to proxy, then https to foo.com
//	socks4://proxy.com|http|foo.com   socks4 to proxy, then http to foo.com
//	socks4a://proxy.com|https|foo.com socks4a to proxy, then https to foo.com
//	https://proxy.com|https|foo.com   https to proxy, then CONNECT to foo.com
//	https://proxy.com|http            https to proxy, http to anywhere after that
type connectMethod struct {
	_            incomparable
	proxyURL     *url.URL // nil for no proxy, else full proxy URL
	targetScheme string   // "http" or "https"
	// If proxyURL specifies an http or https proxy, and targetScheme is http (not https),
	// then targetAddr is not included in the connect method key, because the socket can
	// be reused for different targetAddr values.
	targetAddr string
	onlyH1     bool // whether to disable HTTP/2 and force HTTP/1
}

func ( *connectMethod) () connectMethodKey {
	 := ""
	 := .targetAddr
	if .proxyURL != nil {
		 = .proxyURL.String()
		if (.proxyURL.Scheme == "http" || .proxyURL.Scheme == "https") && .targetScheme == "http" {
			 = ""
		}
	}
	return connectMethodKey{
		proxy:  ,
		scheme: .targetScheme,
		addr:   ,
		onlyH1: .onlyH1,
	}
}

// scheme returns the first hop scheme: http, https, socks5, socks5h, socks4, or socks4a
func ( *connectMethod) () string {
	if .proxyURL != nil {
		return .proxyURL.Scheme
	}
	return .targetScheme
}

// addr returns the first hop "host:port" to which we need to TCP connect.
func ( *connectMethod) () string {
	if .proxyURL != nil {
		return canonicalAddr(.proxyURL)
	}
	return .targetAddr
}

// tlsHost returns the host name to match against the peer's
// TLS certificate.
func ( *connectMethod) () string {
	 := .targetAddr
	if hasPort() {
		 = [:strings.LastIndex(, ":")]
	}
	return 
}

// connectMethodKey is the map key version of connectMethod, with a
// stringified proxy URL (or the empty string) instead of a pointer to
// a URL.
type connectMethodKey struct {
	proxy, scheme, addr string
	onlyH1              bool
}

func ( connectMethodKey) () string {
	// Only used by tests.
	var  string
	if .onlyH1 {
		 = ",h1"
	}
	return fmt.Sprintf("%s|%s%s|%s", .proxy, .scheme, , .addr)
}

// persistConn wraps a connection, usually a persistent one
// (but may be used for non-keep-alive requests as well)
type persistConn struct {
	// alt optionally specifies the TLS NextProto http.RoundTripper.
	// This is used for HTTP/2 today and future protocols later.
	// If it's non-nil, the rest of the fields are unused.
	alt http.RoundTripper

	t         *Transport
	cacheKey  connectMethodKey
	conn      net.Conn
	tlsState  *tls.ConnectionState
	br        *bufio.Reader       // from conn
	bw        *bufio.Writer       // to conn
	nwrite    int64               // bytes written
	reqch     chan requestAndChan // written by roundTrip; read by readLoop
	writech   chan writeRequest   // written by roundTrip; read by writeLoop
	closech   chan struct{}       // closed when conn closed
	isProxy   bool
	sawEOF    bool  // whether we've seen EOF from conn; owned by readLoop
	readLimit int64 // bytes allowed to be read; owned by readLoop
	// writeErrCh passes the request write error (usually nil)
	// from the writeLoop goroutine to the readLoop which passes
	// it off to the res.Body reader, which then uses it to decide
	// whether or not a connection can be reused. Issue 7569.
	writeErrCh chan error

	writeLoopDone chan struct{} // closed when write loop ends

	// Both guarded by Transport.idleMu:
	idleAt    time.Time   // time it last become idle
	idleTimer *time.Timer // holding an AfterFunc to close it

	mu                   sync.Mutex // guards following fields
	numExpectedResponses int
	closed               error // set non-nil when conn is closed, before closech is closed
	canceledErr          error // set non-nil if conn is canceled
	broken               bool  // an error has happened on this connection; marked broken so it's not reused.
	reused               bool  // whether conn has had successful request/response and is being reused.
	// mutateHeaderFunc is an optional func to modify extra
	// headers on each outbound request before it's written. (the
	// original Request given to RoundTrip is not modified)
	mutateHeaderFunc func(http.Header)
}

// RFC 7234, section 5.4: Should treat
//
//	Pragma: no-cache
//
// like
//
//	Cache-Control: no-cache
func fixPragmaCacheControl( http.Header) {
	if ,  := ["Pragma"];  && len() > 0 && [0] == "no-cache" {
		if ,  := ["Cache-Control"]; ! {
			["Cache-Control"] = []string{"no-cache"}
		}
	}
}

// readResponse reads an HTTP response (or two, in the case of "Expect:
// 100-continue") from the server. It returns the final non-100 one.
// trace is optional.
func ( *persistConn) ( *http.Request) (*http.Response, error) {
	 := dump.GetResponseHeaderDumpers(.Context(), .t.Dump)
	 := newTextprotoReader(.br, )
	 := &http.Response{
		Request: ,
	}

	// Parse the first line of the response.
	,  := .ReadLine()
	if  != nil {
		if  == io.EOF {
			 = io.ErrUnexpectedEOF
		}
		return nil, 
	}
	, ,  := util.CutString(, " ")
	if ! {
		return nil, badStringError("malformed HTTP response", )
	}
	.Proto = 
	.Status = strings.TrimLeft(, " ")

	, ,  := util.CutString(.Status, " ")
	if len() != 3 {
		return nil, badStringError("malformed HTTP status code", )
	}
	.StatusCode,  = strconv.Atoi()
	if  != nil || .StatusCode < 0 {
		return nil, badStringError("malformed HTTP status code", )
	}
	if .ProtoMajor, .ProtoMinor,  = http.ParseHTTPVersion(.Proto); ! {
		return nil, badStringError("malformed HTTP version", .Proto)
	}

	// Parse the response headers.
	,  := .ReadMIMEHeader()
	if  != nil {
		if  == io.EOF {
			 = io.ErrUnexpectedEOF
		}
		return nil, 
	}
	.Header = http.Header()

	fixPragmaCacheControl(.Header)

	 = readTransfer(, .br)
	if  != nil {
		return nil, 
	}

	return , nil
}

func ( *persistConn) () int64 {
	if  := .t.MaxResponseHeaderBytes;  != 0 {
		return 
	}
	return 10 << 20 // conservative default; same as http2
}

func ( *persistConn) ( []byte) ( int,  error) {
	if .readLimit <= 0 {
		return 0, fmt.Errorf("read limit of %d bytes exhausted", .maxHeaderResponseSize())
	}
	if int64(len()) > .readLimit {
		 = [:.readLimit]
	}
	,  = .conn.Read()
	if  == io.EOF {
		.sawEOF = true
	}
	.readLimit -= int64()
	return
}

// isBroken reports whether this connection is in a known broken state.
func ( *persistConn) () bool {
	.mu.Lock()
	 := .closed != nil
	.mu.Unlock()
	return 
}

// canceled returns non-nil if the connection was closed due to
// CancelRequest or due to context cancellation.
func ( *persistConn) () error {
	.mu.Lock()
	defer .mu.Unlock()
	return .canceledErr
}

// isReused reports whether this connection has been used before.
func ( *persistConn) () bool {
	.mu.Lock()
	 := .reused
	.mu.Unlock()
	return 
}

func ( *persistConn) ( error) {
	.mu.Lock()
	defer .mu.Unlock()
	.canceledErr = 
	.closeLocked(common.ErrRequestCanceled)
}

// closeConnIfStillIdle closes the connection if it's still sitting idle.
// This is what's called by the persistConn's idleTimer, and is run in its
// own goroutine.
func ( *persistConn) () {
	 := .t
	.idleMu.Lock()
	defer .idleMu.Unlock()
	if ,  := .idleLRU.m[]; ! {
		// Not idle.
		return
	}
	.removeIdleConnLocked()
	.close(errIdleConnTimeout)
}

// mapRoundTripError returns the appropriate error value for
// persistConn.roundTrip.
//
// The provided err is the first error that (*persistConn).roundTrip
// happened to receive from its select statement.
//
// The startBytesWritten value should be the value of pc.nwrite before the roundTrip
// started writing the request.
func ( *persistConn) ( *transportRequest,  int64,  error) error {
	if  == nil {
		return nil
	}

	// Wait for the writeLoop goroutine to terminate to avoid data
	// races on callers who mutate the request on failure.
	//
	// When resc in pc.roundTrip and hence rc.ch receives a responseAndError
	// with a non-nil error it implies that the persistConn is either closed
	// or closing. Waiting on pc.writeLoopDone is hence safe as all callers
	// close closech which in turn ensures writeLoop returns.
	<-.writeLoopDone

	// If the request was canceled, that's better than network
	// failures that were likely the result of tearing down the
	// connection.
	if  := .canceled();  != nil {
		return 
	}

	// See if an error was set explicitly.
	.mu.Lock()
	 := .err
	.mu.Unlock()
	if  != nil {
		return 
	}

	if  == errServerClosedIdle {
		// Don't decorate
		return 
	}

	if ,  := .(transportReadFromServerError);  {
		if .nwrite ==  {
			return nothingWrittenError{}
		}
		// Don't decorate
		return 
	}
	if .isBroken() {
		if .nwrite ==  {
			return nothingWrittenError{}
		}
		return fmt.Errorf("net/http: HTTP/1.x transport connection broken: %w", )
	}
	return 
}

// errCallerOwnsConn is an internal sentinel error used when we hand
// off a writable response.Body to the caller. We use this to prevent
// closing a net.Conn that is now owned by the caller.
var errCallerOwnsConn = errors.New("read loop ending; caller owns writable underlying conn")

func ( *persistConn) () {
	 := errReadLoopExiting // default value, if not changed below
	defer func() {
		.close()
		.t.removeIdleConn()
	}()

	 := func( *transportRequest) bool {
		 := .trace
		if  := .t.tryPutIdleConn();  != nil {
			 = 
			if  != nil && .PutIdleConn != nil &&  != errKeepAlivesDisabled {
				.PutIdleConn()
			}
			return false
		}
		if  != nil && .PutIdleConn != nil {
			.PutIdleConn(nil)
		}
		return true
	}

	// eofc is used to block caller goroutines reading from Response.Body
	// at EOF until this goroutines has (potentially) added the connection
	// back to the idle pool.
	 := make(chan struct{})
	defer close() // unblock reader on errors

	// Read this once, before loop starts. (to avoid races in tests)
	testHookMu.Lock()
	 := testHookReadLoopBeforeNextRead
	testHookMu.Unlock()

	 := true
	for  {
		.readLimit = .maxHeaderResponseSize()
		,  := .br.Peek(1)

		.mu.Lock()
		if .numExpectedResponses == 0 {
			.readLoopPeekFailLocked()
			.mu.Unlock()
			return
		}
		.mu.Unlock()

		 := <-.reqch
		 := .treq.trace

		var  *http.Response
		if  == nil {
			,  = .readResponse(, )
		} else {
			 = transportReadFromServerError{}
			 = 
		}

		if  != nil {
			if .readLimit <= 0 {
				 = fmt.Errorf("net/http: server response headers exceeded %d bytes; aborted", .maxHeaderResponseSize())
			}

			select {
			case .ch <- responseAndError{err: }:
			case <-.callerGone:
				return
			}
			return
		}
		.readLimit = maxInt64 // effectively no limit for response bodies

		.mu.Lock()
		.numExpectedResponses--
		.mu.Unlock()

		 := bodyIsWritable()
		 := .treq.Request.Method != "HEAD" && .ContentLength != 0

		if .Close || .treq.Request.Close || .StatusCode <= 199 ||  {
			// Don't do keep-alive on error if either party requested a close
			// or we get an unexpected informational (1xx) response.
			// StatusCode 100 is already handled above.
			 = false
		}

		if ! ||  {
			// Put the idle conn back into the pool before we send the response
			// so if they process it quickly and make another request, they'll
			// get this same conn. But we use the unbuffered channel 'rc'
			// to guarantee that persistConn.roundTrip got out of its select
			// potentially waiting for this persistConn to close.
			 =  &&
				!.sawEOF &&
				.wroteRequest() &&
				(.treq)

			if  {
				 = errCallerOwnsConn
			}

			select {
			case .ch <- responseAndError{res: }:
			case <-.callerGone:
				return
			}

			.treq.cancel(errRequestDone)

			// Now that they've read from the unbuffered channel, they're safely
			// out of the select that also waits on this goroutine to die, so
			// we're allowed to exit now if needed (if alive is false)
			()
			continue
		}

		 := make(chan bool, 2)
		 := &bodyEOFSignal{
			body: .Body,
			earlyCloseFn: func() error {
				 <- false
				<- // will be closed by deferred call at the end of the function
				return nil
			},
			fn: func( error) error {
				 :=  == io.EOF
				 <- 
				if  {
					<- // see comment above eofc declaration
				} else if  != nil {
					if  := .canceled();  != nil {
						return 
					}
				}
				return 
			},
		}

		.Body = 
		if .addedGzip && ascii.EqualFold(.Header.Get("Content-Encoding"), "gzip") {
			.Body = &gzipReader{body: }
			.Header.Del("Content-Encoding")
			.Header.Del("Content-Length")
			.ContentLength = -1
			.Uncompressed = true
		} else if .t.AutoDecompression {
			 := .Header.Get("Content-Encoding")
			if  != "" {
				.Header.Del("Content-Encoding")
				.Header.Del("Content-Length")
				.ContentLength = -1
				.Uncompressed = true
				.Body = compress.NewCompressReader(.Body, )
			}
		}

		select {
		case .ch <- responseAndError{res: }:
		case <-.callerGone:
			return
		}

		// Before looping back to the top of this function and peeking on
		// the bufio.Reader, wait for the caller goroutine to finish
		// reading the response body. (or for cancellation or death)
		select {
		case  := <-:
			 =  &&
				 &&
				!.sawEOF &&
				.wroteRequest() &&
				(.treq)
			if  {
				 <- struct{}{}
			}
		case <-.treq.ctx.Done():
			 = false
			.cancelRequest(context.Cause(.treq.ctx))
		case <-.closech:
			 = false
		}

		.treq.cancel(errRequestDone)
		()
	}
}

func ( *persistConn) ( error) {
	if .closed != nil {
		return
	}
	if  := .br.Buffered();  > 0 {
		,  := .br.Peek()
		if is408Message() {
			.closeLocked(errServerClosedIdle)
			return
		}
		log.Printf("Unsolicited response received on idle HTTP channel starting with %q; err=%v", , )
	}
	if  == io.EOF {
		// common case.
		.closeLocked(errServerClosedIdle)
	} else {
		.closeLocked(fmt.Errorf("readLoopPeekFailLocked: %w", ))
	}
}

// is408Message reports whether buf has the prefix of an
// HTTP 408 Request Timeout response.
// See golang.org/issue/32310.
func is408Message( []byte) bool {
	if len() < len("HTTP/1.x 408") {
		return false
	}
	if string([:7]) != "HTTP/1." {
		return false
	}
	return string([8:12]) == " 408"
}

// readResponse reads an HTTP response (or two, in the case of "Expect:
// 100-continue") from the server. It returns the final non-100 one.
// trace is optional.
func ( *persistConn) ( requestAndChan,  *httptrace.ClientTrace) ( *http.Response,  error) {
	if  != nil && .GotFirstResponseByte != nil {
		if ,  := .br.Peek(1);  == nil && len() == 1 {
			.GotFirstResponseByte()
		}
	}
	 := 0               // number of informational 1xx headers received
	const  = 5 // arbitrary bound on number of informational responses

	 := .continueCh
	for {
		,  = ._readResponse(.treq.Request)
		if  != nil {
			return
		}
		 := .StatusCode
		if  != nil &&  == http.StatusContinue {
			if  != nil && .Got100Continue != nil {
				.Got100Continue()
			}
			 <- struct{}{}
			 = nil
		}
		 := 100 <=  &&  <= 199
		// treat 101 as a terminal status, see issue 26161
		 :=  &&  != http.StatusSwitchingProtocols

		if  {
			++
			if  >  {
				return nil, errors.New("net/http: too many 1xx informational responses")
			}
			.readLimit = .maxHeaderResponseSize() // reset the limit
			if  != nil && .Got1xxResponse != nil {
				if  := .Got1xxResponse(, textproto.MIMEHeader(.Header));  != nil {
					return nil, 
				}
			}
			continue
		}
		break
	}
	if isProtocolSwitch() {
		.Body = newReadWriteCloserBody(.br, .conn)
	}
	if  != nil {
		// We send an "Expect: 100-continue" header, but the server
		// responded with a terminal status and no 100 Continue.
		//
		// If we're going to keep using the connection, we need to send the request body.
		// Tell writeLoop to skip sending the body if we're going to close the connection,
		// or to send it otherwise.
		//
		// The case where we receive a 101 Switching Protocols response is a bit
		// ambiguous, since we don't know what protocol we're switching to.
		// Conceivably, it's one that doesn't need us to send the body.
		// Given that we'll send the body if ExpectContinueTimeout expires,
		// be consistent and always send it if we aren't closing the connection.
		if .Close || .treq.Request.Close {
			close() // don't send the body; the connection will close
		} else {
			 <- struct{}{} // send the body
		}
	}

	.TLS = .tlsState
	return
}

// waitForContinue returns the function to block until
// any response, timeout or connection close. After any of them,
// the function returns a bool which indicates if the body should be sent.
func ( *persistConn) ( <-chan struct{}) func() bool {
	if  == nil {
		return nil
	}
	return func() bool {
		 := time.NewTimer(.t.ExpectContinueTimeout)
		defer .Stop()

		select {
		case ,  := <-:
			return 
		case <-.C:
			return true
		case <-.closech:
			return false
		}
	}
}

func newReadWriteCloserBody( *bufio.Reader,  io.ReadWriteCloser) io.ReadWriteCloser {
	 := &readWriteCloserBody{ReadWriteCloser: }
	if .Buffered() != 0 {
		.br = 
	}
	return 
}

// readWriteCloserBody is the Response.Body type used when we want to
// give users write access to the Body through the underlying
// connection (TCP, unless using custom dialers). This is then
// the concrete type for a Response.Body on the 101 Switching
// Protocols response, as used by WebSockets, h2c, etc.
type readWriteCloserBody struct {
	_  incomparable
	br *bufio.Reader // used until empty
	io.ReadWriteCloser
}

func ( *readWriteCloserBody) ( []byte) ( int,  error) {
	if .br != nil {
		if  := .br.Buffered(); len() >  {
			 = [:]
		}
		,  = .br.Read()
		if .br.Buffered() == 0 {
			.br = nil
		}
		return , 
	}
	return .ReadWriteCloser.Read()
}

// nothingWrittenError wraps a write errors which ended up writing zero bytes.
type nothingWrittenError struct {
	error
}

func ( nothingWrittenError) () error {
	return .error
}

func ( *persistConn) () {
	defer close(.writeLoopDone)
	for {
		select {
		case  := <-.writech:
			 := .nwrite
			 := .writeRequest(.req.Request, .bw, .isProxy, .req.extra, .waitForContinue(.continueCh))
			if ,  := .(requestBodyReadError);  {
				 = .error
				// Errors reading from the user's
				// Request.Body are high priority.
				// Set it here before sending on the
				// channels below or calling
				// pc.close() which tears down
				// connections and causes other
				// errors.
				.req.setError()
			}
			if  == nil {
				 = .bw.Flush()
			}
			if  != nil {
				if .nwrite ==  {
					 = nothingWrittenError{}
				}
			}
			.writeErrCh <-  // to the body reader, which might recycle us
			.ch <-          // to the roundTrip function
			if  != nil {
				.close()
				return
			}
		case <-.closech:
			return
		}
	}
}

// extraHeaders may be nil
// waitForContinue may be nil
// always closes body
func ( *persistConn) ( *http.Request,  io.Writer,  bool,  http.Header,  func() bool) ( error) {
	 := httptrace.ContextClientTrace(.Context())
	if  != nil && .WroteRequest != nil {
		defer func() {
			.WroteRequest(httptrace.WroteRequestInfo{
				Err: ,
			})
		}()
	}
	 := false
	defer func() {
		if  {
			return
		}
		if  := closeRequestBody();  != nil &&  == nil {
			 = 
		}
	}()

	// Find the target host. Prefer the Host: header, but if that
	// is not given, use the host from the request URL.
	//
	// Clean the host, in case it arrives with unexpected stuff in it.
	 := .Host
	if  == "" {
		if .URL == nil {
			return errMissingHost
		}
		 = .URL.Host
	}
	,  = httpguts.PunycodeHostPort()
	if  != nil {
		return 
	}

	// Validate that the Host header is a valid header in general,
	// but don't validate the host itself. This is sufficient to avoid
	// header or request smuggling via the Host field.
	// The server can (and will, if it's a net/http server) reject
	// the request if it doesn't consider the host valid.
	if !httpguts.ValidHostHeader() {
		// Historically, we would truncate the Host header after '/' or ' '.
		// Some users have relied on this truncation to convert a network
		// address such as Unix domain socket path into a valid, ignored
		// Host header (see https://go.dev/issue/61431).
		//
		// We don't preserve the truncation, because sending an altered
		// header field opens a smuggling vector. Instead, zero out the
		// Host header entirely if it isn't valid. (An empty Host is valid;
		// see RFC 9112 Section 3.2.)
		//
		// Return an error if we're sending to a proxy, since the proxy
		// probably can't do anything useful with an empty Host header.
		if ! {
			 = ""
		} else {
			return errors.New("http: invalid Host header")
		}
	}

	// According to RFC 6874, an HTTP client, proxy, or other
	// intermediary must remove any IPv6 zone identifier attached
	// to an outgoing URI.
	 = removeZone()

	 := .URL.RequestURI()
	if  && .URL.Scheme != "" && .URL.Opaque == "" {
		 = .URL.Scheme + "://" +  + 
	} else if .Method == "CONNECT" && .URL.Path == "" {
		// CONNECT requests normally give just the host and port, not a full URL.
		 = 
		if .URL.Opaque != "" {
			 = .URL.Opaque
		}
	}
	if stringContainsCTLByte() {
		return errors.New("net/http: can't write control character in Request.URL")
	}
	// TODO: validate r.Method too? At least it's less likely to
	// come from an attacker (more likely to be a constant in
	// code).

	// Wrap the writer in a bufio Writer if it's not already buffered.
	// Don't always call NewWriter, as that forces a bytes.Buffer
	// and other small bufio Writers to have a minimum 4k buffer
	// size.
	var  *bufio.Writer
	if ,  := .(io.ByteWriter); ! {
		 = bufio.NewWriter()
		 = 
	}

	 :=  // raw writer
	 := dump.GetDumpers(.Context(), .t.Dump)
	for ,  := range  {
		if .RequestHeader() {
			 = .WrapRequestHeaderWriter()
		}
	}

	_,  = fmt.Fprintf(, "%s %s HTTP/1.1\r\n", valueOrDefault(.Method, "GET"), )
	if  != nil {
		return 
	}

	 := func( string,  ...string) error {
		for ,  := range  {
			,  := fmt.Fprintf(, "%s: %s\r\n", , )
			if  != nil {
				return 
			}
		}
		if  != nil && .WroteHeaderField != nil {
			.WroteHeaderField(, )
		}
		return nil
	}

	var  func( string,  ...string) error
	var  []header.KeyValues
	 := false

	if .Header != nil && len(.Header[header.HeaderOderKey]) > 0 {
		 = func( string,  ...string) error {
			 = append(, header.KeyValues{
				Key:    ,
				Values: ,
			})
			return nil
		}
		 = true
	} else {
		 = 
	}
	// Header lines
	 = ("Host", )
	if  != nil {
		return 
	}

	// Use the defaultUserAgent unless the Header contains one, which
	// may be blank to not send the header.
	 := header.DefaultUserAgent
	if headerHas(.Header, "User-Agent") {
		 = .Header.Get("User-Agent")
	}
	if  != "" {
		 = ("User-Agent", )
		if  != nil {
			return 
		}
	}

	// Process Body,ContentLength,Close,Trailer
	,  := newTransferWriter()
	if  != nil {
		return 
	}
	 = .writeHeader()
	if  != nil {
		return 
	}

	 = headerWriteSubset(.Header, reqWriteExcludeHeader, , )
	if  != nil {
		return 
	}

	if  != nil {
		 = headerWrite(, , )
		if  != nil {
			return 
		}
	}

	if  { // sort and write headers
		header.SortKeyValues(, .Header[header.HeaderOderKey])
		for ,  := range  {
			(.Key, .Values...)
		}
	}

	_,  = io.WriteString(, "\r\n")
	if  != nil {
		return 
	}

	if  != nil && .WroteHeaders != nil {
		.WroteHeaders()
	}

	// Flush and wait for 100-continue if expected.
	if  != nil {
		if ,  := .(*bufio.Writer);  {
			 = .Flush()
			if  != nil {
				return 
			}
		}
		if  != nil && .Wait100Continue != nil {
			.Wait100Continue()
		}
		if !() {
			 = true
			closeRequestBody()
			return nil
		}
	}

	if ,  := .(*bufio.Writer);  && .FlushHeaders {
		if  := .Flush();  != nil {
			return 
		}
	}

	// Write body and trailer
	 = true
	 = .writeBody(, )
	if  != nil {
		if .bodyReadError ==  {
			 = requestBodyReadError{}
		}
		return 
	}

	if  != nil {
		return .Flush()
	}
	return nil
}

// maxWriteWaitBeforeConnReuse is how long the a Transport RoundTrip
// will wait to see the Request's Body.Write result after getting a
// response from the server. See comments in (*persistConn).wroteRequest.
//
// In tests, we set this to a large value to avoid flakiness from inconsistent
// recycling of connections.
var maxWriteWaitBeforeConnReuse = 50 * time.Millisecond

// wroteRequest is a check before recycling a connection that the previous write
// (from writeLoop above) happened and was successful.
func ( *persistConn) () bool {
	select {
	case  := <-.writeErrCh:
		// Common case: the write happened well before the response, so
		// avoid creating a timer.
		return  == nil
	default:
		// Rare case: the request was written in writeLoop above but
		// before it could send to pc.writeErrCh, the reader read it
		// all, processed it, and called us here. In this case, give the
		// write goroutine a bit of time to finish its send.
		//
		// Less rare case: We also get here in the legitimate case of
		// Issue 7569, where the writer is still writing (or stalled),
		// but the server has already replied. In this case, we don't
		// want to wait too long, and we want to return false so this
		// connection isn't reused.
		 := time.NewTimer(maxWriteWaitBeforeConnReuse)
		defer .Stop()
		select {
		case  := <-.writeErrCh:
			return  == nil
		case <-.C:
			return false
		}
	}
}

// responseAndError is how the goroutine reading from an HTTP/1 server
// communicates with the goroutine doing the RoundTrip.
type responseAndError struct {
	_   incomparable
	res *http.Response // else use this response (see res method)
	err error
}

type requestAndChan struct {
	_    incomparable
	treq *transportRequest
	ch   chan responseAndError // unbuffered; always send in select on callerGone

	// whether the Transport (as opposed to the user client code)
	// added the Accept-Encoding gzip header. If the Transport
	// set it, only then do we transparently decode the gzip.
	addedGzip bool

	// Optional blocking chan for Expect: 100-continue (for send).
	// If the request has an "Expect: 100-continue" header and
	// the server responds 100 Continue, readLoop send a value
	// to writeLoop via this chan.
	continueCh chan<- struct{}

	callerGone <-chan struct{} // closed when roundTrip caller has returned
}

// A writeRequest is sent by the caller's goroutine to the
// writeLoop's goroutine to write a request while the read loop
// concurrently waits on both the write response and the server's
// reply.
type writeRequest struct {
	req *transportRequest
	ch  chan<- error

	// Optional blocking chan for Expect: 100-continue (for receive).
	// If not nil, writeLoop blocks sending request body until
	// it receives from this chan.
	continueCh <-chan struct{}
}

// httpTimeoutError represents a timeout.
// It implements net.Error and wraps context.DeadlineExceeded.
type timeoutError struct {
	err string
}

func ( *timeoutError) () string     { return .err }
func ( *timeoutError) () bool     { return true }
func ( *timeoutError) () bool   { return true }
func ( *timeoutError) ( error) bool { return  == context.DeadlineExceeded }

var errTimeout error = &timeoutError{"net/http: timeout awaiting response headers"}

var errRequestCanceledConn = errors.New("net/http: request canceled while waiting for connection") // TODO: unify?

// errRequestDone is used to cancel the round trip Context after a request is successfully done.
// It should not be seen by the user.
var errRequestDone = errors.New("net/http: request completed")

func nop() {}

// testHooks. Always non-nil.
var (
	testHookEnterRoundTrip   = nop
	testHookWaitResLoop      = nop
	testHookRoundTripRetried = nop
	testHookPrePendingDial   = nop
	testHookPostPendingDial  = nop

	testHookMu                     sync.Locker = fakeLocker{} // guards following
	testHookReadLoopBeforeNextRead             = nop
)

func ( *persistConn) ( *transportRequest) ( *http.Response,  error) {
	if .t.Debugf != nil {
		.t.Debugf("HTTP/1.1 %s %s", .Method, .URL.String())
	}
	testHookEnterRoundTrip()
	.mu.Lock()
	.numExpectedResponses++
	 := .mutateHeaderFunc
	.mu.Unlock()

	if  != nil {
		(.extraHeaders())
	}

	// Ask for a compressed version if the caller didn't set their
	// own value for Accept-Encoding. We only attempt to
	// uncompress the gzip stream if we were the layer that
	// requested it.
	 := false
	if !.t.DisableCompression &&
		.Header.Get("Accept-Encoding") == "" &&
		.Header.Get("Range") == "" &&
		.Method != "HEAD" {
		// Request gzip only, not deflate. Deflate is ambiguous and
		// not as universally supported anyway.
		// See: https://zlib.net/zlib_faq.html#faq39
		//
		// Note that we don't request this for HEAD requests,
		// due to a bug in nginx:
		//   https://trac.nginx.org/nginx/ticket/358
		//   https://golang.org/issue/5522
		//
		// We don't request gzip if the request is for a range, since
		// auto-decoding a portion of a gzipped document will just fail
		// anyway. See https://golang.org/issue/8923
		 = true
		.extraHeaders().Set("Accept-Encoding", "gzip")
	}

	var  chan struct{}
	if .ProtoAtLeast(1, 1) && .Body != nil && reqExpectsContinue(.Request) {
		 = make(chan struct{}, 1)
	}

	if .t.DisableKeepAlives &&
		!reqWantsClose(.Request) &&
		!isProtocolSwitchHeader(.Header) {
		.extraHeaders().Set("Connection", "close")
	}

	 := make(chan struct{})
	defer close()

	const  = false

	// Write the request concurrently with waiting for a response,
	// in case the server decides to reply before reading our full
	// request body.
	 := .nwrite
	 := make(chan error, 1)
	.writech <- writeRequest{, , }

	 := make(chan responseAndError)
	.reqch <- requestAndChan{
		treq:       ,
		ch:         ,
		addedGzip:  ,
		continueCh: ,
		callerGone: ,
	}
	 := func( responseAndError) (*http.Response, error) {
		if (.res == nil) == (.err == nil) {
			panic(fmt.Sprintf("internal error: exactly one of res or err should be set; nil=%v", .res == nil))
		}
		if  {
			.logf("resc recv: %p, %T/%#v", .res, .err, .err)
		}
		if .err != nil {
			return nil, .mapRoundTripError(, , .err)
		}
		return .res, nil
	}

	var  <-chan time.Time
	 := .ctx.Done()
	 := .closech
	for {
		testHookWaitResLoop()
		select {
		case  := <-:
			if  {
				.logf("writeErrCh recv: %T/%#v", , )
			}
			if  != nil {
				.close(fmt.Errorf("write error: %w", ))
				return nil, .mapRoundTripError(, , )
			}
			if  := .t.ResponseHeaderTimeout;  > 0 {
				if  {
					.logf("starting timer for %v", )
				}
				 := time.NewTimer()
				defer .Stop() // prevent leaks
				 = .C
			}
		case <-:
			select {
			case  := <-:
				// The pconn closing raced with the response to the request,
				// probably after the server wrote a response and immediately
				// closed the connection. Use the response.
				return ()
			default:
			}
			if  {
				.logf("closech recv: %T %#v", .closed, .closed)
			}
			return nil, .mapRoundTripError(, , .closed)
		case <-:
			if  {
				.logf("timeout waiting for response headers.")
			}
			.close(errTimeout)
			return nil, errTimeout
		case  := <-:
			return ()
		case <-:
			select {
			case  := <-:
				// readLoop is responsible for canceling req.ctx after
				// it reads the response body. Check for a response racing
				// the context close, and use the response if available.
				return ()
			default:
			}
			.cancelRequest(context.Cause(.ctx))
		}
	}
}

// tLogKey is a context WithValue key for test debugging contexts containing
// a t.Logf func. See export_test.go's Request.WithT method.
type tLogKey struct{}

func ( *transportRequest) ( string,  ...any) {
	if ,  := .Request.Context().Value(tLogKey{}).(func(string, ...any));  {
		(time.Now().Format(time.RFC3339Nano)+": "+, ...)
	}
}

// markReused marks this connection as having been successfully used for a
// request and response.
func ( *persistConn) () {
	.mu.Lock()
	.reused = true
	.mu.Unlock()
}

// close closes the underlying TCP connection and closes
// the pc.closech channel.
//
// The provided err is only for testing and debugging; in normal
// circumstances it should never be seen by users.
func ( *persistConn) ( error) {
	.mu.Lock()
	defer .mu.Unlock()
	.closeLocked()
}

func ( *persistConn) ( error) {
	if  == nil {
		panic("nil error")
	}
	.broken = true
	if .closed == nil {
		.closed = 
		.t.decConnsPerHost(.cacheKey)
		// Close HTTP/1 (pc.alt == nil) connection.
		// HTTP/2 closes its connection itself.
		if .alt == nil {
			if  != errCallerOwnsConn {
				.conn.Close()
			}
			close(.closech)
		}
	}
	.mutateHeaderFunc = nil
}

var portMap = map[string]string{
	"http":    "80",
	"https":   "443",
	"socks5":  "1080",
	"socks5h": "1080",
	"socks4":  "1080",
	"socks4a": "1080",
}

func idnaASCIIFromURL( *url.URL) string {
	 := .Hostname()
	if ,  := idnaASCII();  == nil {
		 = 
	}
	return 
}

// canonicalAddr returns url.Host but always with a ":port" suffix.
func canonicalAddr( *url.URL) string {
	 := .Port()
	if  == "" {
		 = portMap[.Scheme]
	}
	return net.JoinHostPort(idnaASCIIFromURL(), )
}

// bodyEOFSignal is used by the HTTP/1 transport when reading response
// bodies to make sure we see the end of a response body before
// proceeding and reading on the connection again.
//
// It wraps a ReadCloser but runs fn (if non-nil) at most
// once, right before its final (error-producing) Read or Close call
// returns. fn should return the new error to return from Read or Close.
//
// If earlyCloseFn is non-nil and Close is called before io.EOF is
// seen, earlyCloseFn is called instead of fn, and its return value is
// the return value from Close.
type bodyEOFSignal struct {
	body         io.ReadCloser
	mu           sync.Mutex        // guards following 4 fields
	closed       bool              // whether Close has been called
	rerr         error             // sticky Read error
	fn           func(error) error // err will be nil on Read io.EOF
	earlyCloseFn func() error      // optional alt Close func used if io.EOF not seen
}

var errReadOnClosedResBody = errors.New("http: read on closed response body")

func ( *bodyEOFSignal) ( []byte) ( int,  error) {
	.mu.Lock()
	,  := .closed, .rerr
	.mu.Unlock()
	if  {
		return 0, errReadOnClosedResBody
	}
	if  != nil {
		return 0, 
	}

	,  = .body.Read()
	if  != nil {
		.mu.Lock()
		defer .mu.Unlock()
		if .rerr == nil {
			.rerr = 
		}
		 = .condfn()
	}
	return
}

func ( *bodyEOFSignal) () error {
	.mu.Lock()
	defer .mu.Unlock()
	if .closed {
		return nil
	}
	.closed = true
	if .earlyCloseFn != nil && .rerr != io.EOF {
		return .earlyCloseFn()
	}
	 := .body.Close()
	return .condfn()
}

// caller must hold es.mu.
func ( *bodyEOFSignal) ( error) error {
	if .fn == nil {
		return 
	}
	 = .fn()
	.fn = nil
	return 
}

// gzipReader wraps a response body so it can lazily
// call gzip.NewReader on the first call to Read
type gzipReader struct {
	_    incomparable
	body *bodyEOFSignal // underlying HTTP/1 response body framing
	zr   *gzip.Reader   // lazily-initialized gzip reader
	zerr error          // any error from gzip.NewReader; sticky
}

func ( *gzipReader) ( []byte) ( int,  error) {
	if .zr == nil {
		if .zerr == nil {
			.zr, .zerr = gzip.NewReader(.body)
		}
		if .zerr != nil {
			return 0, .zerr
		}
	}

	.body.mu.Lock()
	if .body.closed {
		 = errReadOnClosedResBody
	}
	.body.mu.Unlock()

	if  != nil {
		return 0, 
	}
	return .zr.Read()
}

func ( *gzipReader) () error {
	return .body.Close()
}

type tlsHandshakeTimeoutError struct{}

func (tlsHandshakeTimeoutError) () bool   { return true }
func (tlsHandshakeTimeoutError) () bool { return true }
func (tlsHandshakeTimeoutError) () string   { return "net/http: TLS handshake timeout" }

// fakeLocker is a sync.Locker which does nothing. It's used to guard
// test-only fields when not under test, to avoid runtime atomic
// overhead.
type fakeLocker struct{}

func (fakeLocker) ()   {}
func (fakeLocker) () {}

// cloneTLSConfig returns a shallow clone of cfg, or a new zero tls.Config if
// cfg is nil. This is safe to call even if cfg is in active use by a TLS
// client or server.
//
// cloneTLSConfig should be an internal detail,
// but widely used packages access it using linkname.
// Notable members of the hall of shame include:
//   - github.com/searKing/golang
//
// Do not remove or change the type signature.
// See go.dev/issue/67401.
//
//go:linkname cloneTLSConfig
func cloneTLSConfig( *tls.Config) *tls.Config {
	if  == nil {
		return &tls.Config{}
	}
	return .Clone()
}

type connLRU struct {
	ll *list.List // list.Element.Value type is of *persistConn
	m  map[*persistConn]*list.Element
}

// add adds pc to the head of the linked list.
func ( *connLRU) ( *persistConn) {
	if .ll == nil {
		.ll = list.New()
		.m = make(map[*persistConn]*list.Element)
	}
	 := .ll.PushFront()
	if ,  := .m[];  {
		panic("persistConn was already in LRU")
	}
	.m[] = 
}

func ( *connLRU) () *persistConn {
	 := .ll.Back()
	 := .Value.(*persistConn)
	.ll.Remove()
	delete(.m, )
	return 
}

// remove removes pc from cl.
func ( *connLRU) ( *persistConn) {
	if ,  := .m[];  {
		.ll.Remove()
		delete(.m, )
	}
}

// len returns the number of items in the cache.
func ( *connLRU) () int {
	return len(.m)
}