jsonpb.go 36 KB

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