1
1
package recording
2
2
3
3
import (
4
+ "bufio"
5
+ "bytes"
6
+ "compress/gzip"
4
7
"encoding/json"
8
+ "fmt"
9
+ "io/ioutil"
5
10
"net"
11
+ "net/http"
12
+ "strings"
6
13
"unicode/utf8"
14
+
15
+ "golang.org/x/text/encoding/simplifiedchinese"
16
+ "golang.org/x/text/transform"
17
+ )
18
+
19
+ const (
20
+ callOutboundAction = "callOutbound"
21
+ returnInboundAction = "returnInbound"
7
22
)
8
23
9
24
// Action Action
@@ -63,7 +78,7 @@ func (returnInbound *ReturnInbound) MarshalJSON() ([]byte, error) {
63
78
Response json.RawMessage
64
79
}{
65
80
ReturnInbound : * returnInbound ,
66
- Response : EncodeAnyByteArray (returnInbound .Response ),
81
+ Response : ParesResponse (returnInbound .Response , returnInboundAction ),
67
82
})
68
83
}
69
84
@@ -90,7 +105,7 @@ func (callOutbound *CallOutbound) MarshalJSON() ([]byte, error) {
90
105
}{
91
106
CallOutbound : * callOutbound ,
92
107
Request : EncodeAnyByteArray (callOutbound .Request ),
93
- Response : EncodeAnyByteArray (callOutbound .Response ),
108
+ Response : ParesResponse (callOutbound .Response , callOutboundAction ),
94
109
CSpanID : EncodeAnyByteArray (callOutbound .CSpanID ),
95
110
})
96
111
}
@@ -310,3 +325,59 @@ func EncodeAnyByteArray(s []byte) json.RawMessage {
310
325
encoded = append (encoded , '"' )
311
326
return json .RawMessage (encoded )
312
327
}
328
+
329
+ // ParesResponse ...
330
+ func ParesResponse (s []byte , action string ) json.RawMessage {
331
+ encoded := []byte {'"' }
332
+ if ! bytes .Contains (s , []byte ("Content-Encoding: gzip" )) {
333
+ return EncodeAnyByteArray (s )
334
+ }
335
+
336
+ // handle gzip response
337
+ reader := bufio .NewReader (strings .NewReader (string (s )))
338
+ resp , err := http .ReadResponse (reader , nil )
339
+ if err != nil {
340
+ fmt .Println ("反序列化HTTP响应出错:" , err )
341
+ return encoded
342
+ }
343
+ defer resp .Body .Close ()
344
+
345
+ // 解析响应体
346
+ bodyBytes , err := ioutil .ReadAll (resp .Body )
347
+ if err != nil {
348
+ fmt .Println ("读取响应体出错:" , err )
349
+ return encoded
350
+ }
351
+
352
+ // 检查Content-Encoding,并解压缩响应体
353
+ if resp .Header .Get ("Content-Encoding" ) == "gzip" {
354
+ reader , err := gzip .NewReader (bytes .NewReader (bodyBytes ))
355
+ if err != nil {
356
+ fmt .Println ("创建gzip解压缩读取器出错:" , err )
357
+ return encoded
358
+ }
359
+ defer reader .Close ()
360
+
361
+ bodyBytes , err = ioutil .ReadAll (reader )
362
+ if err != nil {
363
+ fmt .Println ("读取解压缩后的内容出错:" , err )
364
+ return encoded
365
+ }
366
+
367
+ switch action {
368
+ case returnInboundAction :
369
+ return bodyBytes
370
+ case callOutboundAction :
371
+ // 将GBK编码转换为UTF-8编码
372
+ utf8Bytes , err := ioutil .ReadAll (transform .NewReader (bytes .NewReader (bodyBytes ), simplifiedchinese .GBK .NewDecoder ()))
373
+ if err != nil {
374
+ fmt .Println ("err: " , err )
375
+ return encoded
376
+ }
377
+
378
+ return utf8Bytes
379
+ }
380
+ }
381
+
382
+ return encoded
383
+ }
0 commit comments