httpx

package
v0.38.0 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package httpx 提供各引擎共用的 HTTP Client 默认值(超时等)。

Index

Constants

View Source
const DefaultTimeout = 90 * time.Second

DefaultTimeout 为未显式配置 Timeout 时的默认请求超时(含连接+TLS+首包+整体)。

Variables

View Source
var ErrNilHookRequest = errors.New("httpx: request hook returned nil request")

Functions

func AppendHTTPHooks added in v0.37.0

func AppendHTTPHooks(client *http.Client, opts ...HookOption) *http.Client

AppendHTTPHooks returns a shallow clone of client with hooks appended. If the client already uses HookTransport, hooks are appended to the existing transport instead of nesting another HookTransport.

func DoJSON added in v0.9.0

func DoJSON(ctx context.Context, hc *http.Client, method, url, apiKey string, body []byte, prefix string) ([]byte, error)

DoJSON sends a JSON request and returns the response body. It sets Authorization (Bearer) and Content-Type headers automatically. Non-2xx responses are converted to *aigoerr.Error.

func NewRateLimitedClient added in v0.13.0

func NewRateLimitedClient(rps float64, burst int, timeout time.Duration) *http.Client

NewRateLimitedClient creates an *http.Client with a token-bucket rate limiter. rps is requests per second; burst is the maximum burst size.

func NewRetryClient added in v0.13.0

func NewRetryClient(maxRetries int, timeout time.Duration) *http.Client

NewRetryClient creates an *http.Client with automatic retry for 429/5xx.

func OrDefault

func OrDefault(c *http.Client, defaultTimeout time.Duration) *http.Client

OrDefault 返回可用的 *http.Client:nil 或 Timeout==0 时使用 defaultTimeout。 若 c 已有 Timeout>0,原样返回 c。

func UploadFile added in v0.13.0

func UploadFile(ctx context.Context, hc *http.Client, url, apiKey, fieldName, filePath string, extra map[string]string, prefix string) ([]byte, error)

UploadFile uploads a file via multipart/form-data. fieldName is the form field name for the file; extra adds additional string fields.

func UploadReader added in v0.13.0

func UploadReader(ctx context.Context, hc *http.Client, url, apiKey, fieldName, fileName string, r io.Reader, extra map[string]string, prefix string) ([]byte, error)

UploadReader uploads data from an io.Reader via multipart/form-data.

func WithHTTPHooks added in v0.37.0

func WithHTTPHooks(client *http.Client, opts ...HookOption) *http.Client

WithHTTPHooks returns a shallow clone of client whose transport applies the supplied request/response hooks.

func WithResponseCapture added in v0.37.0

func WithResponseCapture(ctx context.Context, c *ResponseCapture) context.Context

WithResponseCapture attaches a response header collector to ctx.

Types

type HookOption added in v0.37.0

type HookOption func(*hookOptions)

HookOption configures request/response hooks for HookTransport.

func WithRequestHooks added in v0.37.0

func WithRequestHooks(hooks ...RequestHook) HookOption

WithRequestHooks appends hooks that run before the underlying transport.

func WithResponseHooks added in v0.37.0

func WithResponseHooks(hooks ...ResponseHook) HookOption

WithResponseHooks appends hooks that run after the underlying transport returns a response.

type HookTransport added in v0.37.0

type HookTransport struct {
	Base          http.RoundTripper
	RequestHooks  []RequestHook
	ResponseHooks []ResponseHook
}

HookTransport applies request and response hooks around an underlying RoundTripper.

func (*HookTransport) RoundTrip added in v0.37.0

func (t *HookTransport) RoundTrip(req *http.Request) (*http.Response, error)

type RateLimitTransport added in v0.13.0

type RateLimitTransport struct {
	Base    http.RoundTripper
	Limiter *rate.Limiter
}

RateLimitTransport wraps an http.RoundTripper with a token-bucket rate limiter.

func (*RateLimitTransport) RoundTrip added in v0.13.0

func (t *RateLimitTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper. It waits for rate limit clearance before forwarding the request to the base transport.

type RequestHook added in v0.37.0

type RequestHook interface {
	BeforeRequest(*http.Request) (*http.Request, error)
}

RequestHook can inspect or replace an outbound HTTP request before it is sent. Implementations must not mutate the input request in place unless they own it; clone the request when changing headers, URL, or body.

type ResponseCapture added in v0.37.0

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

ResponseCapture stores response header records for requests sharing a context.

func NewResponseCapture added in v0.37.0

func NewResponseCapture(opts ...ResponseCaptureOption) *ResponseCapture

NewResponseCapture creates an empty response header collector.

func ResponseCaptureFromContext added in v0.37.0

func ResponseCaptureFromContext(ctx context.Context) *ResponseCapture

ResponseCaptureFromContext returns the collector attached to ctx, if any.

func (*ResponseCapture) Records added in v0.37.0

func (c *ResponseCapture) Records() []ResponseRecord

Records returns a snapshot of captured response records.

type ResponseCaptureHook added in v0.37.0

type ResponseCaptureHook struct{}

ResponseCaptureHook records response headers when the request context has a ResponseCapture attached.

func (ResponseCaptureHook) AfterResponse added in v0.37.0

func (ResponseCaptureHook) AfterResponse(resp *http.Response) error

AfterResponse implements ResponseHook.

type ResponseCaptureOption added in v0.37.0

type ResponseCaptureOption func(*ResponseCapture)

ResponseCaptureOption configures response header capture behavior.

func WithResponseCaptureLimits added in v0.37.0

func WithResponseCaptureLimits(maxRecords, maxValueLen int) ResponseCaptureOption

WithResponseCaptureLimits overrides record count and header value length limits. Non-positive values keep the default limit.

func WithResponseHeaderNames added in v0.37.0

func WithResponseHeaderNames(names ...string) ResponseCaptureOption

WithResponseHeaderNames replaces the exact response header allowlist. Header names are matched case-insensitively.

func WithResponseHeaderPrefixes added in v0.37.0

func WithResponseHeaderPrefixes(prefixes ...string) ResponseCaptureOption

WithResponseHeaderPrefixes replaces the response header prefix allowlist. Prefixes are matched case-insensitively.

type ResponseHook added in v0.37.0

type ResponseHook interface {
	AfterResponse(*http.Response) error
}

ResponseHook can inspect a response returned by the wrapped transport. Returning an error makes the client call fail after the response is received; observer hooks should return nil.

type ResponseRecord added in v0.37.0

type ResponseRecord struct {
	Method     string              `json:"method"`
	URL        string              `json:"url"`
	StatusCode int                 `json:"status_code"`
	Headers    map[string][]string `json:"headers"`
}

ResponseRecord captures response headers observed by a wrapped HTTP client.

type RetryTransport added in v0.13.0

type RetryTransport struct {
	Base       http.RoundTripper
	MaxRetries int           // default: 3
	BaseDelay  time.Duration // default: 1s
	MaxDelay   time.Duration // default: 30s
}

RetryTransport wraps an http.RoundTripper and retries on 429/5xx responses. Only GET requests (and other idempotent methods) are retried by default.

func (*RetryTransport) RoundTrip added in v0.13.0

func (t *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper with automatic retry logic.

Jump to

Keyboard shortcuts

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