httpx

package module
v1.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 6 Imported by: 0

README

httpx

基于 net/http 的高性能 HTTP 客户端库:连接复用、分层超时、可选重试, 可适配 HTTP/1 / HTTP/2 / HTTP/3,与 errx / logx 打通。

当前状态:v1.4.1

定位

httpx 不是新协议实现,不解决「HTTP 怎么走」的问题;它解决的是项目里每个 HTTP 调用方都要重复的部分:

  • 连接池复用、空闲回收与分层超时;
  • HTTP/1 / HTTP/2 / HTTP/3 协议可选切换;
  • 幂等重试与指数退避;
  • 与 errx / logx 打通的错误、日志与指标;
  • 响应读取助手(JSON / 文本 / 字节,带大小上限)。

快速上手

client, err := httpx.New(
	httpx.WithTimeout(5*time.Second),
	httpx.WithRetry(3, httpx.ExponentialBackoff(100*time.Millisecond, 2, 0.2)),
	httpx.WithLogger(logger),
)
if err != nil {
	panic(err)
}

resp, err := client.Get(ctx, "https://api.example.com/users/1",
	httpx.WithHeader("X-Project", "demo"))
if err != nil {
	panic(err)
}
var user User
if err := httpx.JSON(resp, &user); err != nil {
	panic(err)
}

HTTP/3 使用可选子包,导入即注册:

import (
	"github.com/lcylpzls/httpx"
	_ "github.com/lcylpzls/httpx/http3" // 注册 HTTP/3 传输层
)

client, err := httpx.New(httpx.WithProtocol(httpx.ProtocolHTTP3))

特性

  • 连接池:per-host 复用、空闲回收、每主机上限,默认贴合生产实践;
  • 四层超时:Dial / TLS / 响应头 / 整体(context),全部可配;
  • 协议:HTTP/1.1、HTTP/2(自动协商或强制)、HTTP/3(可选子包);
  • 重试:默认关闭,显式开启后仅幂等方法,指数退避 + 抖动 + Retry-After;
  • 观测:logx 外部注入 + Metrics 接口,默认 no-op 零开销;
  • 错误:统一 errx,HTX_* 错误码,IsTimeout / IsRetryable 判定助手;
  • 响应助手:ReadBody / ReadString / JSON / ReadFile,统一关闭 Body 并设大小上限;
  • 重定向:默认跟随上限 10,方法转换与跨域敏感头剥离,可关闭/自定义策略;
  • 会话:标准库 CookieJar 自动注入与保存;
  • 钩子:OnRequest / OnResponse / OnError 轻量回调;
  • 请求体:JSON / XML / multipart / 表单 / 字节;
  • 统计:Client.Stats 请求、活跃、错误、重试计数。
  • 请求级超时:WithRequestTimeout,与客户端超时取更严格者;
  • 重试策略:WithRetryPolicy 自定义可重试判定;
  • DNS 缓存:WithDNSCache 按 TTL 缓存解析,失败自动回退;
  • 并发限流:WithMaxConcurrency 控制同时在途请求;
  • HTTP/2 健康检查:WithHTTP2HealthCheck 读空闲 + Ping;
  • 流式响应:ReadStream 逐块回调,带大小上限。
  • 状态断言:EnsureStatus 校验期望状态码,错误携带 status/body 字段;
  • 流式上传:FileField.Reader 大文件不整块载入内存;
  • 重试上限:RetryPolicy.MaxBackoff 截断超大 Retry-After。

质量门槛

  • 语句覆盖率 100%,race、vet、staticcheck、fuzz 全绿;
  • govulncheck 漏洞扫描零告警;
  • 三平台 CI(ubuntu / windows / macos);
  • 性能基准与裸 net/http 同量级(见 docs/performance.md)。

稳定性承诺

  • 本库遵循语义化版本;
  • 家族约定:破坏性变更统一走 minor 版本(不强制主版本升级);
  • 行为修复与安全修复以补丁版本发布,并记录于 CHANGELOG;
  • 每个版本发布前执行:100% 覆盖率、race、staticcheck、fuzz、 govulncheck 与三平台 CI。

文档

贡献与安全

License

MIT © lcylpzls

Documentation

Overview

Package httpx 提供基于 net/http 的薄高性能 HTTP 客户端库: 连接复用、分层超时、可选幂等重试与协议适配 (HTTP/1.1 / HTTP/2 / HTTP/3),与 errx / logx 打通, 统一错误、日志与指标。 实现主体位于 internal/core,本包仅暴露稳定公开 API。

Index

Constants

View Source
const (
	CodeInvalidConfig       = core.CodeInvalidConfig
	CodeUnsupportedProtocol = core.CodeUnsupportedProtocol
	CodeDialFailed          = core.CodeDialFailed
	CodeTLSFailed           = core.CodeTLSFailed
	CodeRequestFailed       = core.CodeRequestFailed
	CodeResponseFailed      = core.CodeResponseFailed
	CodeRetryExhausted      = core.CodeRetryExhausted
	CodeBodyTooLarge        = core.CodeBodyTooLarge
	CodeBodyUnreadable      = core.CodeBodyUnreadable
	CodeRedirectExceeded    = core.CodeRedirectExceeded
	CodeRedirectFailed      = core.CodeRedirectFailed
	CodeUnexpectedStatus    = core.CodeUnexpectedStatus
)

错误码定义:httpx 各失败场景的错误码,统一为 HTX_*。

View Source
const (
	ProtocolAuto  = core.ProtocolAuto
	ProtocolHTTP1 = core.ProtocolHTTP1
	ProtocolHTTP2 = core.ProtocolHTTP2
	ProtocolHTTP3 = core.ProtocolHTTP3
)

协议常量:HTTP/1.1 / HTTP/2 / HTTP/3 选择。

View Source
const Version = core.Version

Version 是当前库版本,与 git tag 保持一致。

Variables

This section is empty.

Functions

func EnsureStatus added in v0.5.0

func EnsureStatus(resp *http.Response, codes ...int) error

EnsureStatus 校验响应状态码。

func ErrorStatus added in v1.3.0

func ErrorStatus(err error) int

ErrorStatus 返回错误对应的 HTTP 状态码。

func IsRetryable

func IsRetryable(err error) bool

IsRetryable 判断错误是否值得重试。

func IsTimeout

func IsTimeout(err error) bool

IsTimeout 判断错误是否为超时。

func JSON

func JSON(resp *http.Response, out any) error

JSON 将响应体解析为 out 并关闭 Body。

func ReadBody

func ReadBody(resp *http.Response, maxBytes int64) ([]byte, error)

ReadBody 读取响应体并关闭 Body。

func ReadFile added in v0.2.0

func ReadFile(resp *http.Response, path string, maxBytes int64) error

ReadFile 将响应体写入文件并关闭 Body。

func ReadStream added in v0.3.0

func ReadStream(resp *http.Response, fn func([]byte) error, maxBytes int64) error

ReadStream 逐块读取响应体并回调 fn。

func ReadString

func ReadString(resp *http.Response, maxBytes int64) (string, error)

ReadString 读取响应体为字符串并关闭 Body。

func RegisterHTTP3

func RegisterHTTP3(builder func(ProtocolConfig) (http.RoundTripper, error))

RegisterHTTP3 注册 HTTP/3 RoundTripper 构造器。

func WriteErrorJSON added in v1.3.0

func WriteErrorJSON(w http.ResponseWriter, err error)

WriteErrorJSON 将错误以 JSON 形式写入 ResponseWriter。

Types

type Backoff

type Backoff = core.Backoff

公开类型:与 internal/core 保持一致。

func ExponentialBackoff

func ExponentialBackoff(base time.Duration, factor, jitter float64) Backoff

ExponentialBackoff 返回指数退避策略。

func FixedBackoff

func FixedBackoff(interval time.Duration) Backoff

FixedBackoff 返回固定间隔退避策略。

type Client

type Client = core.Client

公开类型:与 internal/core 保持一致。

func New

func New(opts ...Option) (*Client, error)

New 创建 HTTP 客户端。

type DNSCache added in v0.3.0

type DNSCache = core.DNSCache

公开类型:与 internal/core 保持一致。

func NewDNSCache added in v0.3.0

func NewDNSCache(ttl time.Duration) *DNSCache

NewDNSCache 创建 DNS 缓存。

type FileField added in v0.2.0

type FileField = core.FileField

公开类型:与 internal/core 保持一致。

type Hooks added in v0.2.0

type Hooks = core.Hooks

公开类型:与 internal/core 保持一致。

type Metrics

type Metrics = core.Metrics

公开类型:与 internal/core 保持一致。

type Option

type Option = core.Option

公开类型:与 internal/core 保持一致。

func WithCookieJar added in v0.2.0

func WithCookieJar(jar http.CookieJar) Option

func WithDNSCache added in v0.3.0

func WithDNSCache(cache *DNSCache) Option

func WithDialTimeout

func WithDialTimeout(d time.Duration) Option

func WithDisableCompression added in v0.2.0

func WithDisableCompression(disabled bool) Option

func WithExpectContinueTimeout added in v0.4.0

func WithExpectContinueTimeout(d time.Duration) Option

func WithHTTP2HealthCheck added in v0.3.0

func WithHTTP2HealthCheck(readIdle, pingTimeout time.Duration) Option

func WithHooks added in v0.2.0

func WithHooks(h Hooks) Option

func WithIdleConnTimeout

func WithIdleConnTimeout(d time.Duration) Option

func WithLogRequest

func WithLogRequest(enabled bool) Option

func WithLogger

func WithLogger(l logx.Logger) Option

func WithMaxConcurrency added in v0.3.0

func WithMaxConcurrency(n int) Option

func WithMaxConnsPerHost added in v0.4.0

func WithMaxConnsPerHost(n int) Option

func WithMaxIdleConns

func WithMaxIdleConns(n int) Option

func WithMaxIdleConnsPerHost

func WithMaxIdleConnsPerHost(n int) Option

func WithMaxRedirects added in v0.2.0

func WithMaxRedirects(n int) Option

func WithMaxResponseHeaderBytes added in v0.4.0

func WithMaxResponseHeaderBytes(n int64) Option

func WithMetrics

func WithMetrics(m Metrics) Option

func WithNoRedirect added in v0.2.0

func WithNoRedirect() Option

func WithProtocol

func WithProtocol(p Protocol) Option

func WithProxy added in v0.2.0

func WithProxy(proxy func(*http.Request) (*url.URL, error)) Option

func WithRedirectPolicy added in v0.2.0

func WithRedirectPolicy(policy func(*http.Request, []*http.Request) error) Option

func WithResponseHeaderTimeout

func WithResponseHeaderTimeout(d time.Duration) Option

func WithRetry

func WithRetry(maxAttempts int, backoff Backoff) Option

func WithRetryPolicy added in v0.3.0

func WithRetryPolicy(p RetryPolicy) Option

func WithRoundTripperWrapper added in v1.0.4

func WithRoundTripperWrapper(wrap func(http.RoundTripper) http.RoundTripper) Option

func WithSlowThreshold

func WithSlowThreshold(d time.Duration) Option

func WithTLSClientConfig

func WithTLSClientConfig(cfg *tls.Config) Option

func WithTLSHandshakeTimeout

func WithTLSHandshakeTimeout(d time.Duration) Option

func WithTimeout

func WithTimeout(d time.Duration) Option

客户端级选项。

type Protocol

type Protocol = core.Protocol

公开类型:与 internal/core 保持一致。

type ProtocolConfig

type ProtocolConfig = core.ProtocolConfig

公开类型:与 internal/core 保持一致。

type RequestOption

type RequestOption = core.RequestOption

公开类型:与 internal/core 保持一致。

func WithBasicAuth

func WithBasicAuth(user, pass string) RequestOption

func WithBearer

func WithBearer(token string) RequestOption

func WithBytesBody

func WithBytesBody(b []byte) RequestOption

func WithFormBody

func WithFormBody(v url.Values) RequestOption

func WithHeader

func WithHeader(key, value string) RequestOption

请求级选项。

func WithJSONBody

func WithJSONBody(v any) RequestOption

func WithMultipartFormData added in v0.2.0

func WithMultipartFormData(fields map[string]string, files map[string]FileField) RequestOption

func WithQuery

func WithQuery(key, value string) RequestOption

func WithRequestID added in v0.4.0

func WithRequestID(id string) RequestOption

func WithRequestTimeout added in v0.3.0

func WithRequestTimeout(d time.Duration) RequestOption

func WithUserAgent

func WithUserAgent(ua string) RequestOption

func WithXMLBody added in v0.2.0

func WithXMLBody(v any) RequestOption

type RetryPolicy added in v0.3.0

type RetryPolicy = core.RetryPolicy

公开类型:与 internal/core 保持一致。

type Stats added in v0.2.0

type Stats = core.Stats

公开类型:与 internal/core 保持一致。

Directories

Path Synopsis
Package http3 提供 HTTP/3(QUIC) 传输层接入。
Package http3 提供 HTTP/3(QUIC) 传输层接入。
internal
core
Package core 实现 httpx 的核心逻辑: 客户端、传输层、重试、重定向、响应读取、错误与可观测性。
Package core 实现 httpx 的核心逻辑: 客户端、传输层、重试、重定向、响应读取、错误与可观测性。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL