Skip to content

Commit

Permalink
improve Client.Clone
Browse files Browse the repository at this point in the history
  • Loading branch information
imroc committed Aug 4, 2023
1 parent 9059ed0 commit 490ffb5
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 21 deletions.
23 changes: 5 additions & 18 deletions req.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,26 +84,13 @@ type DownloadInfo struct {
// response body download.
type DownloadCallback func(info DownloadInfo)

func cloneCookies(cookies []*http.Cookie) []*http.Cookie {
if len(cookies) == 0 {
func cloneSlice[T any](s []T) []T {
if len(s) == 0 {
return nil
}
c := make([]*http.Cookie, len(cookies))
copy(c, cookies)
return c
}

func cloneHeaders(hdrs http.Header) http.Header {
if hdrs == nil {
return nil
}
h := make(http.Header)
for k, vs := range hdrs {
for _, v := range vs {
h.Add(k, v)
}
}
return h
ss := make([]T, len(s))
copy(ss, s)
return ss
}

// TODO: change to generics function when generics are commonly used.
Expand Down
9 changes: 6 additions & 3 deletions transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -798,8 +798,8 @@ func (t *Transport) readBufferSize() int {
// Clone returns a deep copy of t's exported fields.
func (t *Transport) Clone() *Transport {
tt := &Transport{
Headers: cloneHeaders(t.Headers),
Cookies: cloneCookies(t.Cookies),
Headers: t.Headers.Clone(),
Cookies: cloneSlice(t.Cookies),
Options: t.Options.Clone(),
disableAutoDecode: t.disableAutoDecode,
autoDecodeContentType: t.autoDecodeContentType,
Expand All @@ -818,12 +818,15 @@ func (t *Transport) Clone() *Transport {
if t.t2 != nil {
tt.t2 = &h2internal.Transport{
Options: &tt.Options,
Settings: t.t2.Settings,
MaxHeaderListSize: t.t2.MaxHeaderListSize,
StrictMaxConcurrentStreams: t.t2.StrictMaxConcurrentStreams,
ReadIdleTimeout: t.t2.ReadIdleTimeout,
PingTimeout: t.t2.PingTimeout,
WriteByteTimeout: t.t2.WriteByteTimeout,
ConnectionFlow: t.t2.ConnectionFlow,
Settings: cloneSlice(t.t2.Settings),
HeaderPriority: t.t2.HeaderPriority,
PriorityFrames: cloneSlice(t.t2.PriorityFrames),
}
}
if t.t3 != nil {
Expand Down

0 comments on commit 490ffb5

Please sign in to comment.