Debian Codegraph @

vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb.go

raw
1 package runtime
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "reflect"
9
10 "github.com/golang/protobuf/jsonpb"
11 "github.com/golang/protobuf/proto"
12 )
13
14 // JSONPb is a Marshaler which marshals/unmarshals into/from JSON
15 // with the "github.com/golang/protobuf/jsonpb".
16 // It supports fully functionality of protobuf unlike JSONBuiltin.
17 type JSONPb jsonpb.Marshaler
18
19 // ContentType always returns "application/json".
20 func (*JSONPb) ContentType() string {
21 return "application/json"
22 }
23
24 // Marshal marshals "v" into JSON
25 // Currently it can marshal only proto.Message.
26 // TODO(yugui) Support fields of primitive types in a message.
27 func (j *JSONPb) Marshal(v interface{}) ([]byte, error) {
28 if _, ok := v.(proto.Message); !ok {
29 return j.marshalNonProtoField(v)
30 }
31
32 var buf bytes.Buffer
33 if err := j.marshalTo(&buf, v); err != nil {
34 return nil, err
35 }
36 return buf.Bytes(), nil
37 }
38
39 func (j *JSONPb) marshalTo(w io.Writer, v interface{}) error {
40 p, ok := v.(proto.Message)
41 if !ok {
42 buf, err := j.marshalNonProtoField(v)
43 if err != nil {
44 return err
45 }
46 _, err = w.Write(buf)
47 return err
48 }
49 return (*jsonpb.Marshaler)(j).Marshal(w, p)
50 }
51
52 // marshalNonProto marshals a non-message field of a protobuf message.
53 // This function does not correctly marshals arbitary data structure into JSON,
54 // but it is only capable of marshaling non-message field values of protobuf,
55 // i.e. primitive types, enums; pointers to primitives or enums; maps from
56 // integer/string types to primitives/enums/pointers to messages.
57 func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) {
58 rv := reflect.ValueOf(v)
59 for rv.Kind() == reflect.Ptr {
60 if rv.IsNil() {
61 return []byte("null"), nil
62 }
63 rv = rv.Elem()
64 }
65
66 if rv.Kind() == reflect.Map {
67 m := make(map[string]*json.RawMessage)
68 for _, k := range rv.MapKeys() {
69 buf, err := j.Marshal(rv.MapIndex(k).Interface())
70 if err != nil {
71 return nil, err
72 }
73 m[fmt.Sprintf("%v", k.Interface())] = (*json.RawMessage)(&buf)
74 }
75 if j.Indent != "" {
76 return json.MarshalIndent(m, "", j.Indent)
77 }
78 return json.Marshal(m)
79 }
80 if enum, ok := rv.Interface().(protoEnum); ok && !j.EnumsAsInts {
81 return json.Marshal(enum.String())
82 }
83 return json.Marshal(rv.Interface())
84 }
85
86 // Unmarshal unmarshals JSON "data" into "v"
87 // Currently it can marshal only proto.Message.
88 // TODO(yugui) Support fields of primitive types in a message.
89 func (j *JSONPb) Unmarshal(data []byte, v interface{}) error {
90 return unmarshalJSONPb(data, v)
91 }
92
93 // NewDecoder returns a Decoder which reads JSON stream from "r".
94 func (j *JSONPb) NewDecoder(r io.Reader) Decoder {
95 d := json.NewDecoder(r)
96 return DecoderFunc(func(v interface{}) error { return decodeJSONPb(d, v) })
97 }
98
99 // NewEncoder returns an Encoder which writes JSON stream into "w".
100 func (j *JSONPb) NewEncoder(w io.Writer) Encoder {
101 return EncoderFunc(func(v interface{}) error { return j.marshalTo(w, v) })
102 }
103
104 func unmarshalJSONPb(data []byte, v interface{}) error {
105 d := json.NewDecoder(bytes.NewReader(data))
106 return decodeJSONPb(d, v)
107 }
108
109 func decodeJSONPb(d *json.Decoder, v interface{}) error {
110 p, ok := v.(proto.Message)
111 if !ok {
112 return decodeNonProtoField(d, v)
113 }
114 unmarshaler := &jsonpb.Unmarshaler{AllowUnknownFields: true}
115 return unmarshaler.UnmarshalNext(d, p)
116 }
117
118 func decodeNonProtoField(d *json.Decoder, v interface{}) error {
119 rv := reflect.ValueOf(v)
120 if rv.Kind() != reflect.Ptr {
121 return fmt.Errorf("%T is not a pointer", v)
122 }
123 for rv.Kind() == reflect.Ptr {
124 if rv.IsNil() {
125 rv.Set(reflect.New(rv.Type().Elem()))
126 }
127 if rv.Type().ConvertibleTo(typeProtoMessage) {
128 unmarshaler := &jsonpb.Unmarshaler{AllowUnknownFields: true}
129 return unmarshaler.UnmarshalNext(d, rv.Interface().(proto.Message))
130 }
131 rv = rv.Elem()
132 }
133 if rv.Kind() == reflect.Map {
134 if rv.IsNil() {
135 rv.Set(reflect.MakeMap(rv.Type()))
136 }
137 conv, ok := convFromType[rv.Type().Key().Kind()]
138 if !ok {
139 return fmt.Errorf("unsupported type of map field key: %v", rv.Type().Key())
140 }
141
142 m := make(map[string]*json.RawMessage)
143 if err := d.Decode(&m); err != nil {
144 return err
145 }
146 for k, v := range m {
147 result := conv.Call([]reflect.Value{reflect.ValueOf(k)})
148 if err := result[1].Interface(); err != nil {
149 return err.(error)
150 }
151 bk := result[0]
152 bv := reflect.New(rv.Type().Elem())
153 if err := unmarshalJSONPb([]byte(*v), bv.Interface()); err != nil {
154 return err
155 }
156 rv.SetMapIndex(bk, bv.Elem())
157 }
158 return nil
159 }
160 if _, ok := rv.Interface().(protoEnum); ok {
161 var repr interface{}
162 if err := d.Decode(&repr); err != nil {
163 return err
164 }
165 switch repr.(type) {
166 case string:
167 // TODO(yugui) Should use proto.StructProperties?
168 return fmt.Errorf("unmarshaling of symbolic enum %q not supported: %T", repr, rv.Interface())
169 case float64:
170 rv.Set(reflect.ValueOf(int32(repr.(float64))).Convert(rv.Type()))
171 return nil
172 default:
173 return fmt.Errorf("cannot assign %#v into Go type %T", repr, rv.Interface())
174 }
175 }
176 return d.Decode(v)
177 }
178
179 type protoEnum interface {
180 fmt.Stringer
181 EnumDescriptor() ([]byte, []int)
182 }
183
184 var typeProtoMessage = reflect.TypeOf((*proto.Message)(nil)).Elem()