any.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. // Go support for Protocol Buffers - Google's data interchange format
  2. //
  3. // Copyright 2016 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. package ptypes
  32. // This file implements functions to marshal proto.Message to/from
  33. // google.protobuf.Any message.
  34. import (
  35. "fmt"
  36. "reflect"
  37. "strings"
  38. "github.com/golang/protobuf/proto"
  39. "github.com/golang/protobuf/ptypes/any"
  40. )
  41. const googleApis = "type.googleapis.com/"
  42. // AnyMessageName returns the name of the message contained in a google.protobuf.Any message.
  43. //
  44. // Note that regular type assertions should be done using the Is
  45. // function. AnyMessageName is provided for less common use cases like filtering a
  46. // sequence of Any messages based on a set of allowed message type names.
  47. func AnyMessageName(any *any.Any) (string, error) {
  48. if any == nil {
  49. return "", fmt.Errorf("message is nil")
  50. }
  51. slash := strings.LastIndex(any.TypeUrl, "/")
  52. if slash < 0 {
  53. return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl)
  54. }
  55. return any.TypeUrl[slash+1:], nil
  56. }
  57. // MarshalAny takes the protocol buffer and encodes it into google.protobuf.Any.
  58. func MarshalAny(pb proto.Message) (*any.Any, error) {
  59. value, err := proto.Marshal(pb)
  60. if err != nil {
  61. return nil, err
  62. }
  63. return &any.Any{TypeUrl: googleApis + proto.MessageName(pb), Value: value}, nil
  64. }
  65. // DynamicAny is a value that can be passed to UnmarshalAny to automatically
  66. // allocate a proto.Message for the type specified in a google.protobuf.Any
  67. // message. The allocated message is stored in the embedded proto.Message.
  68. //
  69. // Example:
  70. //
  71. // var x ptypes.DynamicAny
  72. // if err := ptypes.UnmarshalAny(a, &x); err != nil { ... }
  73. // fmt.Printf("unmarshaled message: %v", x.Message)
  74. type DynamicAny struct {
  75. proto.Message
  76. }
  77. // Empty returns a new proto.Message of the type specified in a
  78. // google.protobuf.Any message. It returns an error if corresponding message
  79. // type isn't linked in.
  80. func Empty(any *any.Any) (proto.Message, error) {
  81. aname, err := AnyMessageName(any)
  82. if err != nil {
  83. return nil, err
  84. }
  85. t := proto.MessageType(aname)
  86. if t == nil {
  87. return nil, fmt.Errorf("any: message type %q isn't linked in", aname)
  88. }
  89. return reflect.New(t.Elem()).Interface().(proto.Message), nil
  90. }
  91. // UnmarshalAny parses the protocol buffer representation in a google.protobuf.Any
  92. // message and places the decoded result in pb. It returns an error if type of
  93. // contents of Any message does not match type of pb message.
  94. //
  95. // pb can be a proto.Message, or a *DynamicAny.
  96. func UnmarshalAny(any *any.Any, pb proto.Message) error {
  97. if d, ok := pb.(*DynamicAny); ok {
  98. if d.Message == nil {
  99. var err error
  100. d.Message, err = Empty(any)
  101. if err != nil {
  102. return err
  103. }
  104. }
  105. return UnmarshalAny(any, d.Message)
  106. }
  107. aname, err := AnyMessageName(any)
  108. if err != nil {
  109. return err
  110. }
  111. mname := proto.MessageName(pb)
  112. if aname != mname {
  113. return fmt.Errorf("mismatched message type: got %q want %q", aname, mname)
  114. }
  115. return proto.Unmarshal(any.Value, pb)
  116. }
  117. // Is returns true if any value contains a given message type.
  118. func Is(any *any.Any, pb proto.Message) bool {
  119. // The following is equivalent to AnyMessageName(any) == proto.MessageName(pb),
  120. // but it avoids scanning TypeUrl for the slash.
  121. if any == nil {
  122. return false
  123. }
  124. name := proto.MessageName(pb)
  125. prefix := len(any.TypeUrl) - len(name)
  126. return prefix >= 1 && any.TypeUrl[prefix-1] == '/' && any.TypeUrl[prefix:] == name
  127. }