ghttp

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2025 License: MIT Imports: 19 Imported by: 1

README

ghttp - 功能强大的 Go HTTP 客户端

Go Version License

ghttp 是一个功能全面、性能高效、开箱即用的 Go HTTP 客户端库,提供了简洁的 API 和强大的功能。

✨ 特性

  • 🚀 高性能 - 优化的连接池和 HTTP/2 支持
  • 🔗 链式调用 - 流畅的 API 设计,支持链式调用
  • 🔄 智能重试 - 支持指数退避、抖动等多种重试策略
  • 🎯 中间件支持 - 灵活的中间件机制,支持日志、缓存、限流等
  • 📝 请求构建器 - 简单易用的请求构建模式
  • 📦 多种数据格式 - 支持 JSON、XML、表单等多种格式
  • 📤 文件上传 - 便捷的文件上传功能
  • 🍪 Cookie 管理 - 自动 Cookie 管理
  • 🔐 认证支持 - Basic Auth、Bearer Token 等
  • ⚙️ 灵活配置 - 丰富的配置选项
  • 🎨 上下文支持 - 完整的 context.Context 支持
  • 📊 响应处理 - 便捷的响应解析和处理方法

📦 安装

go get -u github.com/nicexiaonie/ghttp

🚀 快速开始

基本使用
package main

import (
    "fmt"
    "github.com/nicexiaonie/ghttp"
)

func main() {
    // GET 请求
    resp, err := ghttp.Get("https://api.example.com/users").Do()
    if err != nil {
        panic(err)
    }
    fmt.Println(resp.String())

    // POST JSON 请求
    data := map[string]interface{}{
        "name": "张三",
        "age":  25,
    }
    resp, err = ghttp.Post("https://api.example.com/users").
        JSON(data).
        Do()
    if err != nil {
        panic(err)
    }
    fmt.Println(resp.String())
}

📖 详细文档

创建客户端
使用默认客户端
// 使用包级别的快捷方法
resp, err := ghttp.Get("https://api.example.com/data").Do()
创建自定义客户端
client := ghttp.NewClient(
    ghttp.WithBaseURL("https://api.example.com"),
    ghttp.WithTimeout(30 * time.Second),
    ghttp.WithHeader("User-Agent", "MyApp/1.0"),
    ghttp.WithRetry(ghttp.DefaultRetryConfig()),
    ghttp.WithCookieJar(),
)

resp, err := client.Get("/users").Do()
HTTP 方法

支持所有标准 HTTP 方法:

// GET
resp, err := ghttp.Get("https://api.example.com/users").Do()

// POST
resp, err := ghttp.Post("https://api.example.com/users").
    JSON(data).
    Do()

// PUT
resp, err := ghttp.Put("https://api.example.com/users/1").
    JSON(data).
    Do()

// DELETE
resp, err := ghttp.Delete("https://api.example.com/users/1").Do()

// PATCH
resp, err := ghttp.Patch("https://api.example.com/users/1").
    JSON(data).
    Do()

// HEAD
resp, err := ghttp.Head("https://api.example.com/users").Do()

// OPTIONS
resp, err := ghttp.Options("https://api.example.com/users").Do()
设置请求头
// 单个请求头
resp, err := ghttp.Get("https://api.example.com/data").
    Header("Authorization", "Bearer token123").
    Header("Content-Type", "application/json").
    Do()

// 批量设置
headers := map[string]string{
    "Authorization": "Bearer token123",
    "X-Request-ID":  "req-123",
}
resp, err := ghttp.Get("https://api.example.com/data").
    Headers(headers).
    Do()
查询参数
// 单个参数
resp, err := ghttp.Get("https://api.example.com/users").
    Query("page", 1).
    Query("size", 10).
    Do()

// 批量参数
params := map[string]interface{}{
    "page":   1,
    "size":   10,
    "status": "active",
}
resp, err := ghttp.Get("https://api.example.com/users").
    QueryParams(params).
    Do()

// 从结构体设置参数
type SearchParams struct {
    Page   int    `json:"page"`
    Size   int    `json:"size"`
    Status string `json:"status"`
}
params := SearchParams{Page: 1, Size: 10, Status: "active"}
resp, err := ghttp.Get("https://api.example.com/users").
    QueryStruct(params).
    Do()
发送 JSON 数据
data := map[string]interface{}{
    "name":  "张三",
    "email": "zhangsan@example.com",
    "age":   25,
}

resp, err := ghttp.Post("https://api.example.com/users").
    JSON(data).
    Do()
发送表单数据
// URL 编码表单
resp, err := ghttp.Post("https://api.example.com/login").
    Form("username", "admin").
    Form("password", "123456").
    Do()

// 批量表单数据
formData := map[string]interface{}{
    "username": "admin",
    "password": "123456",
}
resp, err := ghttp.Post("https://api.example.com/login").
    FormData(formData).
    Do()
文件上传
// 上传单个文件
resp, err := ghttp.Post("https://api.example.com/upload").
    File("file", "/path/to/file.txt").
    Do()

// 上传多个文件和表单数据
resp, err := ghttp.Post("https://api.example.com/upload").
    File("file1", "/path/to/file1.txt").
    File("file2", "/path/to/file2.txt").
    Form("description", "My files").
    Do()

// 使用 Reader 上传
file, _ := os.Open("/path/to/file.txt")
defer file.Close()

resp, err := ghttp.Post("https://api.example.com/upload").
    FileUpload("file", ghttp.FileUpload{
        FileName: "file.txt",
        Reader:   file,
    }).
    Do()
认证
// Basic Auth
resp, err := ghttp.Get("https://api.example.com/protected").
    BasicAuth("username", "password").
    Do()

// Bearer Token
resp, err := ghttp.Get("https://api.example.com/protected").
    BearerToken("your-token-here").
    Do()
响应处理
resp, err := ghttp.Get("https://api.example.com/users").Do()
if err != nil {
    panic(err)
}

// 获取字符串
body := resp.String()

// 获取字节数组
bytes := resp.Bytes()

// 解析 JSON
type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}
var users []User
err = resp.JSON(&users)

// 解析 XML
err = resp.XML(&data)

// 保存到文件
err = resp.SaveToFile("/path/to/save.txt")

// 检查状态
if resp.IsSuccess() {
    fmt.Println("请求成功")
}

// 获取响应头
contentType := resp.GetHeader("Content-Type")

// 获取 Cookie
cookie, err := resp.GetCookie("session")
重试机制
// 使用默认重试配置(3 次重试,指数退避)
resp, err := ghttp.Get("https://api.example.com/data").
    Retry(ghttp.DefaultRetryConfig()).
    Do()

// 简单重试(仅设置次数)
resp, err := ghttp.Get("https://api.example.com/data").
    WithSimpleRetry(5).
    Do()

// 自定义重试配置
retryConfig := &ghttp.RetryConfig{
    MaxAttempts:  5,
    InitialDelay: 1 * time.Second,
    MaxDelay:     30 * time.Second,
    Multiplier:   2.0,
    Jitter:       true,
    RetryIf: func(resp *ghttp.Response, err error) bool {
        // 自定义重试条件
        if err != nil {
            return true
        }
        return resp.StatusCode >= 500
    },
}
resp, err := ghttp.Get("https://api.example.com/data").
    Retry(retryConfig).
    Do()

// 使用预定义的退避策略
resp, err := ghttp.Get("https://api.example.com/data").
    Retry(ghttp.ExponentialBackoff(1*time.Second, 2.0, 5)).
    Do()

// 固定延迟
resp, err := ghttp.Get("https://api.example.com/data").
    Retry(ghttp.FixedDelay(2*time.Second, 3)).
    Do()
上下文支持
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

resp, err := ghttp.Get("https://api.example.com/data").
    Context(ctx).
    Do()
中间件
// 使用内置中间件
client := ghttp.NewClient(
    ghttp.WithMiddleware(ghttp.LoggingMiddleware()),
    ghttp.WithMiddleware(ghttp.DebugMiddleware()),
    ghttp.WithMiddleware(ghttp.StatusCodeCheckMiddleware()),
)

// 自定义中间件
customMiddleware := func(next ghttp.HandlerFunc) ghttp.HandlerFunc {
    return func(req *http.Request) (*ghttp.Response, error) {
        // 请求前处理
        fmt.Println("Before request")
        
        resp, err := next(req)
        
        // 响应后处理
        fmt.Println("After request")
        
        return resp, err
    }
}

client := ghttp.NewClient(
    ghttp.WithMiddleware(customMiddleware),
)

// 缓存中间件
client := ghttp.NewClient(
    ghttp.WithMiddleware(ghttp.CacheMiddleware(5 * time.Minute)),
)

// 限流中间件
client := ghttp.NewClient(
    ghttp.WithMiddleware(ghttp.RateLimitMiddleware(10, time.Second)),
)

// 指标收集
metrics := &ghttp.Metrics{}
client := ghttp.NewClient(
    ghttp.WithMiddleware(ghttp.MetricsMiddleware(metrics)),
)
请求和响应钩子
resp, err := ghttp.Post("https://api.example.com/users").
    JSON(data).
    BeforeRequest(func(req *http.Request) error {
        // 请求前处理
        fmt.Println("Sending request to:", req.URL)
        return nil
    }).
    AfterResponse(func(resp *ghttp.Response) error {
        // 响应后处理
        fmt.Println("Received response with status:", resp.StatusCode)
        return nil
    }).
    Do()
高级配置
client := ghttp.NewClient(
    // 基础 URL
    ghttp.WithBaseURL("https://api.example.com"),
    
    // 超时设置
    ghttp.WithTimeout(30 * time.Second),
    
    // 连接池配置
    ghttp.WithMaxIdleConns(100),
    ghttp.WithMaxIdleConnsPerHost(10),
    
    // 代理设置
    ghttp.WithProxy("http://proxy.example.com:8080"),
    
    // TLS 配置
    ghttp.WithInsecureSkipVerify(), // 跳过证书验证(不推荐)
    
    // Cookie 支持
    ghttp.WithCookieJar(),
    
    // 默认请求头
    ghttp.WithHeader("User-Agent", "MyApp/1.0"),
    ghttp.WithHeader("Accept", "application/json"),
    
    // 调试模式
    ghttp.WithDebug(true),
)

🔧 配置选项

客户端配置
选项 说明
WithBaseURL 设置基础 URL
WithTimeout 设置超时时间
WithHeaders 设置默认请求头
WithHeader 设置单个默认请求头
WithQueryParams 设置默认查询参数
WithUserAgent 设置 User-Agent
WithTransport 自定义 Transport
WithMaxIdleConns 设置最大空闲连接数
WithMaxIdleConnsPerHost 设置每个主机的最大空闲连接数
WithProxy 设置代理
WithTLSConfig 设置 TLS 配置
WithInsecureSkipVerify 跳过 TLS 证书验证
WithCookieJar 启用 Cookie 支持
WithRetry 设置重试配置
WithMiddleware 添加中间件
WithDebug 启用调试模式
重试配置
字段 说明
MaxAttempts 最大重试次数
InitialDelay 初始延迟时间
MaxDelay 最大延迟时间
Multiplier 延迟倍数(指数退避)
Jitter 是否添加随机抖动
RetryIf 自定义重试条件函数

📊 性能优化

连接池优化
client := ghttp.NewClient(
    ghttp.WithMaxIdleConns(100),           // 最大空闲连接数
    ghttp.WithMaxIdleConnsPerHost(10),     // 每个主机的最大空闲连接数
    ghttp.WithTimeout(30 * time.Second),    // 请求超时
)
HTTP/2 支持

默认启用 HTTP/2,可获得更好的性能。

连接复用

通过连接池自动管理连接复用,减少建立连接的开销。

🤝 向后兼容

为了保持与旧版本的兼容性,提供了 ToResult() 方法:

resp, err := ghttp.Get("https://api.example.com/data").Do()
if err != nil {
    panic(err)
}

// 转换为旧版本的 Result 结构
result := resp.ToResult()
fmt.Println(result.Body)
fmt.Println(result.StatusCode)

📝 最佳实践

  1. 复用客户端 - 创建一个客户端实例并在整个应用中复用
  2. 使用上下文 - 为请求设置超时和取消机制
  3. 配置重试 - 对于不稳定的网络请求,使用重试机制
  4. 处理错误 - 始终检查错误和响应状态码
  5. 关闭响应 - 响应会自动关闭,无需手动处理
  6. 连接池配置 - 根据实际负载调整连接池大小

🔍 示例

更多示例请查看 examples 目录。

📄 许可证

MIT License

🙏 贡献

欢迎提交 Issue 和 Pull Request!

📮 联系方式

如有问题或建议,请提交 Issue。

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultRetryCondition

func DefaultRetryCondition(resp *Response, err error) bool

DefaultRetryCondition 默认重试条件 重试以下情况: 1. 网络错误 2. 5xx 服务器错误 3. 408 请求超时 4. 429 请求过多

func IsRetryableError

func IsRetryableError(err error) bool

IsRetryableError 检查是否为可重试错误

func IsTemporaryError

func IsTemporaryError(err error) bool

IsTemporaryError 判断是否为临时错误(网络相关)

func RetryAlways

func RetryAlways() func(*Response, error) bool

RetryAlways 总是重试

func RetryNever

func RetryNever() func(*Response, error) bool

RetryNever 从不重试

func RetryOnError

func RetryOnError() func(*Response, error) bool

RetryOnError 仅在发生错误时重试(忽略状态码)

func RetryOnStatusCodes

func RetryOnStatusCodes(codes ...int) func(*Response, error) bool

RetryOnStatusCodes 根据状态码重试

func SetDefaultClient

func SetDefaultClient(client *Client)

SetDefaultClient 设置默认客户端

Types

type BasicAuth

type BasicAuth struct {
	Username string
	Password string
}

BasicAuth HTTP Basic 认证

type Client

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

Client HTTP 客户端,支持丰富的配置选项

func NewClient

func NewClient(options ...ClientOption) *Client

NewClient 创建新的 HTTP 客户端

func (*Client) Delete

func (c *Client) Delete(url string) *RequestBuilder

Delete 发送 DELETE 请求(快捷方法)

func (*Client) Get

func (c *Client) Get(url string) *RequestBuilder

Get 发送 GET 请求(快捷方法)

func (*Client) Head

func (c *Client) Head(url string) *RequestBuilder

Head 发送 HEAD 请求(快捷方法)

func (*Client) Options

func (c *Client) Options(url string) *RequestBuilder

Options 发送 OPTIONS 请求(快捷方法)

func (*Client) Patch

func (c *Client) Patch(url string) *RequestBuilder

Patch 发送 PATCH 请求(快捷方法)

func (*Client) Post

func (c *Client) Post(url string) *RequestBuilder

Post 发送 POST 请求(快捷方法)

func (*Client) Put

func (c *Client) Put(url string) *RequestBuilder

Put 发送 PUT 请求(快捷方法)

func (*Client) Request

func (c *Client) Request() *RequestBuilder

Request 创建新的请求构建器

type ClientOption

type ClientOption func(*Client)

ClientOption 客户端配置选项函数

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL 设置基础 URL

func WithCookieJar

func WithCookieJar() ClientOption

WithCookieJar 启用 Cookie 支持

func WithCustomCookieJar

func WithCustomCookieJar(jar http.CookieJar) ClientOption

WithCustomCookieJar 使用自定义 CookieJar

func WithDebug

func WithDebug(debug bool) ClientOption

WithDebug 启用调试模式

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient 使用自定义的 http.Client

func WithHeader

func WithHeader(key, value string) ClientOption

WithHeader 设置单个默认请求头

func WithHeaders

func WithHeaders(headers map[string]string) ClientOption

WithHeaders 设置默认请求头

func WithInsecureSkipVerify

func WithInsecureSkipVerify() ClientOption

WithInsecureSkipVerify 跳过 TLS 证书验证(不推荐在生产环境使用)

func WithMaxIdleConns

func WithMaxIdleConns(n int) ClientOption

WithMaxIdleConns 设置最大空闲连接数

func WithMaxIdleConnsPerHost

func WithMaxIdleConnsPerHost(n int) ClientOption

WithMaxIdleConnsPerHost 设置每个主机的最大空闲连接数

func WithMiddleware

func WithMiddleware(middleware Middleware) ClientOption

WithMiddleware 添加中间件

func WithProxy

func WithProxy(proxyURL string) ClientOption

WithProxy 设置代理

func WithQueryParams

func WithQueryParams(params map[string]string) ClientOption

WithQueryParams 设置默认查询参数

func WithRetry

func WithRetry(config *RetryConfig) ClientOption

WithRetry 设置重试配置

func WithTLSConfig

func WithTLSConfig(config *tls.Config) ClientOption

WithTLSConfig 设置 TLS 配置

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout 设置超时时间

func WithTransport

func WithTransport(transport *http.Transport) ClientOption

WithTransport 自定义 Transport

func WithUserAgent

func WithUserAgent(ua string) ClientOption

WithUserAgent 设置 User-Agent

type FileUpload

type FileUpload struct {
	FileName string
	Reader   io.Reader
	FileSize int64
}

FileUpload 文件上传配置

type HandlerFunc

type HandlerFunc func(*http.Request) (*Response, error)

HandlerFunc 处理函数类型

type Metrics

type Metrics struct {
	TotalRequests   int64
	SuccessRequests int64
	FailedRequests  int64
	TotalDuration   time.Duration
}

MetricsMiddleware 指标收集中间件

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

Middleware 中间件类型

func AuthMiddleware

func AuthMiddleware(token string) Middleware

AuthMiddleware 认证中间件

func CacheMiddleware

func CacheMiddleware(ttl time.Duration) Middleware

func ComposeMiddlewares

func ComposeMiddlewares(middlewares ...Middleware) Middleware

ComposeMiddlewares 组合多个中间件

func DebugMiddleware

func DebugMiddleware() Middleware

DebugMiddleware 调试中间件(打印详细信息)

func ErrorHandlerMiddleware

func ErrorHandlerMiddleware(handler func(*Response, error) error) Middleware

ErrorHandlerMiddleware 错误处理中间件

func LoggingMiddleware

func LoggingMiddleware() Middleware

LoggingMiddleware 日志中间件

func MetricsMiddleware

func MetricsMiddleware(metrics *Metrics) Middleware

func RateLimitMiddleware

func RateLimitMiddleware(maxRequests int, duration time.Duration) Middleware

RateLimitMiddleware 限流中间件

func RetryCountMiddleware

func RetryCountMiddleware() Middleware

RetryCountMiddleware 重试计数中间件(记录重试次数到 context)

func StatusCodeCheckMiddleware

func StatusCodeCheckMiddleware() Middleware

StatusCodeCheckMiddleware 状态码检查中间件

func TimeoutMiddleware

func TimeoutMiddleware(timeout time.Duration) Middleware

TimeoutMiddleware 超时中间件

func UserAgentMiddleware

func UserAgentMiddleware(userAgent string) Middleware

UserAgentMiddleware 设置 User-Agent 中间件

type RequestBuilder

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

RequestBuilder 请求构建器,支持链式调用

func Delete

func Delete(url string) *RequestBuilder

Delete 使用默认客户端发送 DELETE 请求

func Get

func Get(url string) *RequestBuilder

Get 使用默认客户端发送 GET 请求

func Head(url string) *RequestBuilder

Head 使用默认客户端发送 HEAD 请求

func Options

func Options(url string) *RequestBuilder

Options 使用默认客户端发送 OPTIONS 请求

func Patch

func Patch(url string) *RequestBuilder

Patch 使用默认客户端发送 PATCH 请求

func Post

func Post(url string) *RequestBuilder

Post 使用默认客户端发送 POST 请求

func Put

func Put(url string) *RequestBuilder

Put 使用默认客户端发送 PUT 请求

func (*RequestBuilder) AfterResponse

func (rb *RequestBuilder) AfterResponse(hook func(*Response) error) *RequestBuilder

AfterResponse 添加响应后钩子

func (*RequestBuilder) BasicAuth

func (rb *RequestBuilder) BasicAuth(username, password string) *RequestBuilder

BasicAuth 设置 HTTP Basic 认证

func (*RequestBuilder) BearerToken

func (rb *RequestBuilder) BearerToken(token string) *RequestBuilder

BearerToken 设置 Bearer Token

func (*RequestBuilder) BeforeRequest

func (rb *RequestBuilder) BeforeRequest(hook func(*http.Request) error) *RequestBuilder

BeforeRequest 添加请求前钩子

func (*RequestBuilder) Body

func (rb *RequestBuilder) Body(body io.Reader) *RequestBuilder

Body 设置原始 body

func (*RequestBuilder) BodyBytes

func (rb *RequestBuilder) BodyBytes(data []byte) *RequestBuilder

BodyBytes 设置字节数组 body

func (*RequestBuilder) BodyString

func (rb *RequestBuilder) BodyString(data string) *RequestBuilder

BodyString 设置字符串 body

func (*RequestBuilder) ContentType

func (rb *RequestBuilder) ContentType(contentType string) *RequestBuilder

ContentType 设置 Content-Type

func (*RequestBuilder) Context

func (rb *RequestBuilder) Context(ctx context.Context) *RequestBuilder

Context 设置上下文

func (*RequestBuilder) Delete

func (rb *RequestBuilder) Delete(url string) *RequestBuilder

Delete 设置为 DELETE 请求

func (*RequestBuilder) Do

func (rb *RequestBuilder) Do() (*Response, error)

Do 执行请求

func (*RequestBuilder) File

func (rb *RequestBuilder) File(fieldName, filePath string) *RequestBuilder

File 添加文件上传(通过文件路径)

func (*RequestBuilder) FileUpload

func (rb *RequestBuilder) FileUpload(fieldName string, upload FileUpload) *RequestBuilder

FileUpload 添加文件上传(通过 Reader)

func (*RequestBuilder) Form

func (rb *RequestBuilder) Form(key string, value interface{}) *RequestBuilder

Form 设置表单字段

func (*RequestBuilder) FormData

func (rb *RequestBuilder) FormData(data map[string]interface{}) *RequestBuilder

FormData 批量设置表单数据

func (*RequestBuilder) Get

func (rb *RequestBuilder) Get(url string) *RequestBuilder

Get 设置为 GET 请求

func (*RequestBuilder) Head

func (rb *RequestBuilder) Head(url string) *RequestBuilder

Head 设置为 HEAD 请求

func (*RequestBuilder) Header

func (rb *RequestBuilder) Header(key, value string) *RequestBuilder

Header 设置请求头

func (*RequestBuilder) Headers

func (rb *RequestBuilder) Headers(headers map[string]string) *RequestBuilder

Headers 批量设置请求头

func (*RequestBuilder) JSON

func (rb *RequestBuilder) JSON(data interface{}) *RequestBuilder

JSON 设置 JSON body

func (*RequestBuilder) Method

func (rb *RequestBuilder) Method(method string) *RequestBuilder

Method 设置请求方法

func (*RequestBuilder) Options

func (rb *RequestBuilder) Options(url string) *RequestBuilder

Options 设置为 OPTIONS 请求

func (*RequestBuilder) Patch

func (rb *RequestBuilder) Patch(url string) *RequestBuilder

Patch 设置为 PATCH 请求

func (*RequestBuilder) Post

func (rb *RequestBuilder) Post(url string) *RequestBuilder

Post 设置为 POST 请求

func (*RequestBuilder) Put

func (rb *RequestBuilder) Put(url string) *RequestBuilder

Put 设置为 PUT 请求

func (*RequestBuilder) Query

func (rb *RequestBuilder) Query(key string, value interface{}) *RequestBuilder

Query 添加查询参数

func (*RequestBuilder) QueryParams

func (rb *RequestBuilder) QueryParams(params map[string]interface{}) *RequestBuilder

QueryParams 批量添加查询参数

func (*RequestBuilder) QueryStruct

func (rb *RequestBuilder) QueryStruct(v interface{}) *RequestBuilder

QueryStruct 从结构体设置查询参数(使用 json tag)

func (*RequestBuilder) Retry

func (rb *RequestBuilder) Retry(config *RetryConfig) *RequestBuilder

Retry 设置重试配置

func (*RequestBuilder) WithRetryConfig

func (rb *RequestBuilder) WithRetryConfig(config *RetryConfig) *RequestBuilder

WithRetryConfig 创建带重试配置的请求

func (*RequestBuilder) WithSimpleRetry

func (rb *RequestBuilder) WithSimpleRetry(maxAttempts int) *RequestBuilder

WithSimpleRetry 简单重试配置(仅设置次数)

func (*RequestBuilder) XML

func (rb *RequestBuilder) XML(data interface{}) *RequestBuilder

XML 设置 XML body

type Response

type Response struct {
	*http.Response
	// contains filtered or unexported fields
}

Response HTTP 响应包装器,提供便捷的响应处理方法

func NewResponse

func NewResponse(resp *http.Response) (*Response, error)

NewResponse 创建响应包装器

func (*Response) Bytes

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

Bytes 返回原始字节数组

func (*Response) Clone

func (r *Response) Clone() *Response

Clone 克隆响应(用于需要多次读取的场景)

func (*Response) ContentType

func (r *Response) ContentType() string

ContentType 获取响应的 Content-Type

func (*Response) Error

func (r *Response) Error() error

Error 返回响应错误

func (*Response) GetCookie

func (r *Response) GetCookie(name string) (*http.Cookie, error)

GetCookie 获取 Cookie

func (*Response) GetHeader

func (r *Response) GetHeader(key string) string

GetHeader 获取响应头

func (*Response) GetHeaders

func (r *Response) GetHeaders(key string) []string

GetHeaders 获取所有指定名称的响应头

func (*Response) IsClientError

func (r *Response) IsClientError() bool

IsClientError 检查是否为客户端错误(状态码 4xx)

func (*Response) IsEmpty

func (r *Response) IsEmpty() bool

IsEmpty 检查响应体是否为空

func (*Response) IsHTML

func (r *Response) IsHTML() bool

IsHTML 检查响应是否为 HTML

func (*Response) IsJSON

func (r *Response) IsJSON() bool

IsJSON 检查响应是否为 JSON

func (*Response) IsServerError

func (r *Response) IsServerError() bool

IsServerError 检查是否为服务器错误(状态码 5xx)

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess 检查响应是否成功(状态码 2xx)

func (*Response) IsXML

func (r *Response) IsXML() bool

IsXML 检查响应是否为 XML

func (*Response) JSON

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

JSON 将响应体解析为 JSON

func (*Response) RawResponse

func (r *Response) RawResponse() *http.Response

RawResponse 获取原始的 http.Response(用于需要直接访问的场景)

func (*Response) SaveToFile

func (r *Response) SaveToFile(filename string) error

SaveToFile 将响应保存到文件

func (*Response) Size

func (r *Response) Size() int

Size 返回响应体的大小(字节)

func (*Response) StatusIs

func (r *Response) StatusIs(code int) bool

StatusIs 检查状态码是否匹配

func (*Response) String

func (r *Response) String() string

String 返回字符串形式的响应体

func (*Response) ToResult

func (r *Response) ToResult() Result

ToResult 转换为旧版本的 Result 结构(向后兼容)

func (*Response) XML

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

XML 将响应体解析为 XML

type Result

type Result struct {
	StatusCode    int
	Status        string
	Body          string
	Header        http.Header
	ContentLength int64
}

Result 兼容旧版本的结果结构(向后兼容)

type RetryCallback

type RetryCallback func(attempt int, resp *Response, err error)

WithRetryCallback 添加重试回调

type RetryConfig

type RetryConfig struct {
	// MaxAttempts 最大重试次数(包括首次请求)
	MaxAttempts int

	// InitialDelay 初始延迟时间
	InitialDelay time.Duration

	// MaxDelay 最大延迟时间
	MaxDelay time.Duration

	// Multiplier 延迟倍数(用于指数退避)
	Multiplier float64

	// Jitter 是否添加随机抖动(避免惊群效应)
	Jitter bool

	// RetryIf 自定义重试条件函数
	RetryIf func(*Response, error) bool
}

RetryConfig 重试配置

func DefaultRetryConfig

func DefaultRetryConfig() *RetryConfig

DefaultRetryConfig 默认重试配置

func ExponentialBackoff

func ExponentialBackoff(initialDelay time.Duration, multiplier float64, maxAttempts int) *RetryConfig

ExponentialBackoff 指数退避策略

func FixedDelay

func FixedDelay(delay time.Duration, maxAttempts int) *RetryConfig

FixedDelay 固定延迟策略

func LinearBackoff

func LinearBackoff(initialDelay, increment time.Duration) *RetryConfig

LinearBackoff 线性退避策略

func NewRetryConfig

func NewRetryConfig(maxAttempts int) *RetryConfig

NewRetryConfig 创建新的重试配置

func RetryWithCallback

func RetryWithCallback(callback RetryCallback) *RetryConfig

RetryWithCallback 带回调的重试执行器

type RetryableError

type RetryableError struct {
	Err         error
	Attempt     int
	MaxAttempts int
}

RetryableError 可重试的错误类型

func (*RetryableError) Error

func (e *RetryableError) Error() string

func (*RetryableError) Unwrap

func (e *RetryableError) Unwrap() error

Directories

Path Synopsis
examples
advanced command
auth command
basic command
file-upload command
form command
json command

Jump to

Keyboard shortcuts

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