Files
ginframework/httpclient/client.go
T
zhangdeman 52205b42c8
Verify / verify (push) Canceled after 0s
Verify / verify (pull_request) Canceled after 0s
chore(module): 更新仓库地址及模块导入路径
2026-11-27 22:58:26 -08:00

175 lines
8.2 KiB
Go

// Package httpclient 提供共享连接池的出站 HTTP 客户端,不包含业务码、缓存和重试策略。
package httpclient
import (
"errors"
"net"
"net/http"
"time"
"git.zhangdeman.cn/zhangdeman/ginframework/diagnostic"
failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure"
"go.uber.org/zap"
)
const (
defaultMaxResponseBytes int64 = 8 << 20
maxRedirects = 10
maxMilliseconds = int64((1<<63 - 1) / time.Millisecond)
)
// Config 描述可复用客户端策略,指针区分缺省与显式零值。
type Config struct {
TimeoutMS *int64 `json:"timeout_ms" yaml:"timeout_ms" dc:"单次请求总超时毫秒,含正文读取;缺省 30000,零禁用以支持长流"`
ConnectTimeoutMS *int64 `json:"connect_timeout_ms" yaml:"connect_timeout_ms" dc:"建连超时毫秒,缺省 5000,零禁用"`
ResponseHeaderTimeoutMS *int64 `json:"response_header_timeout_ms" yaml:"response_header_timeout_ms" dc:"响应头超时毫秒,缺省零表示不单独限制"`
IdleConnTimeoutMS *int64 `json:"idle_conn_timeout_ms" yaml:"idle_conn_timeout_ms" dc:"空闲连接保留毫秒,缺省 90000,零不限制"`
MaxIdleConns *int `json:"max_idle_conns" yaml:"max_idle_conns" dc:"最大空闲连接数,缺省 100,零不限制"`
MaxIdleConnsPerHost *int `json:"max_idle_conns_per_host" yaml:"max_idle_conns_per_host" dc:"单目标最大空闲连接数,缺省 10,零沿用 net/http 默认值"`
MaxConnsPerHost *int `json:"max_conns_per_host" yaml:"max_conns_per_host" dc:"单目标最大连接数,缺省零不限制"`
MaxResponseBytes int64 `json:"max_response_bytes" yaml:"max_response_bytes" dc:"Send 缓冲响应上限,缺省 8 MiB;流式 Do 不读取正文"`
FollowRedirects bool `json:"follow_redirects" yaml:"follow_redirects" dc:"是否跟随同源重定向;默认关闭,跨源始终返回原响应"`
UserAgent string `json:"user_agent" yaml:"user_agent" dc:"可选默认 User-Agent,不覆盖请求显式设置"`
}
// Options 传入已有日志和可选的原生传输实现。
type Options struct {
Logger *zap.Logger `json:"-" dc:"可选执行流水日志,仅记录安全协议元数据"`
Transport http.RoundTripper `json:"-" dc:"可选借用的传输;由外部管理,库不关闭或修改其连接池"`
}
// Client 可在多请求间并发复用;每次请求必须有独立 Body Reader。
type Client struct {
native *http.Client `dc:"持有不可变策略的原生客户端"`
owned *http.Transport `dc:"库创建并拥有的连接池,借用传输时为空"`
logger *zap.Logger `dc:"应用持有的可选执行日志,不归客户端关闭"`
maxResponseBytes int64 `dc:"缓冲响应上限,不影响原生流式 Do"`
userAgent string `dc:"构造时保存的默认 User-Agent"`
}
// New 创建共享连接池,不执行网络请求、不修改默认全局 Transport。
// 入参:cfg 为数据配置,options 为日志及传输依赖;借用传输时其池和阶段超时配置由外部负责。
// 返回:可并发复用的客户端;负值、溢出或冲突配置返回内部错误。
func New(cfg Config, options Options) (*Client, error) {
timeout, connect, header, idle := int64(30000), int64(5000), int64(0), int64(90000)
maxIdle, perHost, maxConns := 100, 10, 0
if cfg.TimeoutMS != nil {
timeout = *cfg.TimeoutMS
}
if cfg.ConnectTimeoutMS != nil {
connect = *cfg.ConnectTimeoutMS
}
if cfg.ResponseHeaderTimeoutMS != nil {
header = *cfg.ResponseHeaderTimeoutMS
}
if cfg.IdleConnTimeoutMS != nil {
idle = *cfg.IdleConnTimeoutMS
}
if cfg.MaxIdleConns != nil {
maxIdle = *cfg.MaxIdleConns
}
if cfg.MaxIdleConnsPerHost != nil {
perHost = *cfg.MaxIdleConnsPerHost
}
if cfg.MaxConnsPerHost != nil {
maxConns = *cfg.MaxConnsPerHost
}
if cfg.MaxResponseBytes == 0 {
cfg.MaxResponseBytes = defaultMaxResponseBytes
}
if timeout < 0 || connect < 0 || header < 0 || idle < 0 || timeout > maxMilliseconds || connect > maxMilliseconds || header > maxMilliseconds || idle > maxMilliseconds || maxIdle < 0 || perHost < 0 || maxConns < 0 || cfg.MaxResponseBytes < 1 || cfg.MaxResponseBytes == 1<<63-1 {
return nil, failure.Wrap(CodeConfig, "validate outbound HTTP configuration failed", errors.New("invalid timeout, connection pool or response limit"))
}
if options.Transport != nil && (cfg.ConnectTimeoutMS != nil || cfg.ResponseHeaderTimeoutMS != nil || cfg.IdleConnTimeoutMS != nil || cfg.MaxIdleConns != nil || cfg.MaxIdleConnsPerHost != nil || cfg.MaxConnsPerHost != nil) {
return nil, failure.Wrap(CodeTransportOwnership, "validate outbound transport ownership failed", errors.New("borrowed transport and owned pool settings cannot be combined"))
}
var (
owned *http.Transport
transport = options.Transport
)
if transport == nil {
// 使用明确的标准传输配置,不读取可能被其他库改写的 DefaultTransport。
owned = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{Timeout: time.Duration(connect) * time.Millisecond, KeepAlive: 30 * time.Second}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: maxIdle,
MaxIdleConnsPerHost: perHost,
MaxConnsPerHost: maxConns,
IdleConnTimeout: time.Duration(idle) * time.Millisecond,
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: time.Duration(header) * time.Millisecond,
ExpectContinueTimeout: time.Second,
}
transport = owned
}
native := &http.Client{
Transport: transport,
Timeout: time.Duration(timeout) * time.Millisecond,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if !cfg.FollowRedirects || len(via) == 0 || req.URL.Scheme != via[0].URL.Scheme || req.URL.Host != via[0].URL.Host {
return http.ErrUseLastResponse
}
if len(via) >= maxRedirects {
return errRedirectLimit
}
return nil
},
}
return &Client{native: native, owned: owned, logger: options.Logger, maxResponseBytes: cfg.MaxResponseBytes, userAgent: cfg.UserAgent}, nil
}
// Do 按 net/http 原生语义执行请求,不读取响应正文,也不把非 2xx 当作传输错误。
// 入参:request 为带 Context 的原生请求;Header 和 URL 会复制,Body Reader 由本次请求消费。
// 返回:原生响应和可追溯传输错误;调用方必须关闭返回的响应正文。
// 隐式逻辑:流水在响应头返回时记录,流式读取耗时不计入该阶段;不额外实现应用重试。
func (c *Client) Do(request *http.Request) (*http.Response, error) {
if request == nil {
return nil, failure.Wrap(CodeRequest, "validate outbound HTTP request failed", errors.New("request is nil"))
}
ctx := request.Context()
cloned := request.Clone(ctx)
if cloned.Header == nil {
cloned.Header = make(http.Header)
}
if _, exists := cloned.Header["User-Agent"]; !exists && c.userAgent != "" {
cloned.Header.Set("User-Agent", c.userAgent)
}
start := time.Now()
response, err := c.native.Do(cloned)
if err != nil {
if errors.Is(err, errRedirectLimit) {
err = failure.WrapContext(ctx, CodeRedirectLimit, "follow outbound HTTP redirects failed", err)
} else {
err = failure.WrapContext(ctx, CodeExecute, "execute outbound HTTP request failed", err)
}
}
if c.logger != nil {
status := 0
host := ""
method := cloned.Method
if method == "" {
method = http.MethodGet
}
if response != nil {
status = response.StatusCode
}
if cloned.URL != nil {
host = cloned.URL.Host
}
snapshot := diagnostic.From(ctx)
c.logger.Info("Outbound HTTP response headers completed",
zap.String("phase", "response_headers"), zap.String("target_host", host), zap.String("method", method), zap.Int("status", status), zap.Duration("duration", time.Since(start)),
zap.String("trace_id", snapshot.TraceID), zap.String("request_id", snapshot.RequestID), zap.Bool("transport_success", err == nil))
}
return response, err
}
// CloseIdleConnections 释放本客户端拥有的空闲连接,不取消在途请求。
// 隐式逻辑:借用的外部传输由其所有者关闭,此处不操作;停止业务后再由应用释放日志。
func (c *Client) CloseIdleConnections() {
if c.owned != nil {
c.owned.CloseIdleConnections()
}
}