-
Notifications
You must be signed in to change notification settings - Fork 49
/
marshaler.go
101 lines (82 loc) · 1.91 KB
/
marshaler.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package api
import (
"encoding/json"
"io"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"go.temporal.io/api/temporalproto"
"google.golang.org/protobuf/proto"
)
type temporalProtoMarshaler struct {
contentType string
mOpts temporalproto.CustomJSONMarshalOptions
uOpts temporalproto.CustomJSONUnmarshalOptions
}
type temporalProtoEncoder struct {
mOpts temporalproto.CustomJSONMarshalOptions
writer io.Writer
json *json.Encoder
}
type temporalProtoDecoder struct {
uOpts temporalproto.CustomJSONUnmarshalOptions
reader io.Reader
json *json.Decoder
}
func (p temporalProtoMarshaler) Marshal(v any) ([]byte, error) {
if m, ok := v.(proto.Message); ok {
return p.mOpts.Marshal(m)
}
if p.mOpts.Indent != "" {
return json.MarshalIndent(v, "", p.mOpts.Indent)
}
return json.Marshal(v)
}
func (p temporalProtoMarshaler) Unmarshal(data []byte, v interface{}) error {
if m, ok := v.(proto.Message); ok {
return p.uOpts.Unmarshal(data, m)
}
return json.Unmarshal(data, v)
}
func (p temporalProtoMarshaler) NewDecoder(r io.Reader) runtime.Decoder {
return temporalProtoDecoder{
p.uOpts,
r,
json.NewDecoder(r),
}
}
func (p temporalProtoMarshaler) NewEncoder(w io.Writer) runtime.Encoder {
return temporalProtoEncoder{
p.mOpts,
w,
json.NewEncoder(w),
}
}
func (p temporalProtoMarshaler) ContentType(_ any) string {
return p.contentType
}
func (d temporalProtoDecoder) Decode(v any) error {
m, ok := v.(proto.Message)
if !ok {
return d.json.Decode(v)
}
var bs json.RawMessage
if err := d.json.Decode(&bs); err != nil {
return err
}
return d.uOpts.Unmarshal([]byte(bs), m)
}
func (e temporalProtoEncoder) Encode(v any) error {
m, ok := v.(proto.Message)
if !ok {
return e.json.Encode(v)
}
bs, err := e.mOpts.Marshal(m)
if err != nil {
return err
}
_, err = e.writer.Write(bs)
if err != nil {
return err
}
_, err = e.writer.Write([]byte{'\n'})
return err
}