HTTP客户端工具
这是一个简单易用的HTTP客户端工具包,支持泛型响应和自动类型转换。
主要特性
- 泛型支持: 所有HTTP方法都支持泛型,可在调用时指定返回类型
- 自动转换: 自动处理JSON解析和类型转换
- 简洁API: 核心方法简单易用
- HttpClient结构体: 支持自定义配置的客户端实例
核心结构
HttpResponse[T] - 泛型响应结构体
type HttpResponse[T any] struct {
StatusCode int // HTTP状态码
Headers map[string]string // 响应头
Body T // 响应体,泛型类型
RawBody string // 原始响应体字符串
Error error // 错误信息
}
HttpClient - HTTP客户端结构体
type HttpClient struct {
config *Config
client *http.Client
}
Config - 配置结构体
type Config struct {
Timeout time.Duration // 超时时间
Auth string // 认证信息
Headers map[string]string // 请求头
}
使用方法
1. 使用默认客户端
// 获取默认客户端
client := http.GetDefaultClient()
// GET请求
resp := client.Get("https://api.example.com/data")
if resp.Error != nil {
log.Fatal(resp.Error)
}
fmt.Println("状态码:", resp.StatusCode)
fmt.Println("响应:", resp.Body)
2. 创建自定义客户端
config := &http.Config{
Timeout: 10 * time.Second,
Auth: "Bearer your-token",
Headers: map[string]string{
"Custom-Header": "value",
},
}
client := http.NewHttpClient(config)
resp := client.Get("https://api.example.com/data")
3. POST请求
// POST表单数据
params := map[string]interface{}{
"name": "张三",
"age": 25,
}
resp := client.Post("https://api.example.com/users", params)
// POST JSON数据
data := map[string]interface{}{
"title": "新文章",
"content": "文章内容",
}
resp := client.PostJSON("https://api.example.com/articles", data)
4. JSON解析
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
var user User
resp := client.GetJSON("https://api.example.com/user/1", &user)
if resp.Error != nil {
log.Fatal(resp.Error)
}
fmt.Printf("用户信息: %+v\n", resp.Body)
4. 使用泛型HTTP方法(默认支持泛型)
// 获取字符串响应
stringResp := http.Get[string]("https://api.example.com/data")
if stringResp.Error != nil {
log.Fatal(stringResp.Error)
}
fmt.Printf("响应: %s\n", stringResp.Body)
// 获取并自动解析为结构体
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
userResp := http.Get[User]("https://api.example.com/user/1")
if userResp.Error != nil {
log.Fatal(userResp.Error)
}
fmt.Printf("用户: %+v\n", userResp.Body) // userResp.Body 是 User 类型
// POST请求并指定返回类型
params := map[string]interface{}{
"name": "张三",
"age": 25,
}
postResp := http.Post[User]("https://api.example.com/users", params)
if postResp.Error != nil {
log.Fatal(postResp.Error)
}
fmt.Printf("新用户: %+v\n", postResp.Body)
// POST JSON并自动解析
data := map[string]interface{}{
"title": "新文章",
"content": "文章内容",
}
jsonResp := http.PostJSON[User]("https://api.example.com/articles", data)
5. 使用自定义配置
// 设置全局配置
http.SetTimeout(30)
http.SetAuth("Bearer token")
http.SetHeader("User-Agent", "MyApp/1.0")
// 使用全局泛型函数
resp := http.Get[string]("https://api.example.com/data")
if resp.Error != nil {
log.Fatal(resp.Error)
}
fmt.Printf("状态码: %d\n", resp.StatusCode)
fmt.Printf("响应: %s\n", resp.Body)
// 使用自定义配置
config := &http.Config{
Timeout: 10 * time.Second,
Auth: "Bearer custom-token",
}
configResp := http.GetWithConfig[User]("https://api.example.com/user/1", config)
// 使用客户端实例
client := http.NewHttpClient(config)
clientResp := http.GetWithClient[User](client, "https://api.example.com/user/1")
支持的HTTP方法
HttpClient方法
Get(url string) *HttpResponse[string]
Post(url string, params map[string]interface{}) *HttpResponse[string]
PostJSON(url string, data interface{}) *HttpResponse[string]
PostText(url, text string) *HttpResponse[string]
Put(url string, params map[string]interface{}) *HttpResponse[string]
PutJSON(url string, data interface{}) *HttpResponse[string]
Delete(url string) *HttpResponse[string]
GetJSON(url string, result interface{}) *HttpResponse[interface{}]
PostJSONAndParse(url string, data, result interface{}) *HttpResponse[interface{}]
泛型HTTP方法(默认支持泛型)
Get[T any](url string) *HttpResponse[T]
Post[T any](url string, params map[string]interface{}) *HttpResponse[T]
PostJSON[T any](url string, data interface{}) *HttpResponse[T]
PostText[T any](url, text string) *HttpResponse[T]
Put[T any](url string, params map[string]interface{}) *HttpResponse[T]
PutJSON[T any](url string, data interface{}) *HttpResponse[T]
Delete[T any](url string) *HttpResponse[T]
带配置的泛型方法
GetWithConfig[T any](url string, config *Config) *HttpResponse[T]
PostWithConfig[T any](url string, params map[string]interface{}, config *Config) *HttpResponse[T]
PostJSONWithConfig[T any](url string, data interface{}, config *Config) *HttpResponse[T]
- 以及其他方法的WithConfig版本
带客户端的泛型方法
GetWithClient[T any](client *HttpClient, url string) *HttpResponse[T]
PostWithClient[T any](client *HttpClient, url string, params map[string]interface{}) *HttpResponse[T]
PostJSONWithClient[T any](client *HttpClient, url string, data interface{}) *HttpResponse[T]
- 以及其他方法的WithClient版本
配置管理
// 全局配置
http.Init(30*time.Second, "Bearer token", map[string]string{
"User-Agent": "MyApp/1.0",
})
// 单独设置
http.SetTimeout(60)
http.SetAuth("Bearer new-token")
http.SetHeader("Custom-Header", "value")
// 重置配置
http.Reset()
工具函数
IsURL(str string) bool - 检查字符串是否为URL
BuildURL(baseURL string, params map[string]interface{}) string - 构建URL
QuickGet(url string) string - 快速GET请求(忽略错误)
QuickPost(url string, params map[string]interface{}) string - 快速POST请求(忽略错误)