Tune The HTTP Transport Connection Pool
Reuse a single http.Transport and set MaxIdleConns, MaxIdleConnsPerHost, and IdleConnTimeout deliberately, because the per-host idle default is only 2.
Code
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
// 长驻客户端复用同一条 Transport:内部就是按 host 计数的连接池
// (connection pool),空闲连接被复用而不是反复握手
transport := &http.Transport{
MaxIdleConns: 100, // 进程级空闲连接上限
MaxIdleConnsPerHost: 10, // 单 host 空闲连接上限;字段留 0 则生效值取 DefaultMaxIdleConnsPerHost
MaxConnsPerHost: 50, // 单 host 并发连接上限,0 表示不限
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 5 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
client := &http.Client{
Timeout: 10 * time.Second,
Transport: transport,
}
// 被忽视的复用瓶颈:DefaultTransport 的字段是 0,
// 真正生效的是常量 DefaultMaxIdleConnsPerHost = 2
fmt.Println("DefaultMaxIdleConnsPerHost:", http.DefaultMaxIdleConnsPerHost)
fmt.Println("DefaultTransport field:", http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost)
fmt.Println("client timeout:", client.Timeout)
}The internals, plainly described
Tune The HTTP Transport Connection Pool reduces to the function main.
Applying it
The demo output is labeled (DefaultMaxIdleConnsPerHost:, DefaultTransport field:, client timeout:), so every printed line maps back to its originating operation.
Statements that matter
MaxIdleConnsPerHost: 10, // 单 host 空闲连接上限;字段留 0 则生效值取 DefaultMaxIdleConnsPerHost
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.
FAQ
- What does Tune The HTTP Transport Connection Pool print when run?
- The script runs standalone; its 3 labeled outputs include `DefaultMaxIdleConnsPerHost:`, `DefaultTransport field:`, `client timeout:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.