httptool

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2025 License: MIT Imports: 15 Imported by: 0

README

httptool

httptool 是一个简单易用的 HTTP 客户端工具包,提供了丰富的功能和灵活的配置选项。该工具包基于 Go 标准库的 net/http 包构建,并添加了更多实用的功能。

特性

  • 支持常用的 HTTP 方法(GET、POST、PUT、DELETE 等)
  • 灵活的配置选项系统
  • 内置的日志记录功能
  • 慢请求监控
  • 自定义 HTTP 客户端支持
  • 上下文(Context)支持
  • 超时控制
  • 请求头管理

安装

go get github.com/yourusername/httptool

快速开始

基本 GET 请求
import "github.com/yourusername/httptool"

func main() {
    ctx := context.Background()
    statusCode, body, err := httptool.Get(ctx, "https://api.example.com/data")
    if err != nil {
        // 处理错误
        return
    }
    // 处理响应
}
带选项的 POST 请求
data := []byte(`{
    "name": "张三",
    "age": 25
}`)
options := []httptool.Option{
    httptool.WithTimeout(10 * time.Second),
    httptool.WithHeaders(map[string]string{
        "Authorization": "Bearer token123",
    }),
    httptool.WithSlowThreshold(100 * time.Millisecond),
}
statusCode, body, err := httptool.Post(ctx, "https://api.example.com/users", data, options...)

配置选项

httptool 提供了多种配置选项,可以根据需要组合使用:

WithTimeout

设置请求超时时间:

httptool.WithTimeout(10 * time.Second)
WithHeaders

设置请求头:

httptool.WithHeaders(map[string]string{
    "Authorization": "Bearer token123",
    "Content-Type": "application/json",
})
WithSlowThreshold

设置慢请求阈值:

httptool.WithSlowThreshold(100 * time.Millisecond)
WithLogger

设置自定义日志记录器:

customLogger := httptool.New(log.New(os.Stdout, "", log.LstdFlags), httptool.Config{
    LogLevel: httptool.Debug,
    Colorful: true,
})
httptool.WithLogger(customLogger)
WithContext

设置请求上下文:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
httptool.WithContext(ctx)

自定义 HTTP 客户端

可以创建自定义的 HTTP 客户端并设置为全局客户端:

customClient := &http.Client{
    Timeout: 30 * time.Second,
    Transport: &http.Transport{
        MaxIdleConns:        100,
        MaxIdleConnsPerHost: 50,
        IdleConnTimeout:     90 * time.Second,
    },
}
httptool.SetHttpClient(customClient)

日志功能

httptool 提供了内置的日志记录功能,支持不同的日志级别和彩色输出:

logger := httptool.New(log.New(os.Stdout, "", log.LstdFlags), httptool.Config{
    LogLevel: httptool.Debug,
    Colorful: true,
})

支持的日志级别:

  • Debug
  • Info
  • Warn
  • Error

错误处理

httptool 会返回以下信息:

  • statusCode: HTTP 状态码
  • body: 响应体
  • err: 错误信息

建议总是检查错误:

statusCode, body, err := httptool.Get(ctx, url)
if err != nil {
    // 处理错误
    return
}

最佳实践

  1. 总是使用上下文来控制请求的生命周期
  2. 设置适当的超时时间
  3. 使用慢请求阈值监控性能
  4. 在生产环境中使用自定义日志记录器
  5. 根据需要配置自定义 HTTP 客户端

示例

更多使用示例请参考 example_test.go

贡献

欢迎提交 Issue 和 Pull Request!

许可证

MIT License

Documentation

Index

Examples

Constants

View Source
const (
	Reset    = "\033[0m"
	Red      = "\033[31m"
	Green    = "\033[32m"
	Yellow   = "\033[33m"
	Magenta  = "\033[35m"
	BlueBold = "\033[34;1m"
)

Colors

Variables

View Source
var (
	// Default logger
	Default = New(log.New(os.Stdout, "\r\n", log.LstdFlags), Config{
		LogLevel: Warn,
		Colorful: true,
	})
)

Functions

func Get

func Get(ctx context.Context, url string, options ...Option) (httpStatusCode int, respBody []byte, err error)

Get 发起GET请求

Example

ExampleGet 展示GET请求的使用方法

// 创建上下文
ctx := context.Background()

// 基本GET请求
statusCode, body, err := Get(ctx, "https://api.example.com/data")
if err != nil {
	// 处理错误
	return
}
_ = statusCode
_ = body

// 带自定义选项的GET请求
options := []Option{
	WithTimeout(10 * time.Second), // 设置超时
	WithHeaders(map[string]string{ // 设置请求头
		"Authorization":   "Bearer token123",
		"X-Custom-Header": "value",
	}),
	WithSlowThreshold(100 * time.Millisecond), // 设置慢请求阈值
}
statusCode, body, err = Get(ctx, "https://api.example.com/data", options...)

func GetHttpClient

func GetHttpClient() *http.Client

GetHttpClient 获取全局HTTP客户端

func Post

func Post(ctx context.Context, url string, data []byte, options ...Option) (httpStatusCode int, respBody []byte, err error)

Post 发起POST请求

Example

ExamplePost 展示POST请求的使用方法

ctx := context.Background()

// 准备POST数据
data := []byte(`{
		"name": "张三",
		"age": 25,
		"email": "zhangsan@example.com"
	}`)

// 基本POST请求
statusCode, body, err := Post(ctx, "https://api.example.com/users", data)
if err != nil {
	// 处理错误
	return
}
_ = statusCode
_ = body

// 带自定义选项的POST请求
options := []Option{
	WithTimeout(10 * time.Second),
	WithHeaders(map[string]string{
		"Authorization": "Bearer token123",
	}),
	WithSlowThreshold(100 * time.Millisecond),
}
statusCode, body, err = Post(ctx, "https://api.example.com/users", data, options...)

func Request

func Request(method string, url string, options ...Option) (httpStatusCode int, respBody []byte, err error)
Example

ExampleRequest 展示通用Request方法的使用

ctx := context.Background()

// PUT请求示例
putData := []byte(`{
		"name": "李四",
		"age": 30
	}`)
options := []Option{
	WithContext(ctx),
	WithData(putData),
	WithHeaders(map[string]string{
		"Authorization": "Bearer token123",
	}),
	WithTimeout(10 * time.Second),
}
statusCode, body, err := Request("PUT", "https://api.example.com/users/1", options...)
if err != nil {
	// 处理错误
	return
}
_ = statusCode
_ = body

// DELETE请求示例
statusCode, body, err = Request("DELETE", "https://api.example.com/users/1", WithContext(ctx))

func SetHttpClient

func SetHttpClient(c *http.Client)

SetHttpClient 提供传入自定义HttpClient方法

Types

type Config

type Config struct {
	Colorful bool
	LogLevel LogLevel
}

Config logger config

type Interface

type Interface interface {
	LogMode(LogLevel) Interface
	Debug(context.Context, string, ...interface{})
	Info(context.Context, string, ...interface{})
	Warn(context.Context, string, ...interface{})
	Error(context.Context, string, ...interface{})
}

Interface logger interface

func New

func New(writer Writer, config Config) Interface

New initialize logger

type LogLevel

type LogLevel int

LogLevel log level

const (
	// Silent silent log level
	Silent LogLevel = iota + 1
	// Error error log level
	Error
	// Warn warn log level
	Warn
	// Info info log level
	Info
	// Debug debug log level
	Debug
)

type Option

type Option interface {
	// contains filtered or unexported methods
}

func WithContext

func WithContext(ctx context.Context) Option
Example

ExampleWithContext 展示使用带超时的上下文

// 创建带超时的上下文
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

// 使用带超时的上下文发送请求
statusCode, body, err := Get(ctx, "https://api.example.com/data")
if err != nil {
	// 处理错误
	return
}
_ = statusCode
_ = body

func WithData

func WithData(data []byte) Option

func WithHeaders

func WithHeaders(headers map[string]string) Option

func WithLogger

func WithLogger(l Interface) Option
Example

ExampleWithLogger 展示自定义日志记录器的使用

ctx := context.Background()

// 创建自定义日志记录器
customLogger := New(log.New(os.Stdout, "", log.LstdFlags), Config{
	LogLevel: Debug,
	Colorful: true,
})

// 使用自定义日志记录器发送请求
options := []Option{
	WithContext(ctx),
	WithLogger(customLogger),
	WithSlowThreshold(100 * time.Millisecond),
}
statusCode, body, err := Get(ctx, "https://api.example.com/data", options...)
if err != nil {
	// 处理错误
	return
}
_ = statusCode
_ = body

func WithSlowThreshold

func WithSlowThreshold(threshold time.Duration) Option

WithSlowThreshold 设置慢请求阈值 单位:毫秒

Example

ExampleWithSlowThreshold 展示慢请求监控

ctx := context.Background()

// 设置慢请求阈值为100毫秒
options := []Option{
	WithContext(ctx),
	WithSlowThreshold(100 * time.Millisecond),
}

// 发送请求,如果响应时间超过阈值,会记录警告日志
statusCode, body, err := Get(ctx, "https://api.example.com/data", options...)
if err != nil {
	// 处理错误
	return
}
_ = statusCode
_ = body

func WithTimeout

func WithTimeout(timeout time.Duration) Option

type Writer

type Writer interface {
	Printf(string, ...interface{})
}

Writer log writer interface

Jump to

Keyboard shortcuts

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