Skip to content

fix(openapi): fix auth scheme loss in OnBeforeRequest hook#59

Open
fan4w wants to merge 1 commit intotencent-connect:masterfrom
fan4w:master
Open

fix(openapi): fix auth scheme loss in OnBeforeRequest hook#59
fan4w wants to merge 1 commit intotencent-connect:masterfrom
fan4w:master

Conversation

@fan4w
Copy link

@fan4w fan4w commented Mar 11, 2026

bug 现象

当项目将底层间接依赖 github.com/go-resty/resty/v2 升级至较高版本(如 v2.17.2)时,机器人发起的首次 API 请求会稳定复现 500 错误(报错体:{"message": "fetch robot info failed", "code": 340067})。而之后的请求正常。

通过日志发现,首次请求的请求头中,认证体为:Authorization: Bearer,而能正常发送的认证体为:Authorization: QQBot。高版本 go-resty 在首次请求时,默认回退使用了 Bearer 作为 Authorization Scheme。

原因

问题出在 openapi/v1/openapi.gosetupClient 函数中的 OnBeforeRequest 钩子设计上:

  1. 在现有的逻辑中,Hook 试图通过 c.SetAuthScheme(tk.TokenType) 来挂载鉴权。但在高版本的 go-resty 中,行为有所不同,此时修改全局的 Client (c),不会影响当前正在发出的这个 RequestTokenType,导致当前请求鉴权失败。
  2. 现有的写法在 Hook 中动态修改了全局单例的 c *resty.Client。可能存在多个并发请求同时修改全局 Client 的属性,存在数据竞争隐患。

- 修复升级 go-resty v2.17+ 后,首次请求鉴权前缀丢失退化为 Bearer 导致 500 的问题
- 且修复高并发场景下,多个协程同时在 Hook 中修改全局 Client 可能导致的竞态
- 方案:改为直接操作当前上下文的 r *resty.Request 注入而不是 client
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant