httpclient

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCircuitOpen            = errors.New("circuit breaker is open")
	ErrCircuitHalfOpenLimited = errors.New("circuit breaker half-open request limit reached")
)

Functions

func ConfigureDefault added in v1.5.0

func ConfigureDefault(opts ...Option)

ConfigureDefault 配置默认客户端 必须在第一次使用全局函数之前调用

func SetDefaultClient

func SetDefaultClient(client *Client)

SetDefaultClient 设置默认客户端

Types

type CircuitBreaker

type CircuitBreaker interface {
	Execute(ctx context.Context, fn func() error) error
	State() string
}

CircuitBreaker 熔断器接口

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	MaxRequests      uint32        // 半开状态最大请求数
	Interval         time.Duration // 统计时间窗口
	Timeout          time.Duration // 熔断超时时间
	FailureThreshold uint32        // 失败阈值
	SuccessThreshold uint32        // 成功阈值
}

CircuitBreakerConfig 熔断器配置

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client HTTP客户端

func GetDefaultClient

func GetDefaultClient() *Client

GetDefaultClient 获取默认客户端实例

func NewClient

func NewClient(options ...Option) *Client

NewClient 创建新的HTTP客户端,支持传入可选配置覆盖默认值

func NewClientWithOptions

func NewClientWithOptions(opts ClientOptions) *Client

NewClientWithOptions 根据选项创建HTTP客户端(兼容旧接口)

func ResetDefault added in v1.1.0

func ResetDefault(opts ...Option) *Client

ResetDefault 重置默认客户端(主要用于测试)

func (*Client) AddCookie

func (c *Client) AddCookie(cookie *http.Cookie)

AddCookie 添加Cookie

func (*Client) AddInterceptor

func (c *Client) AddInterceptor(interceptor Interceptor)

AddInterceptor 添加拦截器

func (*Client) AddMiddleware

func (c *Client) AddMiddleware(middleware Middleware)

AddMiddleware 添加中间件

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, url string) (*Response, error)

Delete 发送DELETE请求

func (*Client) DisableDebug

func (c *Client) DisableDebug()

DisableDebug 禁用Debug模式

func (*Client) Do added in v1.1.0

func (c *Client) Do(ctx context.Context, method, url string, body io.Reader) (*Response, error)

Do 直接执行HTTP请求

func (*Client) EnableDebug

func (c *Client) EnableDebug()

EnableDebug 启用Debug模式

func (*Client) Get

func (c *Client) Get(ctx context.Context, url string) (*Response, error)

Get 发送GET请求

func (*Client) HTTPClient added in v1.1.0

func (c *Client) HTTPClient() *http.Client

HTTPClient 返回底层 http.Client

func (*Client) NewRequest

func (c *Client) NewRequest(method, url string) *Request

NewRequest 创建新的请求构建器

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, url string, body io.Reader) (*Response, error)

Patch 发送PATCH请求

func (*Client) PatchJSON

func (c *Client) PatchJSON(ctx context.Context, url string, data interface{}) (*Response, error)

PatchJSON 发送JSON PATCH请求

func (*Client) Post

func (c *Client) Post(ctx context.Context, url string, body io.Reader) (*Response, error)

Post 发送POST请求

func (*Client) PostJSON

func (c *Client) PostJSON(ctx context.Context, url string, data interface{}) (*Response, error)

PostJSON 发送JSON POST请求

func (*Client) Put

func (c *Client) Put(ctx context.Context, url string, body io.Reader) (*Response, error)

Put 发送PUT请求

func (*Client) PutJSON

func (c *Client) PutJSON(ctx context.Context, url string, data interface{}) (*Response, error)

PutJSON 发送JSON PUT请求

func (*Client) SetBaseURL

func (c *Client) SetBaseURL(baseURL string)

SetBaseURL 设置基础URL

func (*Client) SetDebug

func (c *Client) SetDebug(debug *DebugConfig)

SetDebug 设置Debug配置

func (*Client) SetHeader

func (c *Client) SetHeader(key, value string)

SetHeader 设置请求头

func (*Client) SetHeaders

func (c *Client) SetHeaders(headers map[string]string)

SetHeaders 批量设置请求头

func (*Client) SetTimeout

func (c *Client) SetTimeout(timeout time.Duration)

SetTimeout 设置超时时间

func (*Client) Transport added in v1.1.0

func (c *Client) Transport() http.RoundTripper

Transport 返回底层传输层

type ClientOptions

type ClientOptions struct {
	Timeout        time.Duration                         // 超时时间
	BaseURL        string                                // 基础URL
	Headers        map[string]string                     // 默认请求头
	UserAgent      string                                // 用户代理
	Cookies        []*http.Cookie                        // 默认Cookie
	Retry          *RetryConfig                          // 重试配置
	CircuitBreaker *CircuitBreakerConfig                 // 熔断器配置
	Pool           *PoolConfig                           // 连接池配置
	TLS            *tls.Config                           // TLS配置
	Proxy          func(*http.Request) (*url.URL, error) // 代理函数
	Interceptors   []Interceptor                         // 拦截器
	Middlewares    []Middleware                          // 中间件
	Logger         Logger                                // 日志记录器
	Metrics        Metrics                               // 指标收集器
	RateLimiter    RateLimiter                           // 限流器
	Debug          *DebugConfig                          // Debug配置
	HTTPClient     *http.Client                          // 自定义HTTP Client
}

ClientOptions HTTP客户端选项

func DefaultOptions added in v1.1.0

func DefaultOptions() ClientOptions

DefaultOptions 默认配置

type DebugConfig

type DebugConfig struct {
	Enabled            bool     // 是否启用Debug
	LogRequestHeaders  bool     // 是否记录请求头
	LogRequestBody     bool     // 是否记录请求体
	LogResponseHeaders bool     // 是否记录响应头
	LogResponseBody    bool     // 是否记录响应体
	MaxBodySize        int      // 最大记录的Body大小(字节),0表示不限制
	SensitiveHeaders   []string // 敏感请求头列表,将被脱敏
}

DebugConfig Debug配置

func DefaultDebugConfig

func DefaultDebugConfig() *DebugConfig

DefaultDebugConfig 默认Debug配置

type Interceptor

type Interceptor func(req *http.Request, next func(*http.Request) (*http.Response, error)) (*http.Response, error)

Interceptor HTTP拦截器

type Logger

type Logger interface {
	Debug(ctx context.Context, msg string, fields ...interface{})
	Info(ctx context.Context, msg string, fields ...interface{})
	Warn(ctx context.Context, msg string, fields ...interface{})
	Error(ctx context.Context, msg string, fields ...interface{})
}

Logger 日志接口

type Metrics

type Metrics interface {
	IncCounter(name string, labels map[string]string)
	AddHistogram(name string, value float64, labels map[string]string)
	SetGauge(name string, value float64, labels map[string]string)
}

Metrics 指标接口

type Middleware

type Middleware func(next http.RoundTripper) http.RoundTripper

Middleware HTTP中间件函数类型

func LoggingMiddleware

func LoggingMiddleware(logger Logger) Middleware

LoggingMiddleware 日志中间件

func MetricsMiddleware

func MetricsMiddleware(metrics Metrics) Middleware

MetricsMiddleware 指标中间件

func RetryMiddleware

func RetryMiddleware(config RetryConfig) Middleware

RetryMiddleware 重试中间件

type Option added in v1.1.0

type Option func(*ClientOptions)

Option 选项函数

func WithAdditionalHeaders added in v1.5.0

func WithAdditionalHeaders(headers map[string]string) Option

WithAdditionalHeaders 追加请求头

func WithBaseURL added in v1.1.0

func WithBaseURL(baseURL string) Option

WithBaseURL 设置基础URL

func WithCircuitBreaker added in v1.1.0

func WithCircuitBreaker(cfg *CircuitBreakerConfig) Option

WithCircuitBreaker 设置熔断配置

func WithCookies added in v1.1.0

func WithCookies(cookies []*http.Cookie) Option

WithCookies 设置默认Cookie

func WithDebug added in v1.1.0

func WithDebug(debug *DebugConfig) Option

WithDebug 设置调试配置

func WithHTTPClient added in v1.1.0

func WithHTTPClient(client *http.Client) Option

WithHTTPClient 注入自定义 http.Client

func WithHeaders added in v1.1.0

func WithHeaders(headers map[string]string) Option

WithHeaders 覆盖默认请求头

func WithInterceptors added in v1.1.0

func WithInterceptors(interceptors ...Interceptor) Option

WithInterceptors 设置拦截器

func WithLogger added in v1.1.0

func WithLogger(logger Logger) Option

WithLogger 设置日志器

func WithMetrics added in v1.1.0

func WithMetrics(metrics Metrics) Option

WithMetrics 设置指标收集

func WithMiddlewares added in v1.1.0

func WithMiddlewares(middlewares ...Middleware) Option

WithMiddlewares 设置中间件

func WithPool added in v1.1.0

func WithPool(cfg *PoolConfig) Option

WithPool 设置连接池配置

func WithProxy added in v1.1.0

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

WithProxy 设置代理

func WithRateLimiter added in v1.1.0

func WithRateLimiter(rateLimiter RateLimiter) Option

WithRateLimiter 设置限流器

func WithRetry added in v1.1.0

func WithRetry(cfg *RetryConfig) Option

WithRetry 设置重试配置

func WithTLS added in v1.1.0

func WithTLS(cfg *tls.Config) Option

WithTLS 设置TLS配置

func WithTimeout added in v1.1.0

func WithTimeout(timeout time.Duration) Option

WithTimeout 设置超时时间

func WithTransport added in v1.1.0

func WithTransport(transport http.RoundTripper) Option

WithTransport 注入自定义 RoundTripper

func WithUserAgent added in v1.1.0

func WithUserAgent(ua string) Option

WithUserAgent 设置User-Agent

type PoolConfig

type PoolConfig struct {
	MaxIdleConns        int           // 最大空闲连接数
	MaxIdleConnsPerHost int           // 每个主机最大空闲连接数
	MaxConnsPerHost     int           // 每个主机最大连接数
	IdleConnTimeout     time.Duration // 空闲连接超时时间
	DisableKeepAlives   bool          // 禁用keep-alive
	DisableCompression  bool          // 禁用压缩
}

PoolConfig 连接池配置

type RateLimiter

type RateLimiter interface {
	Allow() bool
	Wait(ctx context.Context) error
}

RateLimiter 限流器接口

type Request

type Request struct {
	// contains filtered or unexported fields
}

Request HTTP请求构建器

func (*Request) Body

func (r *Request) Body(body io.Reader) *Request

Body 设置请求体

func (*Request) Context

func (r *Request) Context(ctx context.Context) *Request

Context 设置上下文

func (*Request) Cookie

func (r *Request) Cookie(cookie *http.Cookie) *Request

Cookie 添加Cookie

func (*Request) Do

func (r *Request) Do() (*Response, error)

Do 执行请求

func (*Request) Form

func (r *Request) Form(data url.Values) *Request

Form 设置表单请求体

func (*Request) Header

func (r *Request) Header(key, value string) *Request

Header 设置请求头

func (*Request) Headers

func (r *Request) Headers(headers map[string]string) *Request

Headers 批量设置请求头

func (*Request) JSON

func (r *Request) JSON(data interface{}) *Request

JSON 设置JSON请求体

func (*Request) Retries

func (r *Request) Retries(retries int) *Request

Retries 设置重试次数

func (*Request) Timeout

func (r *Request) Timeout(timeout time.Duration) *Request

Timeout 设置超时时间

type Response

type Response struct {
	StatusCode int
	Status     string
	Headers    http.Header
	Body       []byte
	Response   *http.Response
	Request    *http.Request
	Duration   time.Duration
}

Response HTTP响应

func Delete

func Delete(ctx context.Context, url string) (*Response, error)

Delete 发送 DELETE 请求

func Do added in v1.5.0

func Do(ctx context.Context, method, url string, body io.Reader) (*Response, error)

Do 直接执行 HTTP 请求

func Get

func Get(ctx context.Context, url string) (*Response, error)

Get 发送 GET 请求

func Patch

func Patch(ctx context.Context, url string, body io.Reader) (*Response, error)

Patch 发送 PATCH 请求

func PatchJSON

func PatchJSON(ctx context.Context, url string, data interface{}) (*Response, error)

PatchJSON 发送 JSON PATCH 请求

func Post

func Post(ctx context.Context, url string, body io.Reader) (*Response, error)

Post 发送 POST 请求

func PostJSON

func PostJSON(ctx context.Context, url string, data interface{}) (*Response, error)

PostJSON 发送 JSON POST 请求

func Put

func Put(ctx context.Context, url string, body io.Reader) (*Response, error)

Put 发送 PUT 请求

func PutJSON

func PutJSON(ctx context.Context, url string, data interface{}) (*Response, error)

PutJSON 发送 JSON PUT 请求

func (*Response) Bytes

func (r *Response) Bytes() []byte

Bytes 获取响应字节

func (*Response) Error

func (r *Response) Error() string

Error 获取错误信息

func (*Response) IsClientError

func (r *Response) IsClientError() bool

IsClientError 检查是否为客户端错误

func (*Response) IsError

func (r *Response) IsError() bool

IsError 检查是否为错误响应 (4xx + 5xx)

func (*Response) IsInformational

func (r *Response) IsInformational() bool

IsInformational 检查是否为信息性响应

func (*Response) IsOK

func (r *Response) IsOK() bool

IsOK 检查是否为OK响应 (2xx + 3xx)

func (*Response) IsRedirect

func (r *Response) IsRedirect() bool

IsRedirect 检查是否为重定向响应

func (*Response) IsServerError

func (r *Response) IsServerError() bool

IsServerError 检查是否为服务器错误

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess 检查是否为成功响应 (仅2xx)

func (*Response) JSON

func (r *Response) JSON(v interface{}) error

JSON 解析响应为JSON

func (*Response) String

func (r *Response) String() string

String 获取响应字符串

type RetryConfig

type RetryConfig struct {
	MaxRetries      int           // 最大重试次数
	InitialDelay    time.Duration // 初始延迟
	MaxDelay        time.Duration // 最大延迟
	BackoffFactor   float64       // 退避因子
	RetryableStatus []int         // 可重试的状态码
	RetryableErrors []error       // 可重试的错误类型
}

RetryConfig 重试配置

Jump to

Keyboard shortcuts

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