package gateway import ( "context" "encoding/json" ) // RawCapture 收集一次网关调用的原始数据(最后一次 HTTP 尝试),供业务记录留存。 // 只保存加密前的明文业务请求与网关响应;不含加密报文、签名、应用标识、密钥与请求头。 type RawCapture struct { // Request 是加密前的明文业务请求({"params": ...});不记录载荷的调用为空。 Request json.RawMessage // HTTPStatus 是 HTTP 状态码;没拿到响应(超时、连接失败)时为 0。 HTTPStatus int // Response 是网关原始响应体;没拿到响应体时为空。 Response []byte // GatewayCode、GatewayMsg、TraceID 是网关响应外层字段;响应无法解析时为空。 GatewayCode *int GatewayMsg string TraceID string // Attempts 是网关客户端内部 HTTP 尝试次数。 Attempts int } type rawCaptureKey struct{} // WithRawCapture 在请求上下文上挂载原始数据收集器;未挂载的调用不收集。 func WithRawCapture(ctx context.Context) (context.Context, *RawCapture) { capture := &RawCapture{} return context.WithValue(ctx, rawCaptureKey{}, capture), capture } func rawCaptureFrom(ctx context.Context) *RawCapture { capture, _ := ctx.Value(rawCaptureKey{}).(*RawCapture) return capture } // resetResponse 在每次 HTTP 尝试前清空上一次的响应,保证留存的是最后一次尝试。 func (c *RawCapture) resetResponse() { if c == nil { return } c.HTTPStatus, c.Response, c.GatewayCode, c.GatewayMsg, c.TraceID = 0, nil, nil, "", "" }