thirdparty

package
v1.51.0 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package thirdparty 提供对接第三方系统的出站 HTTP 客户端框架。 脚手架负责签名、超时、重试与错误码映射,业务只关心请求与响应。

Index

Constants

View Source
const DefaultTimeout = 10 * time.Second

DefaultTimeout 默认总超时。

Variables

This section is empty.

Functions

func IsTimeout

func IsTimeout(err error) bool

IsTimeout 判断错误是否为第三方超时(可用于业务重试决策)。

Types

type Client

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

Client 第三方 HTTP 客户端。 使用前必须 NewClient 构造;所有方法并发安全。

func NewClient

func NewClient(cfg Config) *Client

NewClient 构造第三方客户端。

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, path string, query map[string]string, body, out interface{}) error

Do 发起任意方法请求;query 为查询参数,body 为 JSON 负载(可为 nil)。

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string, query map[string]string, out interface{}) error

Get 发起 GET 请求,响应 JSON 解码到 out。 query 为查询参数(可为 nil);out 为 nil 时只校验状态码。

func (*Client) Post

func (c *Client) Post(ctx context.Context, path string, body, out interface{}) error

Post 发起 POST 请求,body 序列化为 JSON,响应解码到 out。

type Config

type Config struct {
	// BaseURL 第三方服务根地址(如 https://sms.partner.com)。
	BaseURL string
	// Signer 签名器(NewHMACSigner / NewRSASignerFromPEM / NewBearerSigner)。
	Signer Signer
	// Timeout 单次请求总超时;非正数时使用 DefaultTimeout。
	Timeout time.Duration
	// MaxRetries 失败重试次数(默认 2;网络错误与 5xx 重试,4xx 不重试)。
	MaxRetries int
	// RetryBaseDelay 重试基础退避(默认 200ms,指数增长 + 抖动)。
	RetryBaseDelay time.Duration
	// ExtraHeaders 附加固定请求头(如 Accept-Language)。
	ExtraHeaders map[string]string
	// NonceFunc 自定义 nonce 生成;nil 时使用 crypto/rand 随机 hex。
	NonceFunc func() (string, error)
	// Breaker 熔断器(circuit.New 创建);nil 时不启用。下游连续失败(网络错误/5xx)
	// 达到阈值后快速失败(错误码 B0200 系统容灾被触发),防止故障雪崩。
	Breaker *circuit.Breaker
}

Config 第三方客户端配置。

type Signer

type Signer interface {
	// Sign 计算签名;method/path 为请求方法与路径(不含 query),
	// timestamp 为 Unix 秒字符串,nonce 为随机串,bodySHA256 为请求体 SHA256 hex。
	Sign(method, path, timestamp, nonce, bodySHA256 string) (string, error)
	// HeaderName 返回签名写入的请求头名称。
	HeaderName() string
	// HeaderValue 返回签名头附带的值(如 AppKey 或 Bearer token)。
	HeaderValue() string
}

Signer 定义请求签名器。 签名串规范(与入站 openapi 网关对齐):

StringToSign = METHOD + "\n" + Path + "\n" + Timestamp + "\n" + Nonce + "\n" + BodySHA256

业务无需直接使用 Signer,Client 内部自动完成签名。

func NewBearerSigner

func NewBearerSigner(token string) Signer

NewBearerSigner 创建 Bearer token 签名器(仅写 Authorization 头,不计算签名)。

func NewHMACSigner

func NewHMACSigner(appKey, appSecret string) Signer

NewHMACSigner 创建 HMAC-SHA256 签名器。

func NewRSASignerFromPEM

func NewRSASignerFromPEM(appKey string, privateKeyPEM []byte) (Signer, error)

NewRSASignerFromPEM 从 PEM 私钥创建 RSA 签名器。

Jump to

Keyboard shortcuts

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