上篇文章 Go - 實作項目内鍊路追蹤 分享了,通過 鍊路 ID 請求資訊 響應資訊 調用第三方接口的資訊 調試資訊 執行的 SQL 資訊 執行的 Redis 資訊
可以将
、
串起來,記錄的具體參數在檔案中都有介紹。
這篇文章在上面的基礎上,新增 2 個功能點:
- 新增将
記錄到調用 gRPC 接口資訊
中;Trace
- 新增對記錄的敏感資訊進行脫敏處理;
調用 gRPC 接口資訊
記錄參數
Object
,結構如下:
type Grpc struct {
Timestamp string `json:"timestamp"` // 時間,格式:2006-01-02 15:04:05
Addr string `json:"addr"` // 位址
Method string `json:"method"` // 操作方法
Meta metadata.MD `json:"meta"` // Mate 資訊
Request map[string]interface{} `json:"request"` // 請求資訊
Response map[string]interface{} `json:"response"` // 傳回資訊
CostSeconds float64 `json:"cost_seconds"` // 執行時間(機關秒)
Code string `json:"err_code,omitempty"` // 錯誤碼
Message string `json:"err_message,omitempty"` // 錯誤資訊
}
如何收集參數
封裝了一個
grpclient
包:
- 支援設定
;DialTimeout
-
UnaryInterceptor
-
KeepaliveParams
-
TransportCredentials
主要是在攔截器
Interceptor
中進行收集。
示例代碼
執行個體化 gRPC client
// TODO 需從配置檔案中擷取
target := "127.0.0.1:9988"
secret := "abcdef"
clientInterceptor := NewClientInterceptor(func(message []byte) (authorization string, err error) {
return GenerateSign(secret, message)
})
conn, err := grpclient.New(target,
grpclient.WithKeepAlive(keepAlive),
grpclient.WithDialTimeout(time.Second*5),
grpclient.WithUnaryInterceptor(clientInterceptor.UnaryInterceptor),
)
return &clientConn{
conn: conn,
}, err
調用具體方法
// 核心:傳遞 core.Context 給 Interceptor 使用
client := hello.NewHelloClient(d.grpconn.Conn())
client.SayHello(grpc.ContextWithValueAndTimeout(c, time.Second*3), &hello.HelloRequest{Name: "Hello World"})
敏感資訊脫敏
敏感資訊脫敏又稱為動态資料掩碼(Dynamic Data Masking,簡稱為DDM)能夠防止把敏感資料暴露給未經授權的使用者。
根據項目要求可以約定一些規範,例如:
類型 | 要求 | 示例 | 說明 |
---|---|---|---|
手機号 | 前 3 後 4 | 132****7986 | 定長 11 位數字 |
郵箱位址 | 前 1 後 1 | l**[email protected] | 僅對 @ 之前的郵箱名稱進行掩碼 |
姓名 | 隐姓 | *鴻章 | 将姓氏隐藏 |
密碼 | 不輸出 | ****** | |
銀行卡卡号 | 前 6 後 4 | 622888******5676 | 銀行卡卡号最多 19 位數字 |
身份證号 | 1******7 | 定長 18 位 |
如何實作
我現在的實作方案是:自定義 MarshalJSON(),歡迎大佬們提出更好的方案。
// 定義 Mobile 類型
type Mobile string
// 自定義 MarshalJSON()
func (m Mobile) MarshalJSON() ([]byte, error) {
if len(m) != 11 {
return []byte(`"` + m + `"`), nil
}
v := fmt.Sprintf("%s****%s", m[:3], m[len(m)-4:])
return []byte(`"` + v + `"`), nil
}
測試
type message struct {
Mobile ddm.Mobile `json:"mobile"`
}
msg := new(message)
msg.Mobile = ddm.Mobile("13288889999")
marshal, _ := json.Marshal(msg)
fmt.Println(string(marshal))
// 輸出:{"mobile":"132****9999"}
小結
本篇文章新增了 2 個實用的功能點,大家趕緊使用起來吧。關于
敏感資訊脫敏
期待各位大佬不吝賜教,提出更好的解決方案,謝謝!
以上代碼都在 go-gin-api 項目中,位址:https://github.com/xinliangnote/go-gin-api
作者:新亮筆記(關注公衆号,可申請添加微信好友)
出處:https://www.cnblogs.com/xinliangcoder
本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。