/
utils.go
53 lines (45 loc) · 1.3 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
// Package utils provides utilities for GRPC.
package utils
import (
"fmt"
"unicode/utf8"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
var (
protoJSONMarshaller = &protojson.MarshalOptions{
EmitUnpopulated: true,
}
)
// MarshalPbMessageToJsonString marshals protobuf message to json string.
func MarshalPbMessageToJsonString(msg proto.Message) string {
return protoJSONMarshaller.Format(msg)
}
func MarshalMessageToJsonStringForTracing(value interface{}, msgType string, maxBytes int) string {
var messageContent string
if msg, ok := value.(proto.Message); ok {
if proto.Size(msg) <= maxBytes {
messageContent = MarshalPbMessageToJsonString(msg)
} else {
messageContent = fmt.Sprintf(
"[%s Message Too Large For Tracing, Max: %d bytes]",
msgType,
maxBytes,
)
}
} else {
messageContent = fmt.Sprintf("%v", value)
}
if !utf8.ValidString(messageContent) {
messageContent = fmt.Sprintf(
"[%s Message Is Invalid UTF-8 Content For Tracing]",
msgType,
)
}
return messageContent
}