/
jsonpb.marshaler.go
85 lines (72 loc) · 2.05 KB
/
jsonpb.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
// Copyright 2020 The searKing Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package runtime
import (
"bytes"
"encoding/json"
"io"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/protobuf/proto"
)
//go:generate go-option -type=JSONPb
// json -> proto|interface{}
type JSONPb struct {
runtime.JSONPb
}
func (j *JSONPb) Marshal(v interface{}) ([]byte, error) {
// proto -> json
if _, ok := v.(proto.Message); ok {
return j.JSONPb.Marshal(v)
}
// interface{} -> json
var buf bytes.Buffer
if err := j.marshalTo(&buf, v); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Unmarshal unmarshals JSON "data" into "v"
func (j *JSONPb) Unmarshal(data []byte, v interface{}) error {
return j.NewDecoder(bytes.NewReader(data)).Decode(v)
}
// NewDecoder returns a Decoder which reads JSON stream from "r".
func (j *JSONPb) NewDecoder(r io.Reader) runtime.Decoder {
return DecoderWrapper{
decoderProto: j.JSONPb.NewDecoder(r),
decoderJson: json.NewDecoder(r),
}
}
// NewEncoder returns an Encoder which writes JSON stream into "w".
func (j *JSONPb) NewEncoder(w io.Writer) runtime.Encoder {
return j.JSONPb.NewEncoder(w)
}
// interface{} -> json
func (j *JSONPb) marshalTo(w io.Writer, v interface{}) error {
marshal := func() ([]byte, error) {
if _, ok := v.(proto.Message); ok {
return j.JSONPb.Marshal(v)
}
return json.Marshal(v)
}
buf, err := marshal()
if err != nil {
return err
}
_, err = w.Write(buf)
return err
}
// DecoderWrapper is a wrapper around a *json.Decoder that adds
// support for proto and json to the Decode method.
type DecoderWrapper struct {
decoderProto runtime.Decoder // json -> proto
decoderJson *json.Decoder // json -> interface{}
}
// Decode wraps the embedded decoder's Decode method to support
// protos using a jsonpb.Unmarshaler.
func (d DecoderWrapper) Decode(v interface{}) error {
if _, ok := v.(proto.Message); ok {
return d.decoderProto.Decode(v)
}
return d.decoderJson.Decode(v)
}