jsonpb.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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. "fmt"
  42. "io"
  43. "reflect"
  44. "sort"
  45. "strconv"
  46. "strings"
  47. "github.com/gogo/protobuf/proto"
  48. )
  49. // Marshaler is a configurable object for converting between
  50. // protocol buffer objects and a JSON representation for them.
  51. type Marshaler struct {
  52. // Whether to render enum values as integers, as opposed to string values.
  53. EnumsAsInts bool
  54. // Whether to render fields with zero values.
  55. EmitDefaults bool
  56. // A string to indent each level by. The presence of this field will
  57. // also cause a space to appear between the field separator and
  58. // value, and for newlines to be appear between fields and array
  59. // elements.
  60. Indent string
  61. // Whether to use the original (.proto) name for fields.
  62. OrigName bool
  63. }
  64. // Marshal marshals a protocol buffer into JSON.
  65. func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error {
  66. writer := &errWriter{writer: out}
  67. return m.marshalObject(writer, pb, "")
  68. }
  69. // MarshalToString converts a protocol buffer object to JSON string.
  70. func (m *Marshaler) MarshalToString(pb proto.Message) (string, error) {
  71. var buf bytes.Buffer
  72. if err := m.Marshal(&buf, pb); err != nil {
  73. return "", err
  74. }
  75. return buf.String(), nil
  76. }
  77. type int32Slice []int32
  78. // For sorting extensions ids to ensure stable output.
  79. func (s int32Slice) Len() int { return len(s) }
  80. func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
  81. func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  82. // marshalObject writes a struct to the Writer.
  83. func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent string) error {
  84. out.write("{")
  85. if m.Indent != "" {
  86. out.write("\n")
  87. }
  88. s := reflect.ValueOf(v).Elem()
  89. firstField := true
  90. for i := 0; i < s.NumField(); i++ {
  91. value := s.Field(i)
  92. valueField := s.Type().Field(i)
  93. if strings.HasPrefix(valueField.Name, "XXX_") {
  94. continue
  95. }
  96. // IsNil will panic on most value kinds.
  97. switch value.Kind() {
  98. case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
  99. if value.IsNil() {
  100. continue
  101. }
  102. }
  103. if !m.EmitDefaults {
  104. switch value.Kind() {
  105. case reflect.Bool:
  106. if !value.Bool() {
  107. continue
  108. }
  109. case reflect.Int32, reflect.Int64:
  110. if value.Int() == 0 {
  111. continue
  112. }
  113. case reflect.Uint32, reflect.Uint64:
  114. if value.Uint() == 0 {
  115. continue
  116. }
  117. case reflect.Float32, reflect.Float64:
  118. if value.Float() == 0 {
  119. continue
  120. }
  121. case reflect.String:
  122. if value.Len() == 0 {
  123. continue
  124. }
  125. }
  126. }
  127. // Oneof fields need special handling.
  128. if valueField.Tag.Get("protobuf_oneof") != "" {
  129. // value is an interface containing &T{real_value}.
  130. sv := value.Elem().Elem() // interface -> *T -> T
  131. value = sv.Field(0)
  132. valueField = sv.Type().Field(0)
  133. }
  134. prop := jsonProperties(valueField, m.OrigName)
  135. if !firstField {
  136. m.writeSep(out)
  137. }
  138. // If the map value is a cast type, it may not implement proto.Message, therefore
  139. // allow the struct tag to declare the underlying message type. Instead of changing
  140. // the signatures of the child types (and because prop.mvalue is not public), use
  141. // CustomType as a passer.
  142. if value.Kind() == reflect.Map {
  143. if tag := valueField.Tag.Get("protobuf"); tag != "" {
  144. for _, v := range strings.Split(tag, ",") {
  145. if !strings.HasPrefix(v, "castvaluetype=") {
  146. continue
  147. }
  148. v = strings.TrimPrefix(v, "castvaluetype=")
  149. prop.CustomType = v
  150. break
  151. }
  152. }
  153. }
  154. if err := m.marshalField(out, prop, value, indent); err != nil {
  155. return err
  156. }
  157. firstField = false
  158. }
  159. // Handle proto2 extensions.
  160. if ep, ok := v.(proto.Message); ok {
  161. extensions := proto.RegisteredExtensions(v)
  162. // Sort extensions for stable output.
  163. ids := make([]int32, 0, len(extensions))
  164. for id, desc := range extensions {
  165. if !proto.HasExtension(ep, desc) {
  166. continue
  167. }
  168. ids = append(ids, id)
  169. }
  170. sort.Sort(int32Slice(ids))
  171. for _, id := range ids {
  172. desc := extensions[id]
  173. if desc == nil {
  174. // unknown extension
  175. continue
  176. }
  177. ext, extErr := proto.GetExtension(ep, desc)
  178. if extErr != nil {
  179. return extErr
  180. }
  181. value := reflect.ValueOf(ext)
  182. var prop proto.Properties
  183. prop.Parse(desc.Tag)
  184. prop.JSONName = fmt.Sprintf("[%s]", desc.Name)
  185. if !firstField {
  186. m.writeSep(out)
  187. }
  188. if err := m.marshalField(out, &prop, value, indent); err != nil {
  189. return err
  190. }
  191. firstField = false
  192. }
  193. }
  194. if m.Indent != "" {
  195. out.write("\n")
  196. out.write(indent)
  197. }
  198. out.write("}")
  199. return out.err
  200. }
  201. func (m *Marshaler) writeSep(out *errWriter) {
  202. if m.Indent != "" {
  203. out.write(",\n")
  204. } else {
  205. out.write(",")
  206. }
  207. }
  208. // marshalField writes field description and value to the Writer.
  209. func (m *Marshaler) marshalField(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error {
  210. if m.Indent != "" {
  211. out.write(indent)
  212. out.write(m.Indent)
  213. }
  214. out.write(`"`)
  215. out.write(prop.JSONName)
  216. out.write(`":`)
  217. if m.Indent != "" {
  218. out.write(" ")
  219. }
  220. if err := m.marshalValue(out, prop, v, indent); err != nil {
  221. return err
  222. }
  223. return nil
  224. }
  225. // marshalValue writes the value to the Writer.
  226. func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error {
  227. v = reflect.Indirect(v)
  228. // Handle repeated elements.
  229. if v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 {
  230. out.write("[")
  231. comma := ""
  232. for i := 0; i < v.Len(); i++ {
  233. sliceVal := v.Index(i)
  234. out.write(comma)
  235. if m.Indent != "" {
  236. out.write("\n")
  237. out.write(indent)
  238. out.write(m.Indent)
  239. out.write(m.Indent)
  240. }
  241. if err := m.marshalValue(out, prop, sliceVal, indent+m.Indent); err != nil {
  242. return err
  243. }
  244. comma = ","
  245. }
  246. if m.Indent != "" {
  247. out.write("\n")
  248. out.write(indent)
  249. out.write(m.Indent)
  250. }
  251. out.write("]")
  252. return out.err
  253. }
  254. // Handle enumerations.
  255. if !m.EnumsAsInts && prop.Enum != "" {
  256. // Unknown enum values will are stringified by the proto library as their
  257. // value. Such values should _not_ be quoted or they will be interpreted
  258. // as an enum string instead of their value.
  259. enumStr := v.Interface().(fmt.Stringer).String()
  260. var valStr string
  261. if v.Kind() == reflect.Ptr {
  262. valStr = strconv.Itoa(int(v.Elem().Int()))
  263. } else {
  264. valStr = strconv.Itoa(int(v.Int()))
  265. }
  266. if m, ok := v.Interface().(interface {
  267. MarshalJSON() ([]byte, error)
  268. }); ok {
  269. data, err := m.MarshalJSON()
  270. if err != nil {
  271. return err
  272. }
  273. enumStr = string(data)
  274. enumStr, err = strconv.Unquote(enumStr)
  275. if err != nil {
  276. return err
  277. }
  278. }
  279. isKnownEnum := enumStr != valStr
  280. if isKnownEnum {
  281. out.write(`"`)
  282. }
  283. out.write(enumStr)
  284. if isKnownEnum {
  285. out.write(`"`)
  286. }
  287. return out.err
  288. }
  289. // Handle nested messages.
  290. if v.Kind() == reflect.Struct {
  291. i := v
  292. if v.CanAddr() {
  293. i = v.Addr()
  294. } else {
  295. i = reflect.New(v.Type())
  296. i.Elem().Set(v)
  297. }
  298. iface := i.Interface()
  299. if iface == nil {
  300. out.write(`null`)
  301. return out.err
  302. }
  303. pm, ok := iface.(proto.Message)
  304. if !ok {
  305. if prop.CustomType == "" {
  306. return fmt.Errorf("%v does not implement proto.Message", v.Type())
  307. }
  308. t := proto.MessageType(prop.CustomType)
  309. if t == nil || !i.Type().ConvertibleTo(t) {
  310. return fmt.Errorf("%v declared custom type %s but it is not convertible to %v", v.Type(), prop.CustomType, t)
  311. }
  312. pm = i.Convert(t).Interface().(proto.Message)
  313. }
  314. return m.marshalObject(out, pm, indent+m.Indent)
  315. }
  316. // Handle maps.
  317. // Since Go randomizes map iteration, we sort keys for stable output.
  318. if v.Kind() == reflect.Map {
  319. out.write(`{`)
  320. keys := v.MapKeys()
  321. sort.Sort(mapKeys(keys))
  322. for i, k := range keys {
  323. if i > 0 {
  324. out.write(`,`)
  325. }
  326. if m.Indent != "" {
  327. out.write("\n")
  328. out.write(indent)
  329. out.write(m.Indent)
  330. out.write(m.Indent)
  331. }
  332. b, err := json.Marshal(k.Interface())
  333. if err != nil {
  334. return err
  335. }
  336. s := string(b)
  337. // If the JSON is not a string value, encode it again to make it one.
  338. if !strings.HasPrefix(s, `"`) {
  339. b, err := json.Marshal(s)
  340. if err != nil {
  341. return err
  342. }
  343. s = string(b)
  344. }
  345. out.write(s)
  346. out.write(`:`)
  347. if m.Indent != "" {
  348. out.write(` `)
  349. }
  350. if err := m.marshalValue(out, prop, v.MapIndex(k), indent+m.Indent); err != nil {
  351. return err
  352. }
  353. }
  354. if m.Indent != "" {
  355. out.write("\n")
  356. out.write(indent)
  357. out.write(m.Indent)
  358. }
  359. out.write(`}`)
  360. return out.err
  361. }
  362. // Default handling defers to the encoding/json library.
  363. b, err := json.Marshal(v.Interface())
  364. if err != nil {
  365. return err
  366. }
  367. needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64)
  368. if needToQuote {
  369. out.write(`"`)
  370. }
  371. out.write(string(b))
  372. if needToQuote {
  373. out.write(`"`)
  374. }
  375. return out.err
  376. }
  377. // Unmarshaler is a configurable object for converting from a JSON
  378. // representation to a protocol buffer object.
  379. type Unmarshaler struct {
  380. // Whether to allow messages to contain unknown fields, as opposed to
  381. // failing to unmarshal.
  382. AllowUnknownFields bool
  383. }
  384. // UnmarshalNext unmarshals the next protocol buffer from a JSON object stream.
  385. // This function is lenient and will decode any options permutations of the
  386. // related Marshaler.
  387. func (u *Unmarshaler) UnmarshalNext(dec *json.Decoder, pb proto.Message) error {
  388. inputValue := json.RawMessage{}
  389. if err := dec.Decode(&inputValue); err != nil {
  390. return err
  391. }
  392. return u.unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue, nil)
  393. }
  394. // Unmarshal unmarshals a JSON object stream into a protocol
  395. // buffer. This function is lenient and will decode any options
  396. // permutations of the related Marshaler.
  397. func (u *Unmarshaler) Unmarshal(r io.Reader, pb proto.Message) error {
  398. dec := json.NewDecoder(r)
  399. return u.UnmarshalNext(dec, pb)
  400. }
  401. // UnmarshalNext unmarshals the next protocol buffer from a JSON object stream.
  402. // This function is lenient and will decode any options permutations of the
  403. // related Marshaler.
  404. func UnmarshalNext(dec *json.Decoder, pb proto.Message) error {
  405. return new(Unmarshaler).UnmarshalNext(dec, pb)
  406. }
  407. // Unmarshal unmarshals a JSON object stream into a protocol
  408. // buffer. This function is lenient and will decode any options
  409. // permutations of the related Marshaler.
  410. func Unmarshal(r io.Reader, pb proto.Message) error {
  411. return new(Unmarshaler).Unmarshal(r, pb)
  412. }
  413. // UnmarshalString will populate the fields of a protocol buffer based
  414. // on a JSON string. This function is lenient and will decode any options
  415. // permutations of the related Marshaler.
  416. func UnmarshalString(str string, pb proto.Message) error {
  417. return new(Unmarshaler).Unmarshal(strings.NewReader(str), pb)
  418. }
  419. // unmarshalValue converts/copies a value into the target.
  420. // prop may be nil.
  421. func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMessage, prop *proto.Properties) error {
  422. targetType := target.Type()
  423. // Allocate memory for pointer fields.
  424. if targetType.Kind() == reflect.Ptr {
  425. target.Set(reflect.New(targetType.Elem()))
  426. return u.unmarshalValue(target.Elem(), inputValue, prop)
  427. }
  428. // Handle enums, which have an underlying type of int32,
  429. // and may appear as strings.
  430. // The case of an enum appearing as a number is handled
  431. // at the bottom of this function.
  432. if inputValue[0] == '"' && prop != nil && prop.Enum != "" {
  433. vmap := proto.EnumValueMap(prop.Enum)
  434. // Don't need to do unquoting; valid enum names
  435. // are from a limited character set.
  436. s := inputValue[1 : len(inputValue)-1]
  437. n, ok := vmap[string(s)]
  438. if !ok {
  439. return fmt.Errorf("unknown value %q for enum %s", s, prop.Enum)
  440. }
  441. if target.Kind() == reflect.Ptr { // proto2
  442. target.Set(reflect.New(targetType.Elem()))
  443. target = target.Elem()
  444. }
  445. target.SetInt(int64(n))
  446. return nil
  447. }
  448. // Handle nested messages.
  449. if targetType.Kind() == reflect.Struct {
  450. var jsonFields map[string]json.RawMessage
  451. if err := json.Unmarshal(inputValue, &jsonFields); err != nil {
  452. return err
  453. }
  454. consumeField := func(prop *proto.Properties) (json.RawMessage, bool) {
  455. // Be liberal in what names we accept; both orig_name and camelName are okay.
  456. fieldNames := acceptedJSONFieldNames(prop)
  457. vOrig, okOrig := jsonFields[fieldNames.orig]
  458. vCamel, okCamel := jsonFields[fieldNames.camel]
  459. if !okOrig && !okCamel {
  460. return nil, false
  461. }
  462. // If, for some reason, both are present in the data, favour the camelName.
  463. var raw json.RawMessage
  464. if okOrig {
  465. raw = vOrig
  466. delete(jsonFields, fieldNames.orig)
  467. }
  468. if okCamel {
  469. raw = vCamel
  470. delete(jsonFields, fieldNames.camel)
  471. }
  472. return raw, true
  473. }
  474. sprops := proto.GetProperties(targetType)
  475. for i := 0; i < target.NumField(); i++ {
  476. ft := target.Type().Field(i)
  477. if strings.HasPrefix(ft.Name, "XXX_") {
  478. continue
  479. }
  480. valueForField, ok := consumeField(sprops.Prop[i])
  481. if !ok {
  482. continue
  483. }
  484. if err := u.unmarshalValue(target.Field(i), valueForField, sprops.Prop[i]); err != nil {
  485. return err
  486. }
  487. }
  488. // Check for any oneof fields.
  489. if len(jsonFields) > 0 {
  490. for _, oop := range sprops.OneofTypes {
  491. raw, ok := consumeField(oop.Prop)
  492. if !ok {
  493. continue
  494. }
  495. nv := reflect.New(oop.Type.Elem())
  496. target.Field(oop.Field).Set(nv)
  497. if err := u.unmarshalValue(nv.Elem().Field(0), raw, oop.Prop); err != nil {
  498. return err
  499. }
  500. }
  501. }
  502. if !u.AllowUnknownFields && len(jsonFields) > 0 {
  503. // Pick any field to be the scapegoat.
  504. var f string
  505. for fname := range jsonFields {
  506. f = fname
  507. break
  508. }
  509. return fmt.Errorf("unknown field %q in %v", f, targetType)
  510. }
  511. return nil
  512. }
  513. // Handle arrays
  514. if targetType.Kind() == reflect.Slice {
  515. if targetType.Elem().Kind() == reflect.Uint8 {
  516. outRef := reflect.New(targetType)
  517. outVal := outRef.Interface()
  518. //CustomType with underlying type []byte
  519. if _, ok := outVal.(interface {
  520. UnmarshalJSON([]byte) error
  521. }); ok {
  522. if err := json.Unmarshal(inputValue, outVal); err != nil {
  523. return err
  524. }
  525. target.Set(outRef.Elem())
  526. return nil
  527. }
  528. // Special case for encoded bytes. Pre-go1.5 doesn't support unmarshalling
  529. // strings into aliased []byte types.
  530. // https://github.com/golang/go/commit/4302fd0409da5e4f1d71471a6770dacdc3301197
  531. // https://github.com/golang/go/commit/c60707b14d6be26bf4213114d13070bff00d0b0a
  532. var out []byte
  533. if err := json.Unmarshal(inputValue, &out); err != nil {
  534. return err
  535. }
  536. target.SetBytes(out)
  537. return nil
  538. }
  539. var slc []json.RawMessage
  540. if err := json.Unmarshal(inputValue, &slc); err != nil {
  541. return err
  542. }
  543. len := len(slc)
  544. target.Set(reflect.MakeSlice(targetType, len, len))
  545. for i := 0; i < len; i++ {
  546. if err := u.unmarshalValue(target.Index(i), slc[i], prop); err != nil {
  547. return err
  548. }
  549. }
  550. return nil
  551. }
  552. // Handle maps (whose keys are always strings)
  553. if targetType.Kind() == reflect.Map {
  554. var mp map[string]json.RawMessage
  555. if err := json.Unmarshal(inputValue, &mp); err != nil {
  556. return err
  557. }
  558. target.Set(reflect.MakeMap(targetType))
  559. var keyprop, valprop *proto.Properties
  560. if prop != nil {
  561. // These could still be nil if the protobuf metadata is broken somehow.
  562. // TODO: This won't work because the fields are unexported.
  563. // We should probably just reparse them.
  564. //keyprop, valprop = prop.mkeyprop, prop.mvalprop
  565. }
  566. for ks, raw := range mp {
  567. // Unmarshal map key. The core json library already decoded the key into a
  568. // string, so we handle that specially. Other types were quoted post-serialization.
  569. var k reflect.Value
  570. if targetType.Key().Kind() == reflect.String {
  571. k = reflect.ValueOf(ks)
  572. } else {
  573. k = reflect.New(targetType.Key()).Elem()
  574. if err := u.unmarshalValue(k, json.RawMessage(ks), keyprop); err != nil {
  575. return err
  576. }
  577. }
  578. if !k.Type().AssignableTo(targetType.Key()) {
  579. k = k.Convert(targetType.Key())
  580. }
  581. // Unmarshal map value.
  582. v := reflect.New(targetType.Elem()).Elem()
  583. if err := u.unmarshalValue(v, raw, valprop); err != nil {
  584. return err
  585. }
  586. target.SetMapIndex(k, v)
  587. }
  588. return nil
  589. }
  590. // 64-bit integers can be encoded as strings. In this case we drop
  591. // the quotes and proceed as normal.
  592. isNum := targetType.Kind() == reflect.Int64 || targetType.Kind() == reflect.Uint64
  593. if isNum && strings.HasPrefix(string(inputValue), `"`) {
  594. inputValue = inputValue[1 : len(inputValue)-1]
  595. }
  596. // Use the encoding/json for parsing other value types.
  597. return json.Unmarshal(inputValue, target.Addr().Interface())
  598. }
  599. // jsonProperties returns parsed proto.Properties for the field and corrects JSONName attribute.
  600. func jsonProperties(f reflect.StructField, origName bool) *proto.Properties {
  601. var prop proto.Properties
  602. prop.Init(f.Type, f.Name, f.Tag.Get("protobuf"), &f)
  603. if origName || prop.JSONName == "" {
  604. prop.JSONName = prop.OrigName
  605. }
  606. return &prop
  607. }
  608. type fieldNames struct {
  609. orig, camel string
  610. }
  611. func acceptedJSONFieldNames(prop *proto.Properties) fieldNames {
  612. opts := fieldNames{orig: prop.OrigName, camel: prop.OrigName}
  613. if prop.JSONName != "" {
  614. opts.camel = prop.JSONName
  615. }
  616. return opts
  617. }
  618. // Writer wrapper inspired by https://blog.golang.org/errors-are-values
  619. type errWriter struct {
  620. writer io.Writer
  621. err error
  622. }
  623. func (w *errWriter) write(str string) {
  624. if w.err != nil {
  625. return
  626. }
  627. _, w.err = w.writer.Write([]byte(str))
  628. }
  629. // Map fields may have key types of non-float scalars, strings and enums.
  630. // The easiest way to sort them in some deterministic order is to use fmt.
  631. // If this turns out to be inefficient we can always consider other options,
  632. // such as doing a Schwartzian transform.
  633. //
  634. // Numeric keys are sorted in numeric order per
  635. // https://developers.google.com/protocol-buffers/docs/proto#maps.
  636. type mapKeys []reflect.Value
  637. func (s mapKeys) Len() int { return len(s) }
  638. func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  639. func (s mapKeys) Less(i, j int) bool {
  640. if k := s[i].Kind(); k == s[j].Kind() {
  641. switch k {
  642. case reflect.Int32, reflect.Int64:
  643. return s[i].Int() < s[j].Int()
  644. case reflect.Uint32, reflect.Uint64:
  645. return s[i].Uint() < s[j].Uint()
  646. }
  647. }
  648. return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface())
  649. }