Files
any-hub/internal/server/http_client.go
2025-11-14 12:11:44 +08:00

78 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package server
import (
"net"
"net/http"
"net/textproto"
"time"
"github.com/any-hub/any-hub/internal/config"
)
// Shared HTTP transport tunings复用长连接并集中配置超时。
var defaultTransport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
ForceAttemptHTTP2: true,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
}
// NewUpstreamClient 返回共享 http.Client用于所有上游请求。
func NewUpstreamClient(cfg *config.Config) *http.Client {
timeout := 30 * time.Second
if cfg != nil && cfg.Global.UpstreamTimeout.DurationValue() > 0 {
timeout = cfg.Global.UpstreamTimeout.DurationValue()
}
return &http.Client{
Timeout: timeout,
Transport: defaultTransport.Clone(),
}
}
// hopByHopHeaders 定义 RFC 7230 中禁止代理转发的头部。
var hopByHopHeaders = map[string]struct{}{
"Connection": {},
"Keep-Alive": {},
"Proxy-Authenticate": {},
"Proxy-Authorization": {},
"Te": {},
"Trailer": {},
"Transfer-Encoding": {},
"Upgrade": {},
"Proxy-Connection": {}, // 非标准字段,但部分代理仍使用
}
// CopyHeaders 将 src 中允许透传的头复制到 dst自动忽略 hop-by-hop 字段。
func CopyHeaders(dst, src http.Header) {
for key, values := range src {
if isHopByHopHeader(key) {
continue
}
for _, value := range values {
dst.Add(key, value)
}
}
}
func isHopByHopHeader(key string) bool {
canonical := textproto.CanonicalMIMEHeaderKey(key)
if _, ok := hopByHopHeaders[canonical]; ok {
return true
}
return false
}
// IsHopByHopHeader reports whether the header should be stripped by proxies.
func IsHopByHopHeader(key string) bool {
return isHopByHopHeader(key)
}