jsonpb.go 36 KB

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