Documentation
¶
Index ¶
- Constants
- func ApplyClientOptions(opts []any, warn func(msg string), onLogger func(debugger.LoggerInterface), ...)
- func CheckRawResponseStatus(statusCode int, body []byte) error
- type APIResponse
- type ErrorParserFunc
- type FlexBool
- type FlexString
- type HTTPClient
- type ReqMakeOpt
- type Request
- type VerifyResponseFunc
Constants ¶
const ( // 基础错误码 ErrCodeSuccess = 0 ErrCodeInvalidCredential = 40001 ErrCodeInvalidGrantType = 40002 ErrCodeInvalidOpenID = 40003 ErrCodeInvalidMediaType = 40004 ErrCodeInvalidFileSize = 40005 ErrCodeInvalidFileFormat = 40006 ErrCodeInvalidParams = 40013 ErrCodeAccessDenied = 48004 ErrCodeAPIQuotaExceeded = 45009 // 基础API域名 BaseAPIURL = "https://api.weixin.qq.com" OpenBaseURL = "https://open.weixin.qq.com" MPBaseURL = "https://mp.weixin.qq.com" PayAPIURL = "https://api.mch.weixin.qq.com" ResURL = "https://res.wx.qq.com" // 授权页面URL MobileAuthPageURL = "https://open.weixin.qq.com/wxaopen/safe/bindcomponent" PCAuthPageURL = "https://mp.weixin.qq.com/cgi-bin/componentloginpage" SubscribeAuthPageURL = "https://mp.weixin.qq.com/mp/subscribemsg" // 通用授权参数 GrantTypeAuthorizationCode = "authorization_code" GrantTypeRefreshToken = "refresh_token" GrantTypeClientCredential = "client_credential" ResponseTypeCode = "code" // OAuth作用域 OAuthScopeBase = "snsapi_base" OAuthScopeUserInfo = "snsapi_userinfo" // 通用操作结果 SuccessResponse = "success" // 事件响应成功 EventResponseSuccess = "success" // 消息类型常量 MessageTypeText = "text" MessageTypeImage = "image" MessageTypeVoice = "voice" MessageTypeVideo = "video" MessageTypeShortVideo = "shortvideo" MessageTypeLocation = "location" MessageTypeLink = "link" MessageTypeEvent = "event" // 事件类型常量 EventTypeComponentVerifyTicket = "component_verify_ticket" EventTypeAuthorized = "authorized" EventTypeUpdateAuthorized = "updateauthorized" // 时间相关常量 EventTimestampTolerance = 300 // 事件时间戳容忍范围(秒) )
API相关公共常量
Variables ¶
This section is empty.
Functions ¶
func ApplyClientOptions ¶ added in v0.1.3
func ApplyClientOptions( opts []any, warn func(msg string), onLogger func(debugger.LoggerInterface), onHTTPClient func(HTTPClient), extraHandlers ...func(option any) (handled bool), )
ApplyClientOptions 遍历各模块构造函数的可选参数并分发。
内置支持两种通用类型:
- debugger.LoggerInterface: 自定义日志器(回调 onLogger)
- HTTPClient: 自定义HTTP客户端(回调 onHTTPClient)
extraHandlers 允许模块注册额外类型的处理逻辑(如 openplatform.EventHandler), 返回 true 表示该参数已被消费,不再进入通用分支。 未被任何分支处理的类型通过 warn 回调记录警告(warn 为 nil 时忽略)。
注意:warn 使用闭包而非 logger 值,以便在 SetLogger 生效后仍能取到当前日志器, 与重构前各模块循环内 client.logger.Warn(...) 的行为保持一致。
参数:
- opts: 可选参数切片
- warn: 未知参数类型的警告回调(接收已格式化的消息),可为 nil
- onLogger: 处理 debugger.LoggerInterface 的回调,可为 nil
- onHTTPClient: 处理 HTTPClient 的回调,可为 nil
- extraHandlers: 模块自定义类型的处理器,可为空
返回值: 无 异常: 不主动panic;回调内部的行为由调用方决定
使用示例:
core.ApplyClientOptions(opts, func(msg string) { client.logger.Warn(msg) },
client.SetLogger, client.SetHTTPClient)
// 带模块扩展类型:
core.ApplyClientOptions(opt, warn, client.SetLogger, client.SetHTTPClient,
func(option any) (handled bool) {
if h, ok := option.(EventHandler); ok {
client.SetEventHandler(h)
return true
}
return false
})
func CheckRawResponseStatus ¶ added in v0.2.0
CheckRawResponseStatus 校验 MakeRaw 返回的响应状态码(MakeRaw 保持返回原始响应的语义,校验由调用方按需调用)。 非 2xx 时返回错误:若响应体可解析出微信 errcode/errmsg 则附带业务错误信息,否则附加响应体前 512 字节原文, 避免把网关/代理层错误(如 500/404 + HTML 页面)当成功响应体处理导致报错信息失真。
参数:
- statusCode: HTTP 状态码
- body: 已读取的响应体
返回:
- error: 非 2xx 时返回错误,2xx 返回 nil
使用示例:
resp, _ := req.MakeRaw(httpReq)
body, _ := io.ReadAll(resp.Body)
if err := core.CheckRawResponseStatus(resp.StatusCode, body); err != nil { ... }
Types ¶
type APIResponse ¶
type APIResponse struct {
ErrCode int `json:"errcode"` // 错误码,0表示成功
ErrMsg string `json:"errmsg"` // 错误描述
}
APIResponse 微信API通用响应结构
type ErrorParserFunc ¶ added in v0.1.0
ErrorParserFunc 非 2xx 响应的错误解析回调类型
说明:
- 返回 nil 表示响应体不是该服务的错误格式,由调用方回退到通用错误
- 微信支付 V3 等接口在 4xx/5xx 时会返回结构化错误 JSON,需解析后供业务判断
type FlexBool ¶ added in v0.2.0
type FlexBool bool
FlexBool 兼容 JSON 布尔/字符串双形态的字段
背景:微信部分接口文档将布尔语义字段标注为 string(如 sendall 的 filter.is_to_all)。使用本类型可同时接受 true/false、"true"/"false"/"0"/"1"。
使用示例:
type Filter struct {
IsToAll FlexBool `json:"is_to_all"`
}
func (FlexBool) MarshalJSON ¶ added in v0.2.0
MarshalJSON 序列化 FlexBool 为 JSON 布尔值
func (*FlexBool) UnmarshalJSON ¶ added in v0.2.0
UnmarshalJSON 反序列化 JSON 值为 FlexBool
参数:
- data: 原始 JSON 字节(布尔或字符串字面量)
异常:
- 值形态不被识别时返回错误
type FlexString ¶ added in v0.2.0
type FlexString string
FlexString 兼容 JSON 字符串/数字双形态的字段
背景:微信部分接口文档与实际返回不一致(如 queryblocktmplmsg 的 id 参数表为 string 而示例为数字;mass/get 的 msg_id 文档标注 string)。使用本类型可同时 接受两种形态,统一以字符串形式存储,避免反序列化失败。
使用示例:
type Resp struct {
ID FlexString `json:"id"`
}
func (FlexString) Int64 ¶ added in v0.2.0
func (s FlexString) Int64() (int64, error)
Int64 将字符串值解析为 int64
返回:
- int64: 解析结果(空串返回 0)
- error: 值不是合法整数时返回错误
func (FlexString) MarshalJSON ¶ added in v0.2.0
func (s FlexString) MarshalJSON() ([]byte, error)
MarshalJSON 序列化 FlexString 为 JSON 字符串
func (*FlexString) UnmarshalJSON ¶ added in v0.2.0
func (s *FlexString) UnmarshalJSON(data []byte) error
UnmarshalJSON 反序列化 JSON 值为 FlexString
参数:
- data: 原始 JSON 字节(字符串或数字字面量)
异常:
- JSON 字符串非法时返回反序列化错误
type HTTPClient ¶
HTTPClient HTTP客户端接口
type ReqMakeOpt ¶
type ReqMakeOpt struct {
Method string // HTTP方法,如GET、POST等
URL string // 请求URL
Query interface{} // 查询参数,支持map[string]string或结构体
Body interface{} // 请求体
Result interface{} // 响应体,需要传入指针
RawResult *[]byte // 原始响应体接收器,非 nil 时跳过 JSON 解析(如下载账单文件)
Headers map[string]string // 自定义请求头,可选
VerifyResponse VerifyResponseFunc // 响应验证回调,可选
ErrorParser ErrorParserFunc // 非 2xx 响应的错误解析回调,可选
}
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
func NewRequest ¶
func NewRequest(httpClient HTTPClient, logger logger.LoggerInterface) *Request
func (*Request) Make ¶
func (r *Request) Make(ctx context.Context, options *ReqMakeOpt) error
Make 发送HTTP请求的通用方法
参数:
- ctx: 请求上下文,用于控制请求超时和取消
- options: 请求配置选项,包含方法、URL、查询参数、请求体和结果接收器
返回:
- error: 请求执行过程中的错误,包含详细的错误信息
功能:
- 支持GET、POST等常用HTTP方法
- 自动处理查询参数拼接,支持map[string]string和结构体
- 支持JSON格式的请求体和响应体
- 自动验证HTTP响应状态码
- 提供详细的日志记录