Documentation
¶
Index ¶
- func DefaultRetryable(req *http.Request, resp *http.Response, err error) bool
- func NewDiscoveryTransport(discovery discover.Discovery, serviceName string, opts ...HTTPDiscoveryOption) http.RoundTripper
- func NewHTTPClient(opts ...ClientOption) *http.Client
- type CacheTransport
- type CacheTransportOption
- func WithCacheConditionalRequest() CacheTransportOption
- func WithCacheDefaultTTL(d time.Duration) CacheTransportOption
- func WithCacheFilter(fn func(*http.Request) bool) CacheTransportOption
- func WithCacheForceTTL() CacheTransportOption
- func WithCacheIgnoreRequestDirectives() CacheTransportOption
- func WithCacheKeyFunc(fn func(*http.Request) string) CacheTransportOption
- func WithCacheMethods(methods ...string) CacheTransportOption
- func WithCacheSingleFlight() CacheTransportOption
- type CacheTransportStats
- type CachedResponse
- type Client
- type ClientOption
- func WithBaseTransport(rt http.RoundTripper) ClientOption
- func WithCache(store HTTPCacheStore, opts ...CacheTransportOption) ClientOption
- func WithCircuitBreaker(cb *mwcb.CircuitBreaker) ClientOption
- func WithOtelOption(opts ...otelhttp.Option) ClientOption
- func WithRetry(policy *backoff.Policy) ClientOption
- func WithRetryable(fn RetryableFunc) ClientOption
- func WithTimeout(d time.Duration) ClientOption
- type HTTPBalanceStrategy
- type HTTPCacheStore
- type HTTPDiscoveryOption
- func WithHTTPBaseTransport(rt http.RoundTripper) HTTPDiscoveryOption
- func WithHTTPCircuitBreaker(cb governancecb.CircuitBreaker) HTTPDiscoveryOption
- func WithHTTPLabelFilter(f *selector.LabelFilter) HTTPDiscoveryOption
- func WithHTTPMaxRetries(n int) HTTPDiscoveryOption
- func WithHTTPRetryDelay(d time.Duration) HTTPDiscoveryOption
- func WithHTTPRetryOnDifferentNode(on bool) HTTPDiscoveryOption
- func WithHTTPServiceRouter(r governancerouter.ServiceRouter) HTTPDiscoveryOption
- func WithHTTPStrategy(s HTTPBalanceStrategy) HTTPDiscoveryOption
- func WithHTTPTimeout(d time.Duration) HTTPDiscoveryOption
- type MemoryHTTPCache
- type RetryableFunc
- type ServiceDiscoveryHTTPClient
- func (c *ServiceDiscoveryHTTPClient) Close() error
- func (c *ServiceDiscoveryHTTPClient) Do(req *http.Request) (*http.Response, error)
- func (c *ServiceDiscoveryHTTPClient) DoWith(ctx context.Context, method, path string, body io.Reader) (*http.Response, error)
- func (c *ServiceDiscoveryHTTPClient) GetServiceInfo() []discover.ServiceInfo
- func (c *ServiceDiscoveryHTTPClient) NewRequest(ctx context.Context, method, path string) (*http.Request, error)
- func (c *ServiceDiscoveryHTTPClient) Start(ctx context.Context) error
- func (c *ServiceDiscoveryHTTPClient) Stop()
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DefaultRetryable ¶
DefaultRetryable 是默认重试判定:只重试**幂等**方法(GET/HEAD/OPTIONS/TRACE/PUT/DELETE)——
- 网络/传输错误(err != nil);
- 响应 429 / 502 / 503 / 504。
非幂等方法(POST/PATCH 等)默认不重试(可能已在服务端产生副作用);要重试请自定义 RetryableFunc。
func NewDiscoveryTransport ¶
func NewDiscoveryTransport(discovery discover.Discovery, serviceName string, opts ...HTTPDiscoveryOption) http.RoundTripper
NewDiscoveryTransport 创建服务发现 RoundTripper。 未设 WithHTTPBaseTransport 时用 otelhttp 包装的 http.DefaultTransport。 返回的 RoundTripper 可直接塞进 http.Client.Transport,或用 NewServiceDiscoveryHTTPClient 包装。
func NewHTTPClient ¶
func NewHTTPClient(opts ...ClientOption) *http.Client
NewHTTPClient 返回一个带 OTel trace 传播的标准 *http.Client。 默认超时 30s,防止下游无响应时 goroutine 永久挂起。
用法:
client := resty.NewHTTPClient() req, _ := http.NewRequestWithContext(ctx, "GET", url, nil) resp, err := client.Do(req) // 自定义超时 client := resty.NewHTTPClient(resty.WithTimeout(10 * time.Second))
Types ¶
type CacheTransport ¶ added in v0.3.0
type CacheTransport struct {
// contains filtered or unexported fields
}
CacheTransport is an http.RoundTripper that caches responses.
Only safe (GET by default) requests with cacheable responses are stored. The transport respects standard Cache-Control directives (no-store, no-cache, max-age, private) unless WithCacheForceTTL is set.
func NewCacheTransport ¶ added in v0.3.0
func NewCacheTransport(next http.RoundTripper, store HTTPCacheStore, opts ...CacheTransportOption) *CacheTransport
NewCacheTransport wraps next with an HTTP response cache. If next is nil, http.DefaultTransport is used.
func (*CacheTransport) Stats ¶ added in v0.3.0
func (t *CacheTransport) Stats() CacheTransportStats
Stats returns cache hit/miss counters (atomic reads).
type CacheTransportOption ¶ added in v0.3.0
type CacheTransportOption func(*cacheTransportCfg)
CacheTransportOption configures NewCacheTransport.
func WithCacheConditionalRequest ¶ added in v0.3.0
func WithCacheConditionalRequest() CacheTransportOption
WithCacheConditionalRequest enables conditional revalidation: when a cached entry expires the transport sends If-None-Match / If-Modified-Since and handles 304 Not Modified by refreshing the cache.
func WithCacheDefaultTTL ¶ added in v0.3.0
func WithCacheDefaultTTL(d time.Duration) CacheTransportOption
WithCacheDefaultTTL sets the fallback TTL used when the response carries no Cache-Control max-age directive (default 1 min).
func WithCacheFilter ¶ added in v0.3.0
func WithCacheFilter(fn func(*http.Request) bool) CacheTransportOption
WithCacheFilter adds a custom predicate checked after the method filter. Return true = eligible for caching; false = bypass cache entirely.
func WithCacheForceTTL ¶ added in v0.3.0
func WithCacheForceTTL() CacheTransportOption
WithCacheForceTTL ignores both request-side and response-side Cache-Control directives, always using the configured default TTL. Useful for APIs that don't set cache headers or when you want full control over TTL.
func WithCacheIgnoreRequestDirectives ¶ added in v0.3.0
func WithCacheIgnoreRequestDirectives() CacheTransportOption
WithCacheIgnoreRequestDirectives ignores request-side Cache-Control (no-store, no-cache) while still respecting the server's response directives. Useful when upstream callers set no-cache/no-store but you still want transport-level caching controlled by the server's max-age / Expires.
func WithCacheKeyFunc ¶ added in v0.3.0
func WithCacheKeyFunc(fn func(*http.Request) string) CacheTransportOption
WithCacheKeyFunc overrides the default cache key generation (method + URL).
func WithCacheMethods ¶ added in v0.3.0
func WithCacheMethods(methods ...string) CacheTransportOption
WithCacheMethods specifies which HTTP methods are cacheable (default: GET).
func WithCacheSingleFlight ¶ added in v0.3.0
func WithCacheSingleFlight() CacheTransportOption
WithCacheSingleFlight deduplicates concurrent cache-miss fetches for the same key so all concurrent callers share the result of a single round-trip.
type CacheTransportStats ¶ added in v0.3.0
CacheTransportStats holds hit/miss counters.
type CachedResponse ¶ added in v0.3.0
CachedResponse is a serializable snapshot of an HTTP response.
type ClientOption ¶
type ClientOption func(*clientConfig)
ClientOption 配置 NewHTTPClient 的选项。
func WithBaseTransport ¶ added in v0.3.7
func WithBaseTransport(rt http.RoundTripper) ClientOption
WithBaseTransport 设置最内层 RoundTripper(默认 http.DefaultTransport)。 适合注入自定义 TLS / mTLS(如 SPIFFE SVID)或自定义连接池;外层仍会包 otel/重试/熔断/缓存。
func WithCache ¶ added in v0.3.0
func WithCache(store HTTPCacheStore, opts ...CacheTransportOption) ClientOption
WithCache 开启 HTTP 响应缓存。缓存在传输链最外层:命中时跳过熔断/重试/OTel, 零网络开销;未命中走完整链路后存入缓存。默认仅缓存 GET、遵守 Cache-Control。
func WithCircuitBreaker ¶
func WithCircuitBreaker(cb *mwcb.CircuitBreaker) ClientOption
WithCircuitBreaker 接入请求级熔断(pkg/middleware/circuitbreaker):熔断打开时直接短路, 保护下游、快速失败。用 circuitbreaker.NewCircuitBreaker / GetCircuitBreaker 构造。
func WithOtelOption ¶
func WithOtelOption(opts ...otelhttp.Option) ClientOption
WithOtelOption 透传 otelhttp 选项(如自定义 span name、filter 等)。
func WithRetry ¶
func WithRetry(policy *backoff.Policy) ClientOption
WithRetry 开启请求重试:按 backoff.Policy 退避,默认只重试幂等方法的瞬时失败 (网络错误 / 429 / 502 / 503 / 504),遵守 Retry-After,请求体自动重放。 用 backoff.New(backoff.WithMaxRetries(n), ...) 构造 policy。
func WithRetryable ¶
func WithRetryable(fn RetryableFunc) ClientOption
WithRetryable 自定义重试判定(覆盖 DefaultRetryable),需配合 WithRetry。 例如让某个已知幂等的 POST 也参与重试。
func WithTimeout ¶
func WithTimeout(d time.Duration) ClientOption
WithTimeout 覆盖默认超时时间(默认 30s)。传 0 表示不设超时。
type HTTPBalanceStrategy ¶
type HTTPBalanceStrategy int
HTTPBalanceStrategy HTTP 负载均衡策略。不含 LeastConnections—— HTTP 客户端不维护连接池状态,无法查 in-flight/连接状态。
const ( HTTPRoundRobin HTTPBalanceStrategy = iota HTTPRandom HTTPWeightedRoundRobin )
type HTTPCacheStore ¶ added in v0.3.0
type HTTPCacheStore interface {
Get(key string) (*CachedResponse, bool)
Set(key string, resp *CachedResponse, ttl time.Duration)
Delete(key string)
}
HTTPCacheStore persists cached HTTP responses. Implementations must be safe for concurrent use.
type HTTPDiscoveryOption ¶
type HTTPDiscoveryOption func(*discoveryConfig)
HTTPDiscoveryOption 服务发现配置选项。同时作用于 transport 与 client 包装层 (二者共享 discoveryConfig),故 Option 接收 *discoveryConfig。 WithHTTPTimeout 是例外——它配置 http.Client 超时,只在 client 层生效。
func WithHTTPBaseTransport ¶ added in v0.3.7
func WithHTTPBaseTransport(rt http.RoundTripper) HTTPDiscoveryOption
WithHTTPBaseTransport 设置发现客户端最内层 RoundTripper(默认 http.DefaultTransport)。 外层仍包 otel;适合注入自定义 TLS / mTLS(如 SPIFFE SVID)。
func WithHTTPCircuitBreaker ¶
func WithHTTPCircuitBreaker(cb governancecb.CircuitBreaker) HTTPDiscoveryOption
WithHTTPCircuitBreaker 设置节点级熔断器。transport 选实例前过 Available 检查, 跳过已熔断节点;请求结束自动 Report 结果。默认 NoopBreaker(不熔断)。
func WithHTTPLabelFilter ¶
func WithHTTPLabelFilter(f *selector.LabelFilter) HTTPDiscoveryOption
WithHTTPLabelFilter 设置标签过滤器(地域/版本/zone 等),直接复用 selector.LabelFilter。
func WithHTTPMaxRetries ¶
func WithHTTPMaxRetries(n int) HTTPDiscoveryOption
WithHTTPMaxRetries 设置额外重试次数(0=不重试,总尝试=maxRetries+1)。
func WithHTTPRetryDelay ¶
func WithHTTPRetryDelay(d time.Duration) HTTPDiscoveryOption
WithHTTPRetryDelay 设置指数退避 base(默认 1s,实际等待 base*2^i ± 25% jitter)。
func WithHTTPRetryOnDifferentNode ¶
func WithHTTPRetryOnDifferentNode(on bool) HTTPDiscoveryOption
WithHTTPRetryOnDifferentNode 设置重试时是否换节点(默认 true)。 true:每次重试重新选实例,处理节点彻底不可用(对齐 gRPC failover); false:重试复用同一 URL,仅对网络抖动有效。
func WithHTTPServiceRouter ¶
func WithHTTPServiceRouter(r governancerouter.ServiceRouter) HTTPDiscoveryOption
WithHTTPServiceRouter 设置路由过滤层。transport 选实例前过 router.Filter, 用于灰度/地域亲和等。默认 NoopRouter(不过滤)。
func WithHTTPStrategy ¶
func WithHTTPStrategy(s HTTPBalanceStrategy) HTTPDiscoveryOption
WithHTTPStrategy 设置负载均衡策略(默认 HTTPRoundRobin)。
func WithHTTPTimeout ¶
func WithHTTPTimeout(d time.Duration) HTTPDiscoveryOption
WithHTTPTimeout 覆盖底层 http.Client 超时(默认 30s)。传 0 表示不设超时。 仅在 ServiceDiscoveryHTTPClient 上生效(配置 *http.Client.Timeout)。
type MemoryHTTPCache ¶ added in v0.3.0
type MemoryHTTPCache struct {
// contains filtered or unexported fields
}
MemoryHTTPCache is a bounded in-memory HTTPCacheStore. It evicts the earliest-expiring entry when full, and lazily removes expired entries on access. Suitable for development, testing, and single-instance deployments; production can implement HTTPCacheStore backed by Redis / Memcached.
func NewMemoryHTTPCache ¶ added in v0.3.0
func NewMemoryHTTPCache(maxSize int) *MemoryHTTPCache
NewMemoryHTTPCache creates a memory cache. maxSize <= 0 defaults to 256.
func (*MemoryHTTPCache) Delete ¶ added in v0.3.0
func (m *MemoryHTTPCache) Delete(key string)
func (*MemoryHTTPCache) Get ¶ added in v0.3.0
func (m *MemoryHTTPCache) Get(key string) (*CachedResponse, bool)
func (*MemoryHTTPCache) Len ¶ added in v0.3.0
func (m *MemoryHTTPCache) Len() int
Len returns the current number of entries.
func (*MemoryHTTPCache) Set ¶ added in v0.3.0
func (m *MemoryHTTPCache) Set(key string, resp *CachedResponse, ttl time.Duration)
type RetryableFunc ¶
RetryableFunc 判断一次结果是否值得重试。resp 在网络错误时为 nil。
type ServiceDiscoveryHTTPClient ¶
type ServiceDiscoveryHTTPClient struct {
// contains filtered or unexported fields
}
ServiceDiscoveryHTTPClient 基于服务发现的 HTTP 客户端。是 discoveryTransport(RoundTripper) 的薄包装:持有 *http.Client(Transport=discoveryTransport),提供便捷的 Do/DoWith/NewRequest。
调用方也可只用 NewDiscoveryTransport 拿到 RoundTripper,塞进自己的 http.Client, 跳过本包装层——适用于已有 http.Client 管理逻辑的场景。
生命周期:New → Start(ctx)(启动 watch)→ Do/NewRequest → Stop/Close。 未调用 Start 时首次 Do 会 autoStart(仅 refresh 一次,不启动 watch,并打印警告)。
func NewServiceDiscoveryHTTPClient ¶
func NewServiceDiscoveryHTTPClient(discovery discover.Discovery, serviceName string, opts ...HTTPDiscoveryOption) *ServiceDiscoveryHTTPClient
NewServiceDiscoveryHTTPClient 创建基于服务发现的 HTTP 客户端。 内部构造 discoveryTransport 作为 RoundTripper,包成 *http.Client。
func (*ServiceDiscoveryHTTPClient) Close ¶
func (c *ServiceDiscoveryHTTPClient) Close() error
Close 停止后台 goroutine。HTTP 客户端无长连接池需关闭,等价于 Stop。
func (*ServiceDiscoveryHTTPClient) Do ¶
Do 发送已构造好的 *http.Request(通常由 NewRequest 创建,也可外部构造)。 transport 会改写 URL.Host 为选中的实例地址,并按配置重试。 调用方负责关闭返回的 resp.Body。
func (*ServiceDiscoveryHTTPClient) DoWith ¶
func (c *ServiceDiscoveryHTTPClient) DoWith(ctx context.Context, method, path string, body io.Reader) (*http.Response, error)
DoWith 便捷形式:选实例 + 拼 URL + 发送,一步到位。 method 为 HTTP 方法,path 为相对路径(如 "/api/users"),body 为可选 io.Reader。
func (*ServiceDiscoveryHTTPClient) GetServiceInfo ¶
func (c *ServiceDiscoveryHTTPClient) GetServiceInfo() []discover.ServiceInfo
GetServiceInfo 获取当前缓存的服务列表。
func (*ServiceDiscoveryHTTPClient) NewRequest ¶
func (c *ServiceDiscoveryHTTPClient) NewRequest(ctx context.Context, method, path string) (*http.Request, error)
NewRequest 选实例并拼好 URL,返回 *http.Request。调用方自行设置 body/header 后用 Do 发送。 method 为 HTTP 方法,path 为相对路径(如 "/api/users")。
func (*ServiceDiscoveryHTTPClient) Start ¶
func (c *ServiceDiscoveryHTTPClient) Start(ctx context.Context) error
Start 启动客户端:拉取初始服务列表并启动 watch。幂等。 调用 Stop 或取消传入 ctx 均可停止后台 goroutine。
func (*ServiceDiscoveryHTTPClient) Stop ¶
func (c *ServiceDiscoveryHTTPClient) Stop()
Stop 停止后台 goroutine 并等待退出。幂等。