httpx

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2026 License: MIT Imports: 14 Imported by: 0

README

httpx

httpx 是基于 net/http 的增强型 HTTP 客户端封装,专为微服务环境设计。

✨ 特性

  • 自动追踪:集成 OpenTelemetry,自动注入 Trace Context。
  • 指标监控:集成 Prometheus,自动记录请求耗时、状态码分布。
  • 连接池优化:预设生产级连接池参数(MaxIdleConns, IdleConnTimeout 等)。
  • 结构化日志:记录请求/响应的关键信息。
  • 易用 API:提供 Fluent API 风格的请求构建。

🚀 快速开始

1. 初始化客户端
import "github.com/bang-go/micro/transport/httpx"

// 使用默认配置
client := httpx.New(nil)

// 或者自定义配置
client := httpx.New(&httpx.Config{
    Timeout:      5 * time.Second,
    Trace:        true, // 开启链路追踪
    EnableLogger: true, // 开启访问日志
})
2. 发起请求
ctx := context.Background()

req := &httpx.Request{
    Method:      httpx.MethodPost,
    Url:         "https://api.example.com/users",
    ContentType: httpx.ContentJson,
    Body:        httpx.FormatJsonData(map[string]string{"name": "Alice"}),
}

resp, err := client.Send(ctx, req)
if err != nil {
    // handle error
}

fmt.Printf("Status: %d, Body: %s", resp.StatusCode, string(resp.Content))

⚙️ 配置说明

type Config struct {
    Timeout      time.Duration // 请求超时时间
    Trace        bool          // 是否开启 OpenTelemetry 追踪
    Logger       *logger.Logger // 自定义 Logger
    EnableLogger bool          // 是否开启日志记录
    
    // 连接池配置
    MaxIdleConns        int
    MaxIdleConnsPerHost int
    MaxConnsPerHost     int
    IdleConnTimeout     time.Duration
}

Documentation

Index

Constants

View Source
const (
	ContentRaw  = "Raw"  //原始请求
	ContentForm = "Form" //Form请求
	ContentJson = "Json" //Json请求
)
View Source
const (
	MethodGet     = http.MethodGet
	MethodHead    = http.MethodHead
	MethodPost    = http.MethodPost
	MethodPut     = http.MethodPut
	MethodPatch   = http.MethodPatch // RFC 5789
	MethodDelete  = http.MethodDelete
	MethodConnect = http.MethodConnect
	MethodOptions = http.MethodOptions
	MethodTrace   = http.MethodTrace
)

Variables

View Source
var (
	ClientRequestDuration = prometheus.NewHistogramVec(
		prometheus.HistogramOpts{
			Name:    "httpx_client_request_duration_seconds",
			Help:    "HTTP client request duration in seconds",
			Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10},
		},
		[]string{"method", "code", "host"},
	)

	ClientRequestsTotal = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "httpx_client_requests_total",
			Help: "HTTP client requests total",
		},
		[]string{"method", "code", "host"},
	)
)

Prometheus Metrics

Functions

func FormatFormData

func FormatFormData(data map[string]string) string

FormatFormData 格式化form数据

func FormatJsonData

func FormatJsonData(data interface{}) string

FormatJsonData 格式化json数据,支持任意类型

func WithBasicAuth

func WithBasicAuth(auth *RequestBasicAuth) opt.Option[requestOptions]

Types

type Client

type Client interface {
	Send(ctx context.Context, req *Request, opts ...opt.Option[requestOptions]) (resp *Response, err error)
}

func New

func New(conf *Config) Client

type Config

type Config struct {
	// Common settings
	Trace        bool
	Logger       *logger.Logger
	EnableLogger bool

	// Client specific settings
	Timeout             time.Duration
	MaxIdleConns        int
	MaxIdleConnsPerHost int
	MaxConnsPerHost     int
	IdleConnTimeout     time.Duration
	Transport           *http.Transport

	// ObservabilitySkipPaths 跳过可观测性记录(Metrics & Trace)的路径列表
	// 客户端无默认值,完全由用户配置。
	ObservabilitySkipPaths []string

	// Server specific settings
	Addr         string
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
	IdleTimeout  time.Duration
}

Config defines the configuration for both Client and Server

type Request

type Request struct {
	Url         string            `json:"url"`          // 请求url
	Method      string            `json:"method"`       //请求方法,GET/POST/PUT/DELETE/PATCH...
	Params      map[string]string `json:"params"`       //Query参数
	Body        string            `json:"body"`         //请求体
	Headers     map[string]string `json:"headers"`      // 请求头
	ContentType string            `json:"content_type"` //数据编码格式 //TODO:更多
	Files       map[string]string `json:"files"`        //TODO:文件
	Cookies     map[string]string `json:"cookies"`      //Cookies

}

Request 请求结构体

type RequestBasicAuth

type RequestBasicAuth struct {
	Username string `json:"username"` //base认证username
	Password string `json:"password"` //base认证password
}

type Response

type Response struct {
	StatusCode int               `json:"status_code"` // 状态码
	Success    bool              `json:"success"`     // 响应状态
	Content    []byte            `json:"content"`     // 响应内容-字节
	Reason     string            `json:"reason"`      // 状态码说明
	Elapsed    float64           `json:"elapsed"`     // 请求耗时(秒)
	Headers    map[string]string `json:"headers"`     // 响应头
	Cookies    map[string]string `json:"cookies"`     // 响应Cookies
	Request    *Request          `json:"request"`     // 原始请求
}

Response 响应结构体

type Server added in v1.0.7

type Server interface {
	Start(http.Handler) error
	Shutdown(context.Context) error
	Server() *http.Server
}

func NewServer added in v1.0.7

func NewServer(conf *Config) Server

Jump to

Keyboard shortcuts

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