jsonpb.go 36 KB

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