完善服务端交互日志与初始化测试

统一划分 MTOP 与 WebSocket 日志等级,增加 Token 安全指纹和请求耗时诊断;补充 init-admin 临时数据库测试;同步 README 的镜像发布说明。
This commit is contained in:
Christ committed 2026-08-08 12:05:43 +08:00
1 parent ad224bf4e9
commit d7abbfb2b6
16 files changed
+274 -74

No files matched your search

+5 -2
View File
@@ -310,7 +310,7 @@ LocalAI 或兼容网关。只有在明确了解数据流向时才应向外部 AI
GitHub Actions 会将同一标签发布为多架构镜像:
```text
ghcr.io/christ9038/ydisks-xianyu-helper:dev
ghcr.io/christ9038/ydisks-xianyu-helper:latest
├── linux/amd64
└── linux/arm64
```
@@ -322,10 +322,13 @@ ARM64 Linux 拉取 arm64,不需要手动设置 `platform`。
| Git 引用 | 镜像标签 |
| --- | --- |
| `dev` 分支 | `dev`、`sha-<完整提交号>` |
| `main` 分支 | `main`、`latest`、`sha-<完整提交号>` |
| `v1.2.3` 标签 | `1.2.3`、`1.2`、`sha-<完整提交号>` |
当前 Docker 发布工作流只在 `main` 分支推送和发布镜像;`dev` 分支不会自动生成
GHCR 标签。开发分支如需验证镜像,请在本地使用源码构建 Compose 文件,或手动运行
对应的构建流程。
生产环境建议使用明确的版本标签或 SHA 标签,避免上游更新导致未经验证的自动升级。
### Compose 服务
+36 -28
View File
@@ -7,8 +7,10 @@ package main
import (
"bufio"
"context"
"errors"
"flag"
"fmt"
"io"
"os"
"strings"
@@ -32,66 +34,72 @@ func main() {
resolved = *dbPath
}
ctx := context.Background()
if err := run(context.Background(), resolved, bufio.NewReader(os.Stdin), os.Stdout); err != nil {
fatalf("初始化管理员失败: %v", err)
}
}
// run 执行一次初始化流程。把数据库、输入和输出显式注入后,CLI 的核心行为
// 可以在临时数据库中回归测试,而不会调用 os.Exit 或污染用户数据。
func run(ctx context.Context, resolved string, reader *bufio.Reader, out io.Writer) error {
database, dialect, err := db.Open(ctx, resolved)
if err != nil {
fatalf("打开数据库失败: %v", err)
return fmt.Errorf("打开数据库失败: %w", err)
}
defer database.Close()
store := db.NewStore(database, dialect)
reader := bufio.NewReader(os.Stdin)
existing, err := store.Users.GetAdmin(ctx)
if err != nil && !isNotFound(err) {
fatalf("查询 admin 失败: %v", err)
return fmt.Errorf("查询 admin 失败: %w", err)
}
if existing != nil {
fmt.Printf("管理员用户 %s 已存在\n", existing.Username)
fmt.Print("是否重置管理员密码?(y/N): ")
fmt.Fprintf(out, "管理员用户 %s 已存在\n", existing.Username)
fmt.Fprint(out, "是否重置管理员密码?(y/N): ")
ans, _ := reader.ReadString('\n')
if !strings.HasPrefix(strings.ToLower(strings.TrimSpace(ans)), "y") {
fmt.Println("跳过初始化")
return
fmt.Fprintln(out, "跳过初始化")
return nil
}
pw := promptPasswordTwice(reader)
pw := promptPasswordTwice(reader, out)
if _, err := auth.InitAdmin(ctx, store, "", pw); err != nil {
fatalf("重置 admin 密码失败: %v", err)
return fmt.Errorf("重置 admin 密码失败: %w", err)
}
fmt.Printf("重置完成:已更新 %s 的密码\n", existing.Username)
return
fmt.Fprintf(out, "重置完成:已更新 %s 的密码\n", existing.Username)
return nil
}
fmt.Println("=== 初始化管理员账号(CLI)===")
fmt.Print("请输入管理员邮箱: ")
fmt.Fprintln(out, "=== 初始化管理员账号(CLI)===")
fmt.Fprint(out, "请输入管理员邮箱: ")
email, _ := reader.ReadString('\n')
email = strings.TrimSpace(email)
if email == "" {
fatalf("邮箱不能为空")
return errors.New("邮箱不能为空")
}
pw := promptPasswordTwice(reader)
pw := promptPasswordTwice(reader, out)
created, err := auth.InitAdmin(ctx, store, email, pw)
if err != nil {
fatalf("创建 admin 用户失败:%v", err)
return fmt.Errorf("创建 admin 用户失败:%w", err)
}
if created {
fmt.Println("初始化完成:已创建 admin 用户")
fmt.Fprintln(out, "初始化完成:已创建 admin 用户")
}
return nil
}
// promptPasswordTwice 两次输入密码(不回显)并校验一致性。
func promptPasswordTwice(reader *bufio.Reader) string {
func promptPasswordTwice(reader *bufio.Reader, out io.Writer) string {
for {
p1 := readPasswordNoEcho(reader, "请输入管理员密码(不回显): ")
p1 := readPasswordNoEcho(reader, "请输入管理员密码(不回显): ", out)
if p1 == "" {
fmt.Println("密码不能为空")
fmt.Fprintln(out, "密码不能为空")
continue
}
p2 := readPasswordNoEcho(reader, "请再次输入管理员密码(不回显): ")
p2 := readPasswordNoEcho(reader, "请再次输入管理员密码(不回显): ", out)
if p1 != p2 {
fmt.Println("两次输入不一致,请重试")
fmt.Fprintln(out, "两次输入不一致,请重试")
continue
}
return p1
@@ -100,11 +108,11 @@ func promptPasswordTwice(reader *bufio.Reader) string {
// readPasswordNoEcho 不回显读取密码。非 TTY 时回退到普通读取(如管道),
// 共用同一 bufio.Reader 避免缓冲吞掉后续输入。
func readPasswordNoEcho(reader *bufio.Reader, prompt string) string {
fmt.Print(prompt)
func readPasswordNoEcho(reader *bufio.Reader, prompt string, out io.Writer) string {
fmt.Fprint(out, prompt)
if term.IsTerminal(int(os.Stdin.Fd())) {
b, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Println()
fmt.Fprintln(out)
if err != nil {
fatalf("读取密码失败: %v", err)
}
@@ -116,7 +124,7 @@ func readPasswordNoEcho(reader *bufio.Reader, prompt string) string {
return strings.TrimSpace(s)
}
func isNotFound(err error) bool { return err == db.ErrNotFound }
func isNotFound(err error) bool { return errors.Is(err, db.ErrNotFound) }
func fatalf(format string, a ...any) {
fmt.Fprintf(os.Stderr, format+"\n", a...)
+106
View File
@@ -0,0 +1,106 @@
package main
import (
"bufio"
"bytes"
"context"
"flag"
"io"
"os"
"path/filepath"
"strings"
"testing"
"xianyu-go/internal/db"
)
func TestRunCreatesAdminInTemporaryDatabase(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
var out bytes.Buffer
err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("admin@example.com\nsecret\nsecret\n")), &out)
if err != nil {
t.Fatalf("run create: %v", err)
}
if !strings.Contains(out.String(), "初始化完成") {
t.Fatalf("missing create confirmation: %s", out.String())
}
d, dialect, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatal(err)
}
defer d.Close()
admin, err := db.NewStore(d, dialect).Users.GetAdmin(context.Background())
if err != nil || admin == nil || admin.Email != "admin@example.com" {
t.Fatalf("admin=%+v err=%v", admin, err)
}
}
func TestRunExistingAdminCanSkipReset(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
input := "admin@example.com\nsecret\nsecret\n"
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader(input)), &bytes.Buffer{}); err != nil {
t.Fatal(err)
}
var out bytes.Buffer
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("n\n")), &out); err != nil {
t.Fatal(err)
}
if !strings.Contains(out.String(), "跳过初始化") {
t.Fatalf("missing skip confirmation: %s", out.String())
}
}
func TestRunExistingAdminResetsPasswordAfterMismatchRetry(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("admin@example.com\nold\nold\n")), &bytes.Buffer{}); err != nil {
t.Fatal(err)
}
input := "y\nnew\nnot-the-same\nnew\nnew\n"
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader(input)), &bytes.Buffer{}); err != nil {
t.Fatal(err)
}
d, dialect, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatal(err)
}
defer d.Close()
store := db.NewStore(d, dialect)
if _, ok, _ := store.Users.VerifyAndUpgrade(context.Background(), "admin", "old"); ok {
t.Fatal("old password should be invalid")
}
if _, ok, _ := store.Users.VerifyAndUpgrade(context.Background(), "admin", "new"); !ok {
t.Fatal("new password should be valid")
}
}
func TestRunRejectsEmptyEmail(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("\n")), &bytes.Buffer{})
if err == nil || !strings.Contains(err.Error(), "邮箱不能为空") {
t.Fatalf("err=%v, want empty email error", err)
}
}
func TestMainCLIEntrypointUsesDatabaseFlag(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "main.db")
stdin, writer, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
oldArgs, oldStdin, oldEnv, oldCommandLine := os.Args, os.Stdin, os.Getenv("DATABASE_URL"), flag.CommandLine
defer func() {
os.Args, os.Stdin, flag.CommandLine = oldArgs, oldStdin, oldCommandLine
_ = os.Setenv("DATABASE_URL", oldEnv)
_ = stdin.Close()
}()
os.Args = []string{"init-admin", "-db", dbPath}
os.Stdin = stdin
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
flag.CommandLine.SetOutput(io.Discard)
_ = os.Unsetenv("DATABASE_URL")
go func() {
_, _ = writer.Write([]byte("admin@example.com\nmain-secret\nmain-secret\n"))
_ = writer.Close()
}()
main()
}
+16 -1
View File
@@ -8,6 +8,7 @@ package engine
import (
"context"
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"log/slog"
@@ -192,6 +193,7 @@ type Account struct {
tokenAcquiredAt time.Time
tokenExpiresAt time.Time
tokenRefreshAt time.Time
tokenFingerprint string // 仅用于诊断,不保存原始 Token
// 去重
dedupMu sync.Mutex
@@ -1539,12 +1541,15 @@ func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken stri
}
now := time.Now()
expiresAt, refreshAt := tokenRotationSchedule(serverExpireAt, now)
tokenFP := tokenFingerprint(accessToken)
a.mu.Lock()
previousTokenFP := a.tokenFingerprint
a.tokenFingerprint = tokenFP
a.tokenAcquiredAt = now
a.tokenExpiresAt = expiresAt
a.tokenRefreshAt = refreshAt
a.mu.Unlock()
a.logger.Info("WS Token 获取成功", "expires_at", expiresAt, "refresh_at", refreshAt, "ttl", time.Until(expiresAt).Round(time.Second))
a.logger.Info("WS Token 获取成功", "expires_at", expiresAt, "refresh_at", refreshAt, "ttl", time.Until(expiresAt).Round(time.Second), "token_fp", tokenFP, "previous_token_fp", previousTokenFP, "token_changed", previousTokenFP == "" || previousTokenFP != tokenFP)
if a.store == nil || a.store.Tokens == nil {
return
}
@@ -1561,8 +1566,18 @@ func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken stri
}
}
// tokenFingerprint 用不可逆摘要标识 Token,便于判断服务端是否轮换了 Token,
// 同时避免日志泄露可用于 WS 注册的凭证原文。
func tokenFingerprint(token string) string {
sum := sha256.Sum256([]byte(token))
return fmt.Sprintf("%x", sum[:6])
}
// clearTokenCache 清除账号 token 缓存(session 失效 / 短连接可疑 / cookie 被外部更新时调用)。
func (a *Account) clearTokenCache(ctx context.Context) {
a.mu.Lock()
a.tokenFingerprint = ""
a.mu.Unlock()
if a.store == nil || a.store.Tokens == nil {
return
}
+16
View File
@@ -76,3 +76,19 @@ func TestCredentialStateFingerprintIncludesAuthoritativeSnapshot(t *testing.T) {
t.Fatal("权威空 Jar 必须与没有快照的历史状态区分")
}
}
func TestTokenFingerprintIsStableNonReversibleDiagnosticID(t *testing.T) {
first := tokenFingerprint("access-token-a")
if first == "" || len(first) != 12 {
t.Fatalf("token fingerprint=%q, want 12 hex chars", first)
}
if first != tokenFingerprint("access-token-a") {
t.Fatal("same token must produce stable fingerprint")
}
if first == tokenFingerprint("access-token-b") {
t.Fatal("different tokens must produce different fingerprints")
}
if first == "access-token-a" {
t.Fatal("fingerprint must not expose the token")
}
}
+56 -1
View File
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"strconv"
"strings"
@@ -61,7 +62,10 @@ type Client interface {
// ClientImpl 是 Client 接口的 HTTP 实现。零值可用;HTTP 超时默认 30s。
// 仍导出 HTTPClient/TokenURL 等字段以便调用方覆盖(如测试注入 RoundTripper)。
type ClientImpl struct {
HTTPClient *http.Client
HTTPClient *http.Client
// Logger 记录 MTOP 请求的安全摘要(不会输出 Cookie、签名或响应正文)。
// 未设置时使用 slog.Default,测试可传入丢弃日志的 logger。
Logger *slog.Logger
TokenURL string
ConsignURL string
OrderDetailURL string
@@ -70,6 +74,57 @@ type ClientImpl struct {
LoginUserURL string
}
// httpClient 返回带统一请求/响应日志的 HTTP 客户端副本。统一放在传输层,
// 确保 token、续期、订单、商品和发布等所有 MTOP 调用都具备一致的可观测性。
func (c *ClientImpl) httpClient() *http.Client {
return c.httpClientWithTimeout(30 * time.Second)
}
func (c *ClientImpl) httpClientWithTimeout(defaultTimeout time.Duration) *http.Client {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: defaultTimeout}
}
clone := *hc
transport := hc.Transport
if transport == nil {
transport = http.DefaultTransport
}
clone.Transport = loggingTransport{base: transport, logger: c.Logger}
return &clone
}
type loggingTransport struct {
base http.RoundTripper
logger *slog.Logger
}
func (t loggingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
logger := t.logger
if logger == nil {
logger = slog.Default()
}
started := time.Now()
logger.Debug("MTOP 请求开始", "method", req.Method, "path", req.URL.Path)
resp, err := t.base.RoundTrip(req)
attrs := []any{"method", req.Method, "path", req.URL.Path, "duration", time.Since(started).Round(time.Millisecond)}
if err != nil {
if errors.Is(err, context.Canceled) {
logger.Debug("MTOP 请求取消", append(attrs, "err", err)...)
} else {
logger.Warn("MTOP 请求失败", append(attrs, "err", err)...)
}
return nil, err
}
responseAttrs := append(attrs, "status", resp.StatusCode, "content_length", resp.ContentLength)
if resp.StatusCode >= http.StatusBadRequest {
logger.Warn("MTOP HTTP 响应异常", responseAttrs...)
} else {
logger.Debug("MTOP 响应收到", responseAttrs...)
}
return resp, nil
}
// NewClient 构造纯 Go HTTP 的 MTOP 客户端。Chromium 只用于读取本机指纹
// 和处理滑块,不能成为登录、续期、token 或 WebSocket 的传输层。
func NewClient() *ClientImpl {
+1 -4
View File
@@ -68,10 +68,7 @@ func (c *ClientImpl) ConsignContext(ctx context.Context, cookiesStr, orderID str
}
func (c *ClientImpl) consignOnce(ctx context.Context, cookiesStr, orderID string) (ok bool, ret []string, updatedCookies string, err error) {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
hc := c.httpClient()
consignURL := c.ConsignURL
if consignURL == "" {
consignURL = ConsignAPI
+1 -4
View File
@@ -49,10 +49,7 @@ func (c *ClientImpl) DetectItemMultiSpec(ctx context.Context, cookies, itemID st
req.Header.Set("Origin", "https://www.goofish.com")
req.Header.Set("Referer", documentURL)
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
hc := c.httpClient()
resp, err := hc.Do(req)
if err != nil {
return false, fmt.Errorf("商品详情请求失败: %w", err)
+1 -4
View File
@@ -59,10 +59,7 @@ func (c *ClientImpl) FetchItemsPage(ctx context.Context, cookiesStr string, page
}
func (c *ClientImpl) fetchItemsPageOnce(ctx context.Context, cookiesStr string, pageNumber, pageSize int) (*ItemListResult, []string, string, error) {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
hc := c.httpClient()
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", ItemListAPI)
cookies := protocol.TransCookies(signingCookies)
userID := cookies["unb"]
+1 -4
View File
@@ -38,10 +38,7 @@ func (c *ClientImpl) CheckLoginStatusContext(ctx context.Context, cookiesStr str
if session := cookieSessionFromContext(ctx); session != nil {
cookiesStr, _, _ = session.State()
}
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 20 * time.Second}
}
hc := c.httpClientWithTimeout(20 * time.Second)
loginURL := c.LoginUserURL
if loginURL == "" {
loginURL = LoginUserAPI
+1 -4
View File
@@ -66,10 +66,7 @@ func (c *ClientImpl) FetchOrderDetail(ctx context.Context, cookiesStr, orderID s
}
func (c *ClientImpl) fetchOrderDetailOnce(ctx context.Context, cookiesStr, orderID string) (*OrderDetailResult, []string, string, error) {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
hc := c.httpClient()
endpoint := c.OrderDetailURL
if endpoint == "" {
endpoint = OrderDetailAPI
+2 -8
View File
@@ -208,10 +208,7 @@ func (c *ClientImpl) RecommendPublishCategory(ctx context.Context, cookiesStr, k
}
func (c *ClientImpl) uploadPublishImage(ctx context.Context, cookiesStr string, img PublishImage) (uploadedImage, string, error) {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 60 * time.Second}
}
hc := c.httpClientWithTimeout(60 * time.Second)
if img.ContentType == "" {
img.ContentType = "application/octet-stream"
}
@@ -495,10 +492,7 @@ func (c *ClientImpl) publishItemOnce(ctx context.Context, cookiesStr string, req
}
func (c *ClientImpl) callMTop(ctx context.Context, cookiesStr, endpoint, api, version, spmCnt, spmPre, logID string, data any) (map[string]any, string, error) {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
hc := c.httpClient()
rawData, _ := json.Marshal(data)
dataVal := string(rawData)
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", endpoint)
+1 -4
View File
@@ -88,10 +88,7 @@ func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pa
req.Header.Set("Referer", soldOrdersReferer)
req.Header.Set("idle_site_biz_code", "COMMONPRO")
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
hc := c.httpClient()
resp, err := hc.Do(req)
if err != nil {
return nil, fmt.Errorf("订单列表请求失败: %w", err)
+1 -4
View File
@@ -154,10 +154,7 @@ func (c *ClientImpl) RequestFreshCaptchaURLContext(ctx context.Context, cookiesS
}
func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID string, cookieSnapshot []cookierefresh.BrowserCookie) (string, int64, []string, string, []cookierefresh.BrowserCookie, string, int, bool, bool, error) {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 20 * time.Second}
}
hc := c.httpClientWithTimeout(20 * time.Second)
tokenURL := c.TokenURL
if tokenURL == "" {
+1 -4
View File
@@ -53,10 +53,7 @@ func (c *ClientImpl) FetchUserProfile(ctx context.Context, cookiesStr string) (*
}
func (c *ClientImpl) fetchUserProfileOnce(ctx context.Context, cookiesStr string) (*UserProfileResult, []string, string, error) {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
hc := c.httpClient()
dataVal := "{}"
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", UserPageNavAPI)
+29 -2
View File
@@ -5,6 +5,7 @@ import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
@@ -232,9 +233,11 @@ func openBatch(ctx context.Context, target string, cfg Config, logger *slog.Logg
if result.conn != nil {
_ = result.conn.CloseNow()
}
logger.Warn("闲鱼 WebSocket 握手失败", "url", target, "err", result.err)
return nil, fmt.Errorf("WS dial: %w", result.err)
}
result.conn.SetReadLimit(8 << 20)
logger.Info("闲鱼 WebSocket 握手成功", "url", target)
return newConn(result.conn, cfg, logger), nil
}
@@ -350,6 +353,8 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any,
headers["mid"] = mid
}
key := midKey(mid)
started := time.Now()
c.logger.Debug("WS 请求发送", "path", path, "mid", key)
responseCh := make(chan map[string]any, 1)
c.pendingMu.Lock()
c.pending[key] = responseCh
@@ -365,10 +370,13 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any,
frame["body"] = body
}
if err := c.sendJSON(requestCtx, frame); err != nil {
c.logger.Warn("WS 请求发送失败", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err)
return nil, err
}
select {
case response := <-responseCh:
code, _ := responseCode(response["code"])
c.logResponse(path, key, code, time.Since(started))
return response, nil
case <-c.readDone:
// readPump always dispatches a decoded response before it can observe the
@@ -376,15 +384,34 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any,
// matching browser event ordering (message before close).
select {
case response := <-responseCh:
code, _ := responseCode(response["code"])
c.logResponse(path, key, code, time.Since(started))
return response, nil
default:
}
return nil, c.connectionReadError()
err := c.connectionReadError()
c.logger.Warn("WS 请求因连接结束失败", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err)
return nil, err
case <-requestCtx.Done():
return nil, requestCtx.Err()
err := requestCtx.Err()
if errors.Is(err, context.Canceled) {
c.logger.Debug("WS 请求取消", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err)
} else {
c.logger.Warn("WS 请求超时", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err)
}
return nil, err
}
}
func (c *Conn) logResponse(path, mid string, code int, duration time.Duration) {
attrs := []any{"path", path, "mid", mid, "code", code, "duration", duration.Round(time.Millisecond)}
if code >= 400 {
c.logger.Warn("WS 业务响应异常", attrs...)
return
}
c.logger.Debug("WS 响应收到", attrs...)
}
func (c *Conn) readPump() {
defer close(c.readDone)
for {