Debian Codegraph @

vendor/github.com/golang/protobuf/jsonpb/jsonpb.go

raw
1 // Go support for Protocol Buffers - Google's data interchange format
2 //
3 // Copyright 2015 The Go Authors. All rights reserved.
4 // https://github.com/golang/protobuf
5 //
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are
8 // met:
9 //
10 // * Redistributions of source code must retain the above copyright
11 // notice, this list of conditions and the following disclaimer.
12 // * Redistributions in binary form must reproduce the above
13 // copyright notice, this list of conditions and the following disclaimer
14 // in the documentation and/or other materials provided with the
15 // distribution.
16 // * Neither the name of Google Inc. nor the names of its
17 // contributors may be used to endorse or promote products derived from
18 // this software without specific prior written permission.
19 //
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32 /*
33 Package jsonpb provides marshaling and unmarshaling between protocol buffers and JSON.
34 It follows the specification at https://developers.google.com/protocol-buffers/docs/proto3#json.
35
36 This package produces a different output than the standard "encoding/json" package,
37 which does not operate correctly on protocol buffers.
38 */
39 package jsonpb
40
41 import (
42 "bytes"
43 "encoding/json"
44 "errors"
45 "fmt"
46 "io"
47 "math"
48 "reflect"
49 "sort"
50 "strconv"
51 "strings"
52 "time"
53
54 "github.com/golang/protobuf/proto"
55
56 stpb "github.com/golang/protobuf/ptypes/struct"
57 )
58
59 // Marshaler is a configurable object for converting between
60 // protocol buffer objects and a JSON representation for them.
61 type Marshaler struct {
62 // Whether to render enum values as integers, as opposed to string values.
63 EnumsAsInts bool
64
65 // Whether to render fields with zero values.
66 EmitDefaults bool
67
68 // A string to indent each level by. The presence of this field will
69 // also cause a space to appear between the field separator and
70 // value, and for newlines to be appear between fields and array
71 // elements.
72 Indent string
73
74 // Whether to use the original (.proto) name for fields.
75 OrigName bool
76
77 // A custom URL resolver to use when marshaling Any messages to JSON.
78 // If unset, the default resolution strategy is to extract the
79 // fully-qualified type name from the type URL and pass that to
80 // proto.MessageType(string).
81 AnyResolver AnyResolver
82 }
83
84 // AnyResolver takes a type URL, present in an Any message, and resolves it into
85 // an instance of the associated message.
86 type AnyResolver interface {
87 Resolve(typeUrl string) (proto.Message, error)
88 }
89
90 func defaultResolveAny(typeUrl string) (proto.Message, error) {
91 // Only the part of typeUrl after the last slash is relevant.
92 mname := typeUrl
93 if slash := strings.LastIndex(mname, "/"); slash >= 0 {
94 mname = mname[slash+1:]
95 }
96 mt := proto.MessageType(mname)
97 if mt == nil {
98 return nil, fmt.Errorf("unknown message type %q", mname)
99 }
100 return reflect.New(mt.Elem()).Interface().(proto.Message), nil
101 }
102
103 // JSONPBMarshaler is implemented by protobuf messages that customize the
104 // way they are marshaled to JSON. Messages that implement this should
105 // also implement JSONPBUnmarshaler so that the custom format can be
106 // parsed.
107 type JSONPBMarshaler interface {
108 MarshalJSONPB(*Marshaler) ([]byte, error)
109 }
110
111 // JSONPBUnmarshaler is implemented by protobuf messages that customize
112 // the way they are unmarshaled from JSON. Messages that implement this
113 // should also implement JSONPBMarshaler so that the custom format can be
114 // produced.
115 type JSONPBUnmarshaler interface {
116 UnmarshalJSONPB(*Unmarshaler, []byte) error
117 }
118
119 // Marshal marshals a protocol buffer into JSON.
120 func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error {
121 writer := &errWriter{writer: out}
122 return m.marshalObject(writer, pb, "", "")
123 }
124
125 // MarshalToString converts a protocol buffer object to JSON string.
126 func (m *Marshaler) MarshalToString(pb proto.Message) (string, error) {
127 var buf bytes.Buffer
128 if err := m.Marshal(&buf, pb); err != nil {
129 return "", err
130 }
131 return buf.String(), nil
132 }
133
134 type int32Slice []int32
135
136 var nonFinite = map[string]float64{
137 `"NaN"`: math.NaN(),
138 `"Infinity"`: math.Inf(1),
139 `"-Infinity"`: math.Inf(-1),
140 }
141
142 // For sorting extensions ids to ensure stable output.
143 func (s int32Slice) Len() int { return len(s) }
144 func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
145 func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
146
147 type wkt interface {
148 XXX_WellKnownType() string
149 }
150
151 // marshalObject writes a struct to the Writer.
152 func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeURL string) error {
153 if jsm, ok := v.(JSONPBMarshaler); ok {
154 b, err := jsm.MarshalJSONPB(m)
155 if err != nil {
156 return err
157 }
158 if typeURL != "" {
159 // we are marshaling this object to an Any type
160 var js map[string]*json.RawMessage
161 if err = json.Unmarshal(b, &js); err != nil {
162 return fmt.Errorf("type %T produced invalid JSON: %v", v, err)
163 }
164 turl, err := json.Marshal(typeURL)
165 if err != nil {
166 return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err)
167 }
168 js["@type"] = (*json.RawMessage)(&turl)
169 if b, err = json.Marshal(js); err != nil {
170 return err
171 }
172 }
173
174 out.write(string(b))
175 return out.err
176 }
177
178 s := reflect.ValueOf(v).Elem()
179
180 // Handle well-known types.
181 if wkt, ok := v.(wkt); ok {
182 switch wkt.XXX_WellKnownType() {
183 case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value",
184 "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue":
185 // "Wrappers use the same representation in JSON
186 // as the wrapped primitive type, ..."
187 sprop := proto.GetProperties(s.Type())
188 return m.marshalValue(out, sprop.Prop[0], s.Field(0), indent)
189 case "Any":
190 // Any is a bit more involved.
191 return m.marshalAny(out, v, indent)
192 case "Duration":
193 // "Generated output always contains 3, 6, or 9 fractional digits,
194 // depending on required precision."
195 s, ns := s.Field(0).Int(), s.Field(1).Int()
196 x := fmt.Sprintf("%d.%09d", s, ns)
197 x = strings.TrimSuffix(x, "000")
198 x = strings.TrimSuffix(x, "000")
199 out.write(`"`)
200 out.write(x)
201 out.write(`s"`)
202 return out.err
203 case "Struct", "ListValue":
204 // Let marshalValue handle the `Struct.fields` map or the `ListValue.values` slice.
205 // TODO: pass the correct Properties if needed.
206 return m.marshalValue(out, &proto.Properties{}, s.Field(0), indent)
207 case "Timestamp":
208 // "RFC 3339, where generated output will always be Z-normalized
209 // and uses 3, 6 or 9 fractional digits."
210 s, ns := s.Field(0).Int(), s.Field(1).Int()
211 t := time.Unix(s, ns).UTC()
212 // time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits).
213 x := t.Format("2006-01-02T15:04:05.000000000")
214 x = strings.TrimSuffix(x, "000")
215 x = strings.TrimSuffix(x, "000")
216 out.write(`"`)
217 out.write(x)
218 out.write(`Z"`)
219 return out.err
220 case "Value":
221 // Value has a single oneof.
222 kind := s.Field(0)
223 if kind.IsNil() {
224 // "absence of any variant indicates an error"
225 return errors.New("nil Value")
226 }
227 // oneof -> *T -> T -> T.F
228 x := kind.Elem().Elem().Field(0)
229 // TODO: pass the correct Properties if needed.
230 return m.marshalValue(out, &proto.Properties{}, x, indent)
231 }
232 }
233
234 out.write("{")
235 if m.Indent != "" {
236 out.write("\n")
237 }
238
239 firstField := true
240
241 if typeURL != "" {
242 if err := m.marshalTypeURL(out, indent, typeURL); err != nil {
243 return err
244 }
245 firstField = false
246 }
247
248 for i := 0; i < s.NumField(); i++ {
249 value := s.Field(i)
250 valueField := s.Type().Field(i)
251 if strings.HasPrefix(valueField.Name, "XXX_") {
252 continue
253 }
254
255 // IsNil will panic on most value kinds.
256 switch value.Kind() {
257 case reflect.Chan, reflect.Func, reflect.Interface:
258 if value.IsNil() {
259 continue
260 }
261 }
262
263 if !m.EmitDefaults {
264 switch value.Kind() {
265 case reflect.Bool:
266 if !value.Bool() {
267 continue
268 }
269 case reflect.Int32, reflect.Int64:
270 if value.Int() == 0 {
271 continue
272 }
273 case reflect.Uint32, reflect.Uint64:
274 if value.Uint() == 0 {
275 continue
276 }
277 case reflect.Float32, reflect.Float64:
278 if value.Float() == 0 {
279 continue
280 }
281 case reflect.String:
282 if value.Len() == 0 {
283 continue
284 }
285 case reflect.Map, reflect.Ptr, reflect.Slice:
286 if value.IsNil() {
287 continue
288 }
289 }
290 }
291
292 // Oneof fields need special handling.
293 if valueField.Tag.Get("protobuf_oneof") != "" {
294 // value is an interface containing &T{real_value}.
295 sv := value.Elem().Elem() // interface -> *T -> T
296 value = sv.Field(0)
297 valueField = sv.Type().Field(0)
298 }
299 prop := jsonProperties(valueField, m.OrigName)
300 if !firstField {
301 m.writeSep(out)
302 }
303 if err := m.marshalField(out, prop, value, indent); err != nil {
304 return err
305 }
306 firstField = false
307 }
308
309 // Handle proto2 extensions.
310 if ep, ok := v.(proto.Message); ok {
311 extensions := proto.RegisteredExtensions(v)
312 // Sort extensions for stable output.
313 ids := make([]int32, 0, len(extensions))
314 for id, desc := range extensions {
315 if !proto.HasExtension(ep, desc) {
316 continue
317 }
318 ids = append(ids, id)
319 }
320 sort.Sort(int32Slice(ids))
321 for _, id := range ids {
322 desc := extensions[id]
323 if desc == nil {
324 // unknown extension
325 continue
326 }
327 ext, extErr := proto.GetExtension(ep, desc)
328 if extErr != nil {
329 return extErr
330 }
331 value := reflect.ValueOf(ext)
332 var prop proto.Properties
333 prop.Parse(desc.Tag)
334 prop.JSONName = fmt.Sprintf("[%s]", desc.Name)
335 if !firstField {
336 m.writeSep(out)
337 }
338 if err := m.marshalField(out, &prop, value, indent); err != nil {
339 return err
340 }
341 firstField = false
342 }
343
344 }
345
346 if m.Indent != "" {
347 out.write("\n")
348 out.write(indent)
349 }
350 out.write("}")
351 return out.err
352 }
353
354 func (m *Marshaler) writeSep(out *errWriter) {
355 if m.Indent != "" {
356 out.write(",\n")
357 } else {
358 out.write(",")
359 }
360 }
361
362 func (m *Marshaler) marshalAny(out *errWriter, any proto.Message, indent string) error {
363 // "If the Any contains a value that has a special JSON mapping,
364 // it will be converted as follows: {"@type": xxx, "value": yyy}.
365 // Otherwise, the value will be converted into a JSON object,
366 // and the "@type" field will be inserted to indicate the actual data type."
367 v := reflect.ValueOf(any).Elem()
368 turl := v.Field(0).String()
369 val := v.Field(1).Bytes()
370
371 var msg proto.Message
372 var err error
373 if m.AnyResolver != nil {
374 msg, err = m.AnyResolver.Resolve(turl)
375 } else {
376 msg, err = defaultResolveAny(turl)
377 }
378 if err != nil {
379 return err
380 }
381
382 if err := proto.Unmarshal(val, msg); err != nil {
383 return err
384 }
385
386 if _, ok := msg.(wkt); ok {
387 out.write("{")
388 if m.Indent != "" {
389 out.write("\n")
390 }
391 if err := m.marshalTypeURL(out, indent, turl); err != nil {
392 return err
393 }
394 m.writeSep(out)
395 if m.Indent != "" {
396 out.write(indent)
397 out.write(m.Indent)
398 out.write(`"value": `)
399 } else {
400 out.write(`"value":`)
401 }
402 if err := m.marshalObject(out, msg, indent+m.Indent, ""); err != nil {
403 return err
404 }
405 if m.Indent != "" {
406 out.write("\n")
407 out.write(indent)
408 }
409 out.write("}")
410 return out.err
411 }
412
413 return m.marshalObject(out, msg, indent, turl)
414 }
415
416 func (m *Marshaler) marshalTypeURL(out *errWriter, indent, typeURL string) error {
417 if m.Indent != "" {
418 out.write(indent)
419 out.write(m.Indent)
420 }
421 out.write(`"@type":`)
422 if m.Indent != "" {
423 out.write(" ")
424 }
425 b, err := json.Marshal(typeURL)
426 if err != nil {
427 return err
428 }
429 out.write(string(b))
430 return out.err
431 }
432
433 // marshalField writes field description and value to the Writer.
434 func (m *Marshaler) marshalField(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error {
435 if m.Indent != "" {
436 out.write(indent)
437 out.write(m.Indent)
438 }
439 out.write(`"`)
440 out.write(prop.JSONName)
441 out.write(`":`)
442 if m.Indent != "" {
443 out.write(" ")
444 }
445 if err := m.marshalValue(out, prop, v, indent); err != nil {
446 return err
447 }
448 return nil
449 }
450
451 // marshalValue writes the value to the Writer.
452 func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error {
453 var err error
454 v = reflect.Indirect(v)
455
456 // Handle nil pointer
457 if v.Kind() == reflect.Invalid {
458 out.write("null")
459 return out.err
460 }
461
462 // Handle repeated elements.
463 if v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 {
464 out.write("[")
465 comma := ""
466 for i := 0; i < v.Len(); i++ {
467 sliceVal := v.Index(i)
468 out.write(comma)
469 if m.Indent != "" {
470 out.write("\n")
471 out.write(indent)
472 out.write(m.Indent)
473 out.write(m.Indent)
474 }
475 if err := m.marshalValue(out, prop, sliceVal, indent+m.Indent); err != nil {
476 return err
477 }
478 comma = ","
479 }
480 if m.Indent != "" {
481 out.write("\n")
482 out.write(indent)
483 out.write(m.Indent)
484 }
485 out.write("]")
486 return out.err
487 }
488
489 // Handle well-known types.
490 // Most are handled up in marshalObject (because 99% are messages).
491 if wkt, ok := v.Interface().(wkt); ok {
492 switch wkt.XXX_WellKnownType() {
493 case "NullValue":
494 out.write("null")
495 return out.err
496 }
497 }
498
499 // Handle enumerations.
500 if !m.EnumsAsInts && prop.Enum != "" {
501 // Unknown enum values will are stringified by the proto library as their
502 // value. Such values should _not_ be quoted or they will be interpreted
503 // as an enum string instead of their value.
504 enumStr := v.Interface().(fmt.Stringer).String()
505 var valStr string
506 if v.Kind() == reflect.Ptr {
507 valStr = strconv.Itoa(int(v.Elem().Int()))
508 } else {
509 valStr = strconv.Itoa(int(v.Int()))
510 }
511 isKnownEnum := enumStr != valStr
512 if isKnownEnum {
513 out.write(`"`)
514 }
515 out.write(enumStr)
516 if isKnownEnum {
517 out.write(`"`)
518 }
519 return out.err
520 }
521
522 // Handle nested messages.
523 if v.Kind() == reflect.Struct {
524 return m.marshalObject(out, v.Addr().Interface().(proto.Message), indent+m.Indent, "")
525 }
526
527 // Handle maps.
528 // Since Go randomizes map iteration, we sort keys for stable output.
529 if v.Kind() == reflect.Map {
530 out.write(`{`)
531 keys := v.MapKeys()
532 sort.Sort(mapKeys(keys))
533 for i, k := range keys {
534 if i > 0 {
535 out.write(`,`)
536 }
537 if m.Indent != "" {
538 out.write("\n")
539 out.write(indent)
540 out.write(m.Indent)
541 out.write(m.Indent)
542 }
543
544 b, err := json.Marshal(k.Interface())
545 if err != nil {
546 return err
547 }
548 s := string(b)
549
550 // If the JSON is not a string value, encode it again to make it one.
551 if !strings.HasPrefix(s, `"`) {
552 b, err := json.Marshal(s)
553 if err != nil {
554 return err
555 }
556 s = string(b)
557 }
558
559 out.write(s)
560 out.write(`:`)
561 if m.Indent != "" {
562 out.write(` `)
563 }
564
565 if err := m.marshalValue(out, prop, v.MapIndex(k), indent+m.Indent); err != nil {
566 return err
567 }
568 }
569 if m.Indent != "" {
570 out.write("\n")
571 out.write(indent)
572 out.write(m.Indent)
573 }
574 out.write(`}`)
575 return out.err
576 }
577
578 // Handle non-finite floats, e.g. NaN, Infinity and -Infinity.
579 if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
580 f := v.Float()
581 var sval string
582 switch {
583 case math.IsInf(f, 1):
584 sval = `"Infinity"`
585 case math.IsInf(f, -1):
586 sval = `"-Infinity"`
587 case math.IsNaN(f):
588 sval = `"NaN"`
589 }
590 if sval != "" {
591 out.write(sval)
592 return out.err
593 }
594 }
595
596 // Default handling defers to the encoding/json library.
597 b, err := json.Marshal(v.Interface())
598 if err != nil {
599 return err
600 }
601 needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64)
602 if needToQuote {
603 out.write(`"`)
604 }
605 out.write(string(b))
606 if needToQuote {
607 out.write(`"`)
608 }
609 return out.err
610 }
611
612 // Unmarshaler is a configurable object for converting from a JSON
613 // representation to a protocol buffer object.
614 type Unmarshaler struct {
615 // Whether to allow messages to contain unknown fields, as opposed to
616 // failing to unmarshal.
617 AllowUnknownFields bool
618
619 // A custom URL resolver to use when unmarshaling Any messages from JSON.
620 // If unset, the default resolution strategy is to extract the
621 // fully-qualified type name from the type URL and pass that to
622 // proto.MessageType(string).
623 AnyResolver AnyResolver
624 }
625
626 // UnmarshalNext unmarshals the next protocol buffer from a JSON object stream.
627 // This function is lenient and will decode any options permutations of the
628 // related Marshaler.
629 func (u *Unmarshaler) UnmarshalNext(dec *json.Decoder, pb proto.Message) error {
630 inputValue := json.RawMessage{}
631 if err := dec.Decode(&inputValue); err != nil {
632 return err
633 }
634 return u.unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue, nil)
635 }
636
637 // Unmarshal unmarshals a JSON object stream into a protocol
638 // buffer. This function is lenient and will decode any options
639 // permutations of the related Marshaler.
640 func (u *Unmarshaler) Unmarshal(r io.Reader, pb proto.Message) error {
641 dec := json.NewDecoder(r)
642 return u.UnmarshalNext(dec, pb)
643 }
644
645 // UnmarshalNext unmarshals the next protocol buffer from a JSON object stream.
646 // This function is lenient and will decode any options permutations of the
647 // related Marshaler.
648 func UnmarshalNext(dec *json.Decoder, pb proto.Message) error {
649 return new(Unmarshaler).UnmarshalNext(dec, pb)
650 }
651
652 // Unmarshal unmarshals a JSON object stream into a protocol
653 // buffer. This function is lenient and will decode any options
654 // permutations of the related Marshaler.
655 func Unmarshal(r io.Reader, pb proto.Message) error {
656 return new(Unmarshaler).Unmarshal(r, pb)
657 }
658
659 // UnmarshalString will populate the fields of a protocol buffer based
660 // on a JSON string. This function is lenient and will decode any options
661 // permutations of the related Marshaler.
662 func UnmarshalString(str string, pb proto.Message) error {
663 return new(Unmarshaler).Unmarshal(strings.NewReader(str), pb)
664 }
665
666 // unmarshalValue converts/copies a value into the target.
667 // prop may be nil.
668 func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMessage, prop *proto.Properties) error {
669 targetType := target.Type()
670
671 // Allocate memory for pointer fields.
672 if targetType.Kind() == reflect.Ptr {
673 // If input value is "null" and target is a pointer type, then the field should be treated as not set
674 // UNLESS the target is structpb.Value, in which case it should be set to structpb.NullValue.
675 _, isJSONPBUnmarshaler := target.Interface().(JSONPBUnmarshaler)
676 if string(inputValue) == "null" && targetType != reflect.TypeOf(&stpb.Value{}) && !isJSONPBUnmarshaler {
677 return nil
678 }
679 target.Set(reflect.New(targetType.Elem()))
680
681 return u.unmarshalValue(target.Elem(), inputValue, prop)
682 }
683
684 if jsu, ok := target.Addr().Interface().(JSONPBUnmarshaler); ok {
685 return jsu.UnmarshalJSONPB(u, []byte(inputValue))
686 }
687
688 // Handle well-known types that are not pointers.
689 if w, ok := target.Addr().Interface().(wkt); ok {
690 switch w.XXX_WellKnownType() {
691 case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value",
692 "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue":
693 return u.unmarshalValue(target.Field(0), inputValue, prop)
694 case "Any":
695 // Use json.RawMessage pointer type instead of value to support pre-1.8 version.
696 // 1.8 changed RawMessage.MarshalJSON from pointer type to value type, see
697 // https://github.com/golang/go/issues/14493
698 var jsonFields map[string]*json.RawMessage
699 if err := json.Unmarshal(inputValue, &jsonFields); err != nil {
700 return err
701 }
702
703 val, ok := jsonFields["@type"]
704 if !ok || val == nil {
705 return errors.New("Any JSON doesn't have '@type'")
706 }
707
708 var turl string
709 if err := json.Unmarshal([]byte(*val), &turl); err != nil {
710 return fmt.Errorf("can't unmarshal Any's '@type': %q", *val)
711 }
712 target.Field(0).SetString(turl)
713
714 var m proto.Message
715 var err error
716 if u.AnyResolver != nil {
717 m, err = u.AnyResolver.Resolve(turl)
718 } else {
719 m, err = defaultResolveAny(turl)
720 }
721 if err != nil {
722 return err
723 }
724
725 if _, ok := m.(wkt); ok {
726 val, ok := jsonFields["value"]
727 if !ok {
728 return errors.New("Any JSON doesn't have 'value'")
729 }
730
731 if err := u.unmarshalValue(reflect.ValueOf(m).Elem(), *val, nil); err != nil {
732 return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err)
733 }
734 } else {
735 delete(jsonFields, "@type")
736 nestedProto, err := json.Marshal(jsonFields)
737 if err != nil {
738 return fmt.Errorf("can't generate JSON for Any's nested proto to be unmarshaled: %v", err)
739 }
740
741 if err = u.unmarshalValue(reflect.ValueOf(m).Elem(), nestedProto, nil); err != nil {
742 return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err)
743 }
744 }
745
746 b, err := proto.Marshal(m)
747 if err != nil {
748 return fmt.Errorf("can't marshal proto %T into Any.Value: %v", m, err)
749 }
750 target.Field(1).SetBytes(b)
751
752 return nil
753 case "Duration":
754 unq, err := strconv.Unquote(string(inputValue))
755 if err != nil {
756 return err
757 }
758
759 d, err := time.ParseDuration(unq)
760 if err != nil {
761 return fmt.Errorf("bad Duration: %v", err)
762 }
763
764 ns := d.Nanoseconds()
765 s := ns / 1e9
766 ns %= 1e9
767 target.Field(0).SetInt(s)
768 target.Field(1).SetInt(ns)
769 return nil
770 case "Timestamp":
771 unq, err := strconv.Unquote(string(inputValue))
772 if err != nil {
773 return err
774 }
775
776 t, err := time.Parse(time.RFC3339Nano, unq)
777 if err != nil {
778 return fmt.Errorf("bad Timestamp: %v", err)
779 }
780
781 target.Field(0).SetInt(t.Unix())
782 target.Field(1).SetInt(int64(t.Nanosecond()))
783 return nil
784 case "Struct":
785 var m map[string]json.RawMessage
786 if err := json.Unmarshal(inputValue, &m); err != nil {
787 return fmt.Errorf("bad StructValue: %v", err)
788 }
789
790 target.Field(0).Set(reflect.ValueOf(map[string]*stpb.Value{}))
791 for k, jv := range m {
792 pv := &stpb.Value{}
793 if err := u.unmarshalValue(reflect.ValueOf(pv).Elem(), jv, prop); err != nil {
794 return fmt.Errorf("bad value in StructValue for key %q: %v", k, err)
795 }
796 target.Field(0).SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(pv))
797 }
798 return nil
799 case "ListValue":
800 var s []json.RawMessage
801 if err := json.Unmarshal(inputValue, &s); err != nil {
802 return fmt.Errorf("bad ListValue: %v", err)
803 }
804
805 target.Field(0).Set(reflect.ValueOf(make([]*stpb.Value, len(s), len(s))))
806 for i, sv := range s {
807 if err := u.unmarshalValue(target.Field(0).Index(i), sv, prop); err != nil {
808 return err
809 }
810 }
811 return nil
812 case "Value":
813 ivStr := string(inputValue)
814 if ivStr == "null" {
815 target.Field(0).Set(reflect.ValueOf(&stpb.Value_NullValue{}))
816 } else if v, err := strconv.ParseFloat(ivStr, 0); err == nil {
817 target.Field(0).Set(reflect.ValueOf(&stpb.Value_NumberValue{v}))
818 } else if v, err := strconv.Unquote(ivStr); err == nil {
819 target.Field(0).Set(reflect.ValueOf(&stpb.Value_StringValue{v}))
820 } else if v, err := strconv.ParseBool(ivStr); err == nil {
821 target.Field(0).Set(reflect.ValueOf(&stpb.Value_BoolValue{v}))
822 } else if err := json.Unmarshal(inputValue, &[]json.RawMessage{}); err == nil {
823 lv := &stpb.ListValue{}
824 target.Field(0).Set(reflect.ValueOf(&stpb.Value_ListValue{lv}))
825 return u.unmarshalValue(reflect.ValueOf(lv).Elem(), inputValue, prop)
826 } else if err := json.Unmarshal(inputValue, &map[string]json.RawMessage{}); err == nil {
827 sv := &stpb.Struct{}
828 target.Field(0).Set(reflect.ValueOf(&stpb.Value_StructValue{sv}))
829 return u.unmarshalValue(reflect.ValueOf(sv).Elem(), inputValue, prop)
830 } else {
831 return fmt.Errorf("unrecognized type for Value %q", ivStr)
832 }
833 return nil
834 }
835 }
836
837 // Handle enums, which have an underlying type of int32,
838 // and may appear as strings.
839 // The case of an enum appearing as a number is handled
840 // at the bottom of this function.
841 if inputValue[0] == '"' && prop != nil && prop.Enum != "" {
842 vmap := proto.EnumValueMap(prop.Enum)
843 // Don't need to do unquoting; valid enum names
844 // are from a limited character set.
845 s := inputValue[1 : len(inputValue)-1]
846 n, ok := vmap[string(s)]
847 if !ok {
848 return fmt.Errorf("unknown value %q for enum %s", s, prop.Enum)
849 }
850 if target.Kind() == reflect.Ptr { // proto2
851 target.Set(reflect.New(targetType.Elem()))
852 target = target.Elem()
853 }
854 target.SetInt(int64(n))
855 return nil
856 }
857
858 // Handle nested messages.
859 if targetType.Kind() == reflect.Struct {
860 var jsonFields map[string]json.RawMessage
861 if err := json.Unmarshal(inputValue, &jsonFields); err != nil {
862 return err
863 }
864
865 consumeField := func(prop *proto.Properties) (json.RawMessage, bool) {
866 // Be liberal in what names we accept; both orig_name and camelName are okay.
867 fieldNames := acceptedJSONFieldNames(prop)
868
869 vOrig, okOrig := jsonFields[fieldNames.orig]
870 vCamel, okCamel := jsonFields[fieldNames.camel]
871 if !okOrig && !okCamel {
872 return nil, false
873 }
874 // If, for some reason, both are present in the data, favour the camelName.
875 var raw json.RawMessage
876 if okOrig {
877 raw = vOrig
878 delete(jsonFields, fieldNames.orig)
879 }
880 if okCamel {
881 raw = vCamel
882 delete(jsonFields, fieldNames.camel)
883 }
884 return raw, true
885 }
886
887 sprops := proto.GetProperties(targetType)
888 for i := 0; i < target.NumField(); i++ {
889 ft := target.Type().Field(i)
890 if strings.HasPrefix(ft.Name, "XXX_") {
891 continue
892 }
893
894 valueForField, ok := consumeField(sprops.Prop[i])
895 if !ok {
896 continue
897 }
898
899 if err := u.unmarshalValue(target.Field(i), valueForField, sprops.Prop[i]); err != nil {
900 return err
901 }
902 }
903 // Check for any oneof fields.
904 if len(jsonFields) > 0 {
905 for _, oop := range sprops.OneofTypes {
906 raw, ok := consumeField(oop.Prop)
907 if !ok {
908 continue
909 }
910 nv := reflect.New(oop.Type.Elem())
911 target.Field(oop.Field).Set(nv)
912 if err := u.unmarshalValue(nv.Elem().Field(0), raw, oop.Prop); err != nil {
913 return err
914 }
915 }
916 }
917 // Handle proto2 extensions.
918 if len(jsonFields) > 0 {
919 if ep, ok := target.Addr().Interface().(proto.Message); ok {
920 for _, ext := range proto.RegisteredExtensions(ep) {
921 name := fmt.Sprintf("[%s]", ext.Name)
922 raw, ok := jsonFields[name]
923 if !ok {
924 continue
925 }
926 delete(jsonFields, name)
927 nv := reflect.New(reflect.TypeOf(ext.ExtensionType).Elem())
928 if err := u.unmarshalValue(nv.Elem(), raw, nil); err != nil {
929 return err
930 }
931 if err := proto.SetExtension(ep, ext, nv.Interface()); err != nil {
932 return err
933 }
934 }
935 }
936 }
937 if !u.AllowUnknownFields && len(jsonFields) > 0 {
938 // Pick any field to be the scapegoat.
939 var f string
940 for fname := range jsonFields {
941 f = fname
942 break
943 }
944 return fmt.Errorf("unknown field %q in %v", f, targetType)
945 }
946 return nil
947 }
948
949 // Handle arrays (which aren't encoded bytes)
950 if targetType.Kind() == reflect.Slice && targetType.Elem().Kind() != reflect.Uint8 {
951 var slc []json.RawMessage
952 if err := json.Unmarshal(inputValue, &slc); err != nil {
953 return err
954 }
955 if slc != nil {
956 l := len(slc)
957 target.Set(reflect.MakeSlice(targetType, l, l))
958 for i := 0; i < l; i++ {
959 if err := u.unmarshalValue(target.Index(i), slc[i], prop); err != nil {
960 return err
961 }
962 }
963 }
964 return nil
965 }
966
967 // Handle maps (whose keys are always strings)
968 if targetType.Kind() == reflect.Map {
969 var mp map[string]json.RawMessage
970 if err := json.Unmarshal(inputValue, &mp); err != nil {
971 return err
972 }
973 if mp != nil {
974 target.Set(reflect.MakeMap(targetType))
975 var keyprop, valprop *proto.Properties
976 if prop != nil {
977 // These could still be nil if the protobuf metadata is broken somehow.
978 // TODO: This won't work because the fields are unexported.
979 // We should probably just reparse them.
980 //keyprop, valprop = prop.mkeyprop, prop.mvalprop
981 }
982 for ks, raw := range mp {
983 // Unmarshal map key. The core json library already decoded the key into a
984 // string, so we handle that specially. Other types were quoted post-serialization.
985 var k reflect.Value
986 if targetType.Key().Kind() == reflect.String {
987 k = reflect.ValueOf(ks)
988 } else {
989 k = reflect.New(targetType.Key()).Elem()
990 if err := u.unmarshalValue(k, json.RawMessage(ks), keyprop); err != nil {
991 return err
992 }
993 }
994
995 // Unmarshal map value.
996 v := reflect.New(targetType.Elem()).Elem()
997 if err := u.unmarshalValue(v, raw, valprop); err != nil {
998 return err
999 }
1000 target.SetMapIndex(k, v)
1001 }
1002 }
1003 return nil
1004 }
1005
1006 // 64-bit integers can be encoded as strings. In this case we drop
1007 // the quotes and proceed as normal.
1008 isNum := targetType.Kind() == reflect.Int64 || targetType.Kind() == reflect.Uint64
1009 if isNum && strings.HasPrefix(string(inputValue), `"`) {
1010 inputValue = inputValue[1 : len(inputValue)-1]
1011 }
1012
1013 // Non-finite numbers can be encoded as strings.
1014 isFloat := targetType.Kind() == reflect.Float32 || targetType.Kind() == reflect.Float64
1015 if isFloat {
1016 if num, ok := nonFinite[string(inputValue)]; ok {
1017 target.SetFloat(num)
1018 return nil
1019 }
1020 }
1021
1022 // Use the encoding/json for parsing other value types.
1023 return json.Unmarshal(inputValue, target.Addr().Interface())
1024 }
1025
1026 // jsonProperties returns parsed proto.Properties for the field and corrects JSONName attribute.
1027 func jsonProperties(f reflect.StructField, origName bool) *proto.Properties {
1028 var prop proto.Properties
1029 prop.Init(f.Type, f.Name, f.Tag.Get("protobuf"), &f)
1030 if origName || prop.JSONName == "" {
1031 prop.JSONName = prop.OrigName
1032 }
1033 return &prop
1034 }
1035
1036 type fieldNames struct {
1037 orig, camel string
1038 }
1039
1040 func acceptedJSONFieldNames(prop *proto.Properties) fieldNames {
1041 opts := fieldNames{orig: prop.OrigName, camel: prop.OrigName}
1042 if prop.JSONName != "" {
1043 opts.camel = prop.JSONName
1044 }
1045 return opts
1046 }
1047
1048 // Writer wrapper inspired by https://blog.golang.org/errors-are-values
1049 type errWriter struct {
1050 writer io.Writer
1051 err error
1052 }
1053
1054 func (w *errWriter) write(str string) {
1055 if w.err != nil {
1056 return
1057 }
1058 _, w.err = w.writer.Write([]byte(str))
1059 }
1060
1061 // Map fields may have key types of non-float scalars, strings and enums.
1062 // The easiest way to sort them in some deterministic order is to use fmt.
1063 // If this turns out to be inefficient we can always consider other options,
1064 // such as doing a Schwartzian transform.
1065 //
1066 // Numeric keys are sorted in numeric order per
1067 // https://developers.google.com/protocol-buffers/docs/proto#maps.
1068 type mapKeys []reflect.Value
1069
1070 func (s mapKeys) Len() int { return len(s) }
1071 func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
1072 func (s mapKeys) Less(i, j int) bool {
1073 if k := s[i].Kind(); k == s[j].Kind() {
1074 switch k {
1075 case reflect.Int32, reflect.Int64:
1076 return s[i].Int() < s[j].Int()
1077 case reflect.Uint32, reflect.Uint64:
1078 return s[i].Uint() < s[j].Uint()
1079 }
1080 }
1081 return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface())
1082 }