json.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package codec
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "github.com/gogo/protobuf/jsonpb"
  6. "github.com/gogo/protobuf/proto"
  7. "google.golang.org/grpc/encoding"
  8. )
  9. //Reference https://jbrandhorst.com/post/grpc-json/
  10. func init() {
  11. encoding.RegisterCodec(JSON{
  12. Marshaler: jsonpb.Marshaler{
  13. EmitDefaults: true,
  14. OrigName: true,
  15. },
  16. })
  17. }
  18. // JSON is impl of encoding.Codec
  19. type JSON struct {
  20. jsonpb.Marshaler
  21. jsonpb.Unmarshaler
  22. }
  23. // Name is name of JSON
  24. func (j JSON) Name() string {
  25. return "json"
  26. }
  27. // Marshal is json marshal
  28. func (j JSON) Marshal(v interface{}) (out []byte, err error) {
  29. if pm, ok := v.(proto.Message); ok {
  30. b := new(bytes.Buffer)
  31. err := j.Marshaler.Marshal(b, pm)
  32. if err != nil {
  33. return nil, err
  34. }
  35. return b.Bytes(), nil
  36. }
  37. return json.Marshal(v)
  38. }
  39. // Unmarshal is json unmarshal
  40. func (j JSON) Unmarshal(data []byte, v interface{}) (err error) {
  41. if pm, ok := v.(proto.Message); ok {
  42. b := bytes.NewBuffer(data)
  43. return j.Unmarshaler.Unmarshal(b, pm)
  44. }
  45. return json.Unmarshal(data, v)
  46. }