protobuf_enc.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2015-2018 The NATS Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package protobuf
  14. import (
  15. "errors"
  16. "github.com/golang/protobuf/proto"
  17. "github.com/nats-io/go-nats"
  18. )
  19. // Additional index for registered Encoders.
  20. const (
  21. PROTOBUF_ENCODER = "protobuf"
  22. )
  23. func init() {
  24. // Register protobuf encoder
  25. nats.RegisterEncoder(PROTOBUF_ENCODER, &ProtobufEncoder{})
  26. }
  27. // ProtobufEncoder is a protobuf implementation for EncodedConn
  28. // This encoder will use the builtin protobuf lib to Marshal
  29. // and Unmarshal structs.
  30. type ProtobufEncoder struct {
  31. // Empty
  32. }
  33. var (
  34. ErrInvalidProtoMsgEncode = errors.New("nats: Invalid protobuf proto.Message object passed to encode")
  35. ErrInvalidProtoMsgDecode = errors.New("nats: Invalid protobuf proto.Message object passed to decode")
  36. )
  37. // Encode
  38. func (pb *ProtobufEncoder) Encode(subject string, v interface{}) ([]byte, error) {
  39. if v == nil {
  40. return nil, nil
  41. }
  42. i, found := v.(proto.Message)
  43. if !found {
  44. return nil, ErrInvalidProtoMsgEncode
  45. }
  46. b, err := proto.Marshal(i)
  47. if err != nil {
  48. return nil, err
  49. }
  50. return b, nil
  51. }
  52. // Decode
  53. func (pb *ProtobufEncoder) Decode(subject string, data []byte, vPtr interface{}) error {
  54. if _, ok := vPtr.(*interface{}); ok {
  55. return nil
  56. }
  57. i, found := vPtr.(proto.Message)
  58. if !found {
  59. return ErrInvalidProtoMsgDecode
  60. }
  61. return proto.Unmarshal(data, i)
  62. }