httpclient

package
v0.0.0-...-09790a5 Latest Latest
Warning

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

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

README

HTTP Client - 类似 PHP Guzzle 的 Go HTTP 客户端

一个功能强大、易用的 Go HTTP 客户端库,类似于 PHP 的 Guzzle,支持链式调用、中间件、文件上传下载、代理、证书等完整功能。


✨ 特性

  • 链式调用 - 优雅的 API 设计
  • GET/POST/PUT/PATCH/DELETE - 支持所有 HTTP 方法
  • JSON/XML/Form - 多种数据格式支持
  • 文件上传/下载 - 支持单文件、多文件、断点续传
  • 中间件系统 - 请求/响应拦截器
  • 代理支持 - HTTP/SOCKS5 代理
  • SSL/TLS - 客户端证书、跳过验证
  • 超时和重试 - 可配置的超时和重试机制
  • Cookie 管理 - 自动 Cookie 管理
  • Context 支持 - 支持 context 取消
  • 日志记录 - 可选的请求/响应日志

📦 安装

go get golang.org/x/net/proxy

🚀 快速开始

1. 从容器获取客户端(推荐)
// 从容器获取已配置的 HTTP 客户端
client := container.GetHTTPClient()

// 发送 GET 请求
resp, err := client.Get("https://api.example.com/users").Send()
if err != nil {
    panic(err)
}
defer resp.Close()

// 解析 JSON 响应
var users []User
resp.JSON(&users)
2. 创建独立客户端
import "github.com/lvjiaben/go-wheel/pkg/httpclient"

// 创建基础客户端
client := httpclient.NewClient()

// 创建带配置的客户端
client := httpclient.NewClient(
    httpclient.WithBaseURL("https://api.example.com"),
    httpclient.WithTimeout(30*time.Second),
    httpclient.WithHeaders(map[string]string{
        "User-Agent": "MyApp/1.0",
    }),
)

📖 使用示例

GET 请求
// 简单 GET 请求
resp, err := client.Get("/users").Send()

// 带查询参数
resp, err := client.Get("/users").
    SetQuery("page", "1").
    SetQuery("limit", "10").
    Send()

// 批量设置查询参数
resp, err := client.Get("/users").
    SetQueryParams(map[string]string{
        "page":  "1",
        "limit": "10",
        "sort":  "created_at",
    }).
    Send()
POST 请求
// POST JSON 数据
data := map[string]interface{}{
    "username": "admin",
    "password": "123456",
}
resp, err := client.Post("/login").
    SetJSON(data).
    Send()

// POST 表单数据
resp, err := client.Post("/form").
    SetForm("name", "John").
    SetForm("email", "john@example.com").
    Send()

// 批量设置表单数据
resp, err := client.Post("/form").
    SetFormData(map[string]string{
        "name":  "John",
        "email": "john@example.com",
    }).
    Send()
设置 Headers
resp, err := client.Get("/api/data").
    SetHeader("Authorization", "Bearer token123").
    SetHeader("Content-Type", "application/json").
    Send()

// 批量设置
resp, err := client.Get("/api/data").
    SetHeaders(map[string]string{
        "Authorization": "Bearer token123",
        "X-Custom-Header": "value",
    }).
    Send()
认证
// Bearer Token
resp, err := client.Get("/api/protected").
    SetBearerToken("your-token-here").
    Send()

// Basic Auth
resp, err := client.Get("/api/protected").
    SetBasicAuth("username", "password").
    Send()
文件上传
// 上传单个文件
resp, err := client.UploadFile("/upload", "file", "/path/to/file.jpg")

// 上传多个文件
resp, err := client.UploadFiles("/upload", map[string]string{
    "file1": "/path/to/file1.jpg",
    "file2": "/path/to/file2.jpg",
})

// 上传文件并附带表单数据
resp, err := client.UploadFileWithData(
    "/upload",
    "file",
    "/path/to/file.jpg",
    map[string]string{
        "title": "My Photo",
        "description": "A beautiful photo",
    },
)

// 使用 Request 方式
resp, err := client.Post("/upload").
    SetFile("avatar", "/path/to/avatar.jpg").
    SetForm("user_id", "123").
    Send()
文件下载
// 下载文件
err := client.DownloadFile("https://example.com/file.zip", "/path/to/save.zip")

// 下载文件(带进度)
err := client.DownloadFileWithProgress(
    "https://example.com/large-file.zip",
    "/path/to/save.zip",
    func(downloaded, total int64) {
        percent := float64(downloaded) / float64(total) * 100
        fmt.Printf("下载进度: %.2f%%\n", percent)
    },
)

// 断点续传下载
err := client.DownloadFileResume("https://example.com/large-file.zip", "/path/to/save.zip")

// 获取文件信息
fileInfo, err := client.GetFileInfo("https://example.com/file.zip")
fmt.Printf("文件大小: %d bytes\n", fileInfo.Size)
响应处理
resp, err := client.Get("/api/data").Send()
if err != nil {
    panic(err)
}
defer resp.Close()

// 获取响应字符串
body, _ := resp.String()

// 解析 JSON
var result map[string]interface{}
resp.JSON(&result)

// 解析 XML
var xmlResult struct {
    Status string `xml:"status"`
}
resp.XML(&xmlResult)

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

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

// 获取 Cookie
cookie := resp.GetCookie("session_id")

// 保存到文件
resp.SaveToFile("/path/to/response.json")
超时和重试
resp, err := client.Get("/api/slow").
    SetTimeout(5 * time.Second).
    SetRetry(3, time.Second).
    Send()
Context 支持
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

resp, err := client.Get("/api/data").
    WithContext(ctx).
    Send()

🔧 高级配置

代理
// HTTP 代理
client := httpclient.NewClient(
    httpclient.WithProxy("http://proxy.example.com:8080"),
)

// SOCKS5 代理
client := httpclient.NewClient(
    httpclient.WithSocks5Proxy("127.0.0.1:1080"),
)
SSL/TLS
// 跳过 SSL 验证(不推荐生产环境)
client := httpclient.NewClient(
    httpclient.WithInsecureSkipVerify(),
)

// 使用客户端证书
client := httpclient.NewClient(
    httpclient.WithCertificates("/path/to/cert.pem", "/path/to/key.pem"),
)

// 自定义 TLS 配置
tlsConfig := &tls.Config{
    MinVersion: tls.VersionTLS12,
}
client := httpclient.NewClient(
    httpclient.WithTLSConfig(tlsConfig),
)
中间件
// 日志中间件
client := httpclient.NewClient(
    httpclient.WithMiddleware(httpclient.NewLoggingMiddleware(logger)),
)

// 认证中间件
client := httpclient.NewClient(
    httpclient.WithMiddleware(httpclient.NewAuthMiddleware("your-token")),
)

// 自定义 Header 中间件
client := httpclient.NewClient(
    httpclient.WithMiddleware(httpclient.NewCustomHeaderMiddleware(map[string]string{
        "X-API-Key": "your-api-key",
    })),
)

// 调试中间件
client := httpclient.NewClient(
    httpclient.WithMiddleware(httpclient.NewDebugMiddleware(logger)),
)

📝 完整示例

package main

import (
    "fmt"
    "time"
    "github.com/lvjiaben/go-wheel/pkg/httpclient"
)

func main() {
    // 创建客户端
    client := httpclient.NewClient(
        httpclient.WithBaseURL("https://api.example.com"),
        httpclient.WithTimeout(30*time.Second),
        httpclient.WithRetry(3, time.Second),
        httpclient.WithHeaders(map[string]string{
            "User-Agent": "MyApp/1.0",
        }),
    )

    // 发送请求
    resp, err := client.Post("/api/users").
        SetHeader("Authorization", "Bearer token123").
        SetQuery("notify", "true").
        SetJSON(map[string]interface{}{
            "name":  "John Doe",
            "email": "john@example.com",
            "age":   30,
        }).
        Send()

    if err != nil {
        panic(err)
    }
    defer resp.Close()

    // 处理响应
    if resp.IsSuccess() {
        var user User
        resp.JSON(&user)
        fmt.Printf("创建用户成功: %+v\n", user)
    } else {
        body, _ := resp.String()
        fmt.Printf("请求失败: %s\n", body)
    }
}

type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

🎯 与 PHP Guzzle 对比

功能 Guzzle (PHP) httpclient (Go)
链式调用
中间件
文件上传
文件下载
代理支持
SSL/TLS
超时重试
Cookie 管理
异步请求 ✅ (通过 goroutine)

📚 更多示例

查看 example.go 文件获取更多使用示例。


🤝 贡献

欢迎提交 Issue 和 Pull Request!


📄 许可证

MIT License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Example

func Example()

Example 使用示例(仅供参考,不会被编译)

Types

type AuthMiddleware

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

AuthMiddleware 认证中间件

func NewAuthMiddleware

func NewAuthMiddleware(token string) *AuthMiddleware

NewAuthMiddleware 创建认证中间件

func (*AuthMiddleware) AfterResponse

func (m *AuthMiddleware) AfterResponse(resp *Response) error

AfterResponse 响应后处理

func (*AuthMiddleware) BeforeRequest

func (m *AuthMiddleware) BeforeRequest(req *http.Request) error

BeforeRequest 请求前添加认证信息

type Client

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

Client HTTP 客户端(类似 Guzzle)

func NewClient

func NewClient(options ...ClientOption) *Client

NewClient 创建 HTTP 客户端

func (*Client) Delete

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

Delete 发送 DELETE 请求

func (*Client) DownloadFile

func (c *Client) DownloadFile(url, savePath string) error

DownloadFile 下载文件

func (*Client) DownloadFileResume

func (c *Client) DownloadFileResume(url, savePath string) error

DownloadFileResume 断点续传下载

func (*Client) DownloadFileWithProgress

func (c *Client) DownloadFileWithProgress(url, savePath string, callback func(downloaded, total int64)) error

DownloadFileWithProgress 下载文件(带进度回调)

func (*Client) DownloadToWriter

func (c *Client) DownloadToWriter(url string, writer io.Writer) error

DownloadToWriter 下载到 Writer

func (*Client) Get

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

Get 发送 GET 请求

func (*Client) GetFileInfo

func (c *Client) GetFileInfo(url string) (*FileInfo, error)

GetFileInfo 获取远程文件信息

func (*Client) Head

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

Head 发送 HEAD 请求

func (*Client) NewRequest

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

NewRequest 创建新请求

func (*Client) Options

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

Options 发送 OPTIONS 请求

func (*Client) Patch

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

Patch 发送 PATCH 请求

func (*Client) Post

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

Post 发送 POST 请求

func (*Client) Put

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

Put 发送 PUT 请求

func (*Client) SetCookie

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

SetCookie 设置 Cookie

func (*Client) SetHeader

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

SetHeader 设置单个 Header

func (*Client) SetHeaders

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

SetHeaders 批量设置 Headers

func (*Client) SetRetry

func (c *Client) SetRetry(count int, delay time.Duration) *Client

SetRetry 设置重试配置

func (*Client) SetTimeout

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

SetTimeout 设置超时时间

func (*Client) UploadFile

func (c *Client) UploadFile(url, fieldName, filePath string) (*Response, error)

UploadFile 上传单个文件

func (*Client) UploadFileWithData

func (c *Client) UploadFileWithData(url, fieldName, filePath string, formData map[string]string) (*Response, error)

UploadFileWithData 上传文件并附带表单数据

func (*Client) UploadFiles

func (c *Client) UploadFiles(url string, files map[string]string) (*Response, error)

UploadFiles 上传多个文件

func (*Client) UploadFromReader

func (c *Client) UploadFromReader(url string, reader io.Reader, contentType string) (*Response, error)

UploadFromReader 从 Reader 上传数据

type ClientOption

type ClientOption func(*Client)

ClientOption 客户端配置选项

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL 设置基础 URL

func WithCertificates

func WithCertificates(certFile, keyFile string) ClientOption

WithCertificates 设置客户端证书

func WithCookieJar

func WithCookieJar(jar http.CookieJar) ClientOption

WithCookieJar 设置 Cookie Jar

func WithDebug

func WithDebug(debug bool) ClientOption

WithDebug 启用调试模式

func WithHeaders

func WithHeaders(headers map[string]string) ClientOption

WithHeaders 设置默认 Headers

func WithInsecureSkipVerify

func WithInsecureSkipVerify() ClientOption

WithInsecureSkipVerify 跳过 SSL 证书验证(不推荐生产环境)

func WithLogger

func WithLogger(logger Logger) ClientOption

WithLogger 设置日志记录器

func WithMiddleware

func WithMiddleware(middleware Middleware) ClientOption

WithMiddleware 添加中间件

func WithProxy

func WithProxy(proxyURL string) ClientOption

WithProxy 设置 HTTP 代理

func WithRetry

func WithRetry(count int, delay time.Duration) ClientOption

WithRetry 设置重试配置

func WithSocks5Proxy

func WithSocks5Proxy(proxyAddr string) ClientOption

WithSocks5Proxy 设置 SOCKS5 代理

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

type CustomHeaderMiddleware

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

CustomHeaderMiddleware 自定义 Header 中间件

func NewCustomHeaderMiddleware

func NewCustomHeaderMiddleware(headers map[string]string) *CustomHeaderMiddleware

NewCustomHeaderMiddleware 创建自定义 Header 中间件

func (*CustomHeaderMiddleware) AfterResponse

func (m *CustomHeaderMiddleware) AfterResponse(resp *Response) error

AfterResponse 响应后处理

func (*CustomHeaderMiddleware) BeforeRequest

func (m *CustomHeaderMiddleware) BeforeRequest(req *http.Request) error

BeforeRequest 请求前添加自定义 Header

type DebugMiddleware

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

DebugMiddleware 调试中间件

func NewDebugMiddleware

func NewDebugMiddleware(logger Logger) *DebugMiddleware

NewDebugMiddleware 创建调试中间件

func (*DebugMiddleware) AfterResponse

func (m *DebugMiddleware) AfterResponse(resp *Response) error

AfterResponse 响应后打印调试信息

func (*DebugMiddleware) BeforeRequest

func (m *DebugMiddleware) BeforeRequest(req *http.Request) error

BeforeRequest 请求前打印调试信息

type ErrorHandlerMiddleware

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

ErrorHandlerMiddleware 错误处理中间件

func NewErrorHandlerMiddleware

func NewErrorHandlerMiddleware(handler func(*Response) error) *ErrorHandlerMiddleware

NewErrorHandlerMiddleware 创建错误处理中间件

func (*ErrorHandlerMiddleware) AfterResponse

func (m *ErrorHandlerMiddleware) AfterResponse(resp *Response) error

AfterResponse 响应后处理错误

func (*ErrorHandlerMiddleware) BeforeRequest

func (m *ErrorHandlerMiddleware) BeforeRequest(req *http.Request) error

BeforeRequest 请求前处理

type FileInfo

type FileInfo struct {
	Size        int64
	ContentType string
	FileName    string
	AcceptRange bool
}

FileInfo 文件信息

type Logger

type Logger interface {
	Debug(msg string, fields ...interface{})
	Info(msg string, fields ...interface{})
	Error(msg string, fields ...interface{})
}

Logger 日志接口

type LoggingMiddleware

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

LoggingMiddleware 日志中间件

func NewLoggingMiddleware

func NewLoggingMiddleware(logger Logger) *LoggingMiddleware

NewLoggingMiddleware 创建日志中间件

func (*LoggingMiddleware) AfterResponse

func (m *LoggingMiddleware) AfterResponse(resp *Response) error

AfterResponse 响应后记录日志

func (*LoggingMiddleware) BeforeRequest

func (m *LoggingMiddleware) BeforeRequest(req *http.Request) error

BeforeRequest 请求前记录日志

type Middleware

type Middleware interface {
	BeforeRequest(req *http.Request) error
	AfterResponse(resp *Response) error
}

Middleware 中间件接口

type RateLimitMiddleware

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

RateLimitMiddleware 限流中间件

func NewRateLimitMiddleware

func NewRateLimitMiddleware(requestsPerSecond int) *RateLimitMiddleware

NewRateLimitMiddleware 创建限流中间件

func (*RateLimitMiddleware) AfterResponse

func (m *RateLimitMiddleware) AfterResponse(resp *Response) error

AfterResponse 响应后处理

func (*RateLimitMiddleware) BeforeRequest

func (m *RateLimitMiddleware) BeforeRequest(req *http.Request) error

BeforeRequest 请求前限流

type Request

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

Request HTTP 请求构建器

func (*Request) Send

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

Send 发送请求

func (*Request) SetBasicAuth

func (r *Request) SetBasicAuth(username, password string) *Request

SetBasicAuth 设置 Basic 认证

func (*Request) SetBearerToken

func (r *Request) SetBearerToken(token string) *Request

SetBearerToken 设置 Bearer Token

func (*Request) SetBody

func (r *Request) SetBody(body interface{}) *Request

SetBody 设置原始请求体

func (*Request) SetBodyReader

func (r *Request) SetBodyReader(reader io.Reader) *Request

SetBodyReader 设置请求体 Reader

func (*Request) SetCookie

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

SetCookie 设置 Cookie

func (*Request) SetFile

func (r *Request) SetFile(fieldName, filePath string) *Request

SetFile 设置单个文件上传

func (*Request) SetFiles

func (r *Request) SetFiles(files map[string]string) *Request

SetFiles 批量设置文件上传

func (*Request) SetForm

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

SetForm 设置单个表单字段

func (*Request) SetFormData

func (r *Request) SetFormData(data map[string]string) *Request

SetFormData 批量设置表单数据

func (*Request) SetHeader

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

SetHeader 设置单个 Header

func (*Request) SetHeaders

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

SetHeaders 批量设置 Headers

func (*Request) SetJSON

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

SetJSON 设置 JSON 请求体

func (*Request) SetQuery

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

SetQuery 设置单个查询参数

func (*Request) SetQueryParams

func (r *Request) SetQueryParams(params map[string]string) *Request

SetQueryParams 批量设置查询参数

func (*Request) SetRetry

func (r *Request) SetRetry(count int, delay time.Duration) *Request

SetRetry 设置重试配置

func (*Request) SetTimeout

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

SetTimeout 设置超时时间

func (*Request) SetXML

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

SetXML 设置 XML 请求体

func (*Request) WithContext

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

WithContext 设置上下文

type Response

type Response struct {
	StatusCode int
	Status     string
	Headers    http.Header
	Cookies    []*http.Cookie
	// contains filtered or unexported fields
}

Response HTTP 响应

func (*Response) Body

func (r *Response) Body() ([]byte, error)

Body 获取响应体(字节数组)

func (*Response) Close

func (r *Response) Close() error

Close 关闭响应体

func (*Response) GetCookie

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

GetCookie 获取 Cookie

func (*Response) GetHeader

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

GetHeader 获取响应头

func (*Response) IsClientError

func (r *Response) IsClientError() bool

IsClientError 判断是否客户端错误(4xx)

func (*Response) IsRedirect

func (r *Response) IsRedirect() bool

IsRedirect 判断是否重定向(3xx)

func (*Response) IsServerError

func (r *Response) IsServerError() bool

IsServerError 判断是否服务器错误(5xx)

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess 判断是否成功(2xx)

func (*Response) JSON

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

JSON 解析 JSON 响应

func (*Response) Request

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

Request 获取原始请求

func (*Response) SaveToFile

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

SaveToFile 保存响应到文件

func (*Response) SaveToFileStream

func (r *Response) SaveToFileStream(filePath string) error

SaveToFileStream 流式保存到文件(适合大文件)

func (*Response) String

func (r *Response) String() (string, error)

String 获取响应体(字符串)

func (*Response) XML

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

XML 解析 XML 响应

type RetryMiddleware

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

RetryMiddleware 重试中间件

func NewRetryMiddleware

func NewRetryMiddleware(maxRetries int, retryDelay time.Duration) *RetryMiddleware

NewRetryMiddleware 创建重试中间件

func (*RetryMiddleware) AfterResponse

func (m *RetryMiddleware) AfterResponse(resp *Response) error

AfterResponse 响应后处理

func (*RetryMiddleware) BeforeRequest

func (m *RetryMiddleware) BeforeRequest(req *http.Request) error

BeforeRequest 请求前处理

type StatusCodeMiddleware

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

StatusCodeMiddleware 状态码检查中间件

func NewStatusCodeMiddleware

func NewStatusCodeMiddleware(allowedCodes []int) *StatusCodeMiddleware

NewStatusCodeMiddleware 创建状态码检查中间件

func (*StatusCodeMiddleware) AfterResponse

func (m *StatusCodeMiddleware) AfterResponse(resp *Response) error

AfterResponse 响应后检查状态码

func (*StatusCodeMiddleware) BeforeRequest

func (m *StatusCodeMiddleware) BeforeRequest(req *http.Request) error

BeforeRequest 请求前处理

type TimeoutMiddleware

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

TimeoutMiddleware 超时中间件

func NewTimeoutMiddleware

func NewTimeoutMiddleware(timeout time.Duration) *TimeoutMiddleware

NewTimeoutMiddleware 创建超时中间件

func (*TimeoutMiddleware) AfterResponse

func (m *TimeoutMiddleware) AfterResponse(resp *Response) error

AfterResponse 响应后处理

func (*TimeoutMiddleware) BeforeRequest

func (m *TimeoutMiddleware) BeforeRequest(req *http.Request) error

BeforeRequest 请求前设置超时

type User

type User struct {
	ID    int    `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
}

User 示例用户结构体

Jump to

Keyboard shortcuts

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