|
| 1 | +package client |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "net" |
| 6 | + "net/http" |
| 7 | + "time" |
| 8 | +) |
| 9 | + |
| 10 | +var reasonableRoundTripper http.RoundTripper = &http.Transport{ |
| 11 | + Proxy: http.ProxyFromEnvironment, |
| 12 | + |
| 13 | + DialContext: (&net.Dialer{ |
| 14 | + Timeout: 30 * time.Second, |
| 15 | + KeepAlive: 30 * time.Second, |
| 16 | + }).DialContext, |
| 17 | + |
| 18 | + MaxIdleConns: 100, |
| 19 | + MaxIdleConnsPerHost: 10, |
| 20 | + IdleConnTimeout: 90 * time.Second, |
| 21 | + |
| 22 | + TLSHandshakeTimeout: 10 * time.Second, |
| 23 | + ExpectContinueTimeout: 1 * time.Second, |
| 24 | + |
| 25 | + ResponseHeaderTimeout: 60 * time.Second, |
| 26 | + |
| 27 | + ForceAttemptHTTP2: true, |
| 28 | +} |
| 29 | + |
| 30 | +func GetReasonableClientContext(ctx context.Context, httpTransports ...HttpTransport) *http.Client { |
| 31 | + t := reasonableRoundTripper |
| 32 | + |
| 33 | + tc, ok := RoundTripperCreatorFromContext(ctx) |
| 34 | + if ok { |
| 35 | + t = tc() |
| 36 | + } |
| 37 | + |
| 38 | + for i := range httpTransports { |
| 39 | + t = httpTransports[i](t) |
| 40 | + } |
| 41 | + |
| 42 | + return &http.Client{Transport: t} |
| 43 | +} |
| 44 | + |
| 45 | +func newRoundTripperWithoutKeepAlive() http.RoundTripper { |
| 46 | + return &http.Transport{ |
| 47 | + Proxy: http.ProxyFromEnvironment, |
| 48 | + |
| 49 | + DialContext: (&net.Dialer{ |
| 50 | + Timeout: 30 * time.Second, |
| 51 | + KeepAlive: 0, |
| 52 | + }).DialContext, |
| 53 | + |
| 54 | + DisableKeepAlives: true, |
| 55 | + |
| 56 | + TLSHandshakeTimeout: 10 * time.Second, |
| 57 | + ExpectContinueTimeout: 1 * time.Second, |
| 58 | + ResponseHeaderTimeout: 60 * time.Second, |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +func GetShortConnClientContext(ctx context.Context, httpTransports ...HttpTransport) *http.Client { |
| 63 | + t := newRoundTripperWithoutKeepAlive() |
| 64 | + |
| 65 | + tc, ok := RoundTripperCreatorFromContext(ctx) |
| 66 | + if ok { |
| 67 | + t = tc() |
| 68 | + } |
| 69 | + |
| 70 | + for i := range httpTransports { |
| 71 | + t = httpTransports[i](t) |
| 72 | + } |
| 73 | + |
| 74 | + return &http.Client{Transport: t} |
| 75 | +} |
0 commit comments