http

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2025 License: MIT Imports: 8 Imported by: 0

README

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请求(忽略错误)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Timeout time.Duration     // 超时时间,0表示使用默认值
	Auth    string            // 认证信息,空字符串表示不使用认证
	Headers map[string]string // 请求头,nil表示不设置额外头部
}

Config HTTP客户端配置

type HttpClient added in v0.0.7

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

HttpClient HTTP客户端结构体

func GetDefaultClient added in v0.0.7

func GetDefaultClient() *HttpClient

GetDefaultClient 获取默认客户端实例

func NewDefaultHttpClient added in v0.0.7

func NewDefaultHttpClient() *HttpClient

NewDefaultHttpClient 创建使用默认配置的HTTP客户端

func NewHttpClient added in v0.0.7

func NewHttpClient(config *Config) *HttpClient

NewHttpClient 创建新的HTTP客户端

func (*HttpClient) Delete added in v0.0.7

func (c *HttpClient) Delete(url string) *HttpResponse[string]

Delete 发送DELETE请求

func (*HttpClient) Get added in v0.0.7

func (c *HttpClient) Get(url string) *HttpResponse[string]

Get 发送GET请求

func (*HttpClient) Post added in v0.0.7

func (c *HttpClient) Post(urlStr string, params map[string]interface{}) *HttpResponse[string]

Post 发送POST请求,参数为表单数据

func (*HttpClient) PostJSON added in v0.0.7

func (c *HttpClient) PostJSON(url string, data interface{}) *HttpResponse[string]

PostJSON 发送JSON POST请求

type HttpResponse added in v0.0.7

type HttpResponse[T any] struct {
	StatusCode int               // HTTP状态码
	Headers    map[string]string // 响应头
	Body       T                 // 响应体,泛型类型
	RawBody    string            // 原始响应体字符串
	Error      error             // 错误信息
}

HttpResponse HTTP响应结构体,支持泛型

func Delete

func Delete[T any](url string) *HttpResponse[T]

Delete 发送DELETE请求

func Get

func Get[T any](url string) *HttpResponse[T]

Get 发送GET请求

func Post

func Post[T any](url string, params map[string]interface{}) *HttpResponse[T]

Post 发送POST请求

func PostJSON

func PostJSON[T any](url string, data interface{}) *HttpResponse[T]

PostJSON 发送JSON POST请求

Jump to

Keyboard shortcuts

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