proto.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. *
  3. * Copyright 2018 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Package proto defines the protobuf codec. Importing this package will
  19. // register the codec.
  20. package proto
  21. import (
  22. "fmt"
  23. "google.golang.org/grpc/encoding"
  24. "google.golang.org/protobuf/proto"
  25. "google.golang.org/protobuf/protoadapt"
  26. )
  27. // Name is the name registered for the proto compressor.
  28. const Name = "proto"
  29. func init() {
  30. encoding.RegisterCodec(codec{})
  31. }
  32. // codec is a Codec implementation with protobuf. It is the default codec for gRPC.
  33. type codec struct{}
  34. func (codec) Marshal(v any) ([]byte, error) {
  35. vv := messageV2Of(v)
  36. if vv == nil {
  37. return nil, fmt.Errorf("failed to marshal, message is %T, want proto.Message", v)
  38. }
  39. return proto.Marshal(vv)
  40. }
  41. func (codec) Unmarshal(data []byte, v any) error {
  42. vv := messageV2Of(v)
  43. if vv == nil {
  44. return fmt.Errorf("failed to unmarshal, message is %T, want proto.Message", v)
  45. }
  46. return proto.Unmarshal(data, vv)
  47. }
  48. func messageV2Of(v any) proto.Message {
  49. switch v := v.(type) {
  50. case protoadapt.MessageV1:
  51. return protoadapt.MessageV2Of(v)
  52. case protoadapt.MessageV2:
  53. return v
  54. }
  55. return nil
  56. }
  57. func (codec) Name() string {
  58. return Name
  59. }