httpclient

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

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

Functions

func SetBaseURL

func SetBaseURL(baseURL string)

func SetDefaultClient

func SetDefaultClient(client *Client)

func SetHeader

func SetHeader(key, value string)

func SetHeaders

func SetHeaders(headers map[string]string)

func SetTimeout

func SetTimeout(timeout time.Duration)

Types

type CircuitBreaker

type CircuitBreaker interface {
	Execute(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

func NewClient

func NewClient() *Client

NewClient 创建新的HTTP客户端

func NewClientWithOptions

func NewClientWithOptions(opts ClientOptions) *Client

NewClientWithOptions 根据选项创建HTTP客户端

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(url string) (*Response, error)

Delete 发送DELETE请求

func (*Client) DisableDebug

func (c *Client) DisableDebug()

DisableDebug 禁用Debug模式

func (*Client) EnableDebug

func (c *Client) EnableDebug()

EnableDebug 启用Debug模式

func (*Client) Get

func (c *Client) Get(url string) (*Response, error)

Get 发送GET请求

func (*Client) NewRequest

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

NewRequest 创建新的请求构建器

func (*Client) Patch

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

Patch 发送PATCH请求

func (*Client) PatchJSON

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

PatchJSON 发送JSON PATCH请求

func (*Client) Post

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

Post 发送POST请求

func (*Client) PostJSON

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

PostJSON 发送JSON POST请求

func (*Client) Put

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

Put 发送PUT请求

func (*Client) PutJSON

func (c *Client) PutJSON(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 设置超时时间

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配置
}

ClientOptions HTTP客户端选项

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(msg string, fields ...interface{})
	Info(msg string, fields ...interface{})
	Warn(msg string, fields ...interface{})
	Error(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 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 设置超时时间

func (*Request) WithCtx

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

WithCtx 设置上下文 (Context方法的简洁版本)

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(url string) (*Response, error)

func Get

func Get(url string) (*Response, error)

全局函数

func Patch

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

func PatchJSON

func PatchJSON(url string, data interface{}) (*Response, error)

func Post

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

func PostJSON

func PostJSON(url string, data interface{}) (*Response, error)

func Put

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

func PutJSON

func PutJSON(url string, data interface{}) (*Response, error)

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