forked from bojand/ghz
/
call_template_data.go
81 lines (69 loc) · 2.24 KB
/
call_template_data.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package ghz
import (
"bytes"
"encoding/json"
"text/template"
"time"
"github.com/jhump/protoreflect/desc"
)
// call template data
type callTemplateData struct {
RequestNumber int64 // unique incrememnted request number for each request
FullyQualifiedName string // fully-qualified name of the method call
MethodName string // shorter call method name
ServiceName string // the service name
InputName string // name of the input message type
OutputName string // name of the output message type
IsClientStreaming bool // whether this call is client streaming
IsServerStreaming bool // whether this call is server streaming
Timestamp string // timestamp of the call in RFC3339 format
TimestampUnix int64 // timestamp of the call as unix time
}
// newCallTemplateData returns new call template data
func newCallTemplateData(mtd *desc.MethodDescriptor, reqNum int64) *callTemplateData {
now := time.Now()
return &callTemplateData{
RequestNumber: reqNum,
FullyQualifiedName: mtd.GetFullyQualifiedName(),
MethodName: mtd.GetName(),
ServiceName: mtd.GetService().GetName(),
InputName: mtd.GetInputType().GetName(),
OutputName: mtd.GetOutputType().GetName(),
IsClientStreaming: mtd.IsClientStreaming(),
IsServerStreaming: mtd.IsServerStreaming(),
Timestamp: now.Format(time.RFC3339),
TimestampUnix: now.Unix(),
}
}
func (td *callTemplateData) execute(data string) (*bytes.Buffer, error) {
t := template.Must(template.New("call_template_data").Parse(data))
var tpl bytes.Buffer
err := t.Execute(&tpl, td)
return &tpl, err
}
func (td *callTemplateData) executeData(data string) (interface{}, error) {
input := []byte(data)
tpl, err := td.execute(data)
if err == nil {
input = tpl.Bytes()
}
var dataMap interface{}
err = json.Unmarshal(input, &dataMap)
if err != nil {
return nil, err
}
return dataMap, nil
}
func (td *callTemplateData) executeMetadata(metadata string) (*map[string]string, error) {
input := []byte(metadata)
tpl, err := td.execute(metadata)
if err == nil {
input = tpl.Bytes()
}
var mdMap map[string]string
err = json.Unmarshal(input, &mdMap)
if err != nil {
return nil, err
}
return &mdMap, nil
}