jsonpb.go 35 KB

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