metadata.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. /*
  2. *
  3. * Copyright 2014 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 metadata define the structure of the metadata supported by gRPC library.
  19. // Please refer to https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
  20. // for more information about custom-metadata.
  21. package metadata // import "google.golang.org/grpc/metadata"
  22. import (
  23. "context"
  24. "fmt"
  25. "strings"
  26. )
  27. // DecodeKeyValue returns k, v, nil.
  28. //
  29. // Deprecated: use k and v directly instead.
  30. func DecodeKeyValue(k, v string) (string, string, error) {
  31. return k, v, nil
  32. }
  33. // MD is a mapping from metadata keys to values. Users should use the following
  34. // two convenience functions New and Pairs to generate MD.
  35. type MD map[string][]string
  36. // New creates an MD from a given key-value map.
  37. //
  38. // Only the following ASCII characters are allowed in keys:
  39. // - digits: 0-9
  40. // - uppercase letters: A-Z (normalized to lower)
  41. // - lowercase letters: a-z
  42. // - special characters: -_.
  43. // Uppercase letters are automatically converted to lowercase.
  44. //
  45. // Keys beginning with "grpc-" are reserved for grpc-internal use only and may
  46. // result in errors if set in metadata.
  47. func New(m map[string]string) MD {
  48. md := MD{}
  49. for k, val := range m {
  50. key := strings.ToLower(k)
  51. md[key] = append(md[key], val)
  52. }
  53. return md
  54. }
  55. // Pairs returns an MD formed by the mapping of key, value ...
  56. // Pairs panics if len(kv) is odd.
  57. //
  58. // Only the following ASCII characters are allowed in keys:
  59. // - digits: 0-9
  60. // - uppercase letters: A-Z (normalized to lower)
  61. // - lowercase letters: a-z
  62. // - special characters: -_.
  63. // Uppercase letters are automatically converted to lowercase.
  64. //
  65. // Keys beginning with "grpc-" are reserved for grpc-internal use only and may
  66. // result in errors if set in metadata.
  67. func Pairs(kv ...string) MD {
  68. if len(kv)%2 == 1 {
  69. panic(fmt.Sprintf("metadata: Pairs got the odd number of input pairs for metadata: %d", len(kv)))
  70. }
  71. md := MD{}
  72. var key string
  73. for i, s := range kv {
  74. if i%2 == 0 {
  75. key = strings.ToLower(s)
  76. continue
  77. }
  78. md[key] = append(md[key], s)
  79. }
  80. return md
  81. }
  82. // Len returns the number of items in md.
  83. func (md MD) Len() int {
  84. return len(md)
  85. }
  86. // Copy returns a copy of md.
  87. func (md MD) Copy() MD {
  88. return Join(md)
  89. }
  90. // Get obtains the values for a given key.
  91. func (md MD) Get(k string) []string {
  92. k = strings.ToLower(k)
  93. return md[k]
  94. }
  95. // Set sets the value of a given key with a slice of values.
  96. func (md MD) Set(k string, vals ...string) {
  97. if len(vals) == 0 {
  98. return
  99. }
  100. k = strings.ToLower(k)
  101. md[k] = vals
  102. }
  103. // Append adds the values to key k, not overwriting what was already stored at that key.
  104. func (md MD) Append(k string, vals ...string) {
  105. if len(vals) == 0 {
  106. return
  107. }
  108. k = strings.ToLower(k)
  109. md[k] = append(md[k], vals...)
  110. }
  111. // Join joins any number of mds into a single MD.
  112. // The order of values for each key is determined by the order in which
  113. // the mds containing those values are presented to Join.
  114. func Join(mds ...MD) MD {
  115. out := MD{}
  116. for _, md := range mds {
  117. for k, v := range md {
  118. out[k] = append(out[k], v...)
  119. }
  120. }
  121. return out
  122. }
  123. type mdIncomingKey struct{}
  124. type mdOutgoingKey struct{}
  125. // NewIncomingContext creates a new context with incoming md attached.
  126. func NewIncomingContext(ctx context.Context, md MD) context.Context {
  127. return context.WithValue(ctx, mdIncomingKey{}, md)
  128. }
  129. // NewOutgoingContext creates a new context with outgoing md attached. If used
  130. // in conjunction with AppendToOutgoingContext, NewOutgoingContext will
  131. // overwrite any previously-appended metadata.
  132. func NewOutgoingContext(ctx context.Context, md MD) context.Context {
  133. return context.WithValue(ctx, mdOutgoingKey{}, rawMD{md: md})
  134. }
  135. // AppendToOutgoingContext returns a new context with the provided kv merged
  136. // with any existing metadata in the context. Please refer to the
  137. // documentation of Pairs for a description of kv.
  138. func AppendToOutgoingContext(ctx context.Context, kv ...string) context.Context {
  139. if len(kv)%2 == 1 {
  140. panic(fmt.Sprintf("metadata: AppendToOutgoingContext got an odd number of input pairs for metadata: %d", len(kv)))
  141. }
  142. md, _ := ctx.Value(mdOutgoingKey{}).(rawMD)
  143. added := make([][]string, len(md.added)+1)
  144. copy(added, md.added)
  145. added[len(added)-1] = make([]string, len(kv))
  146. copy(added[len(added)-1], kv)
  147. return context.WithValue(ctx, mdOutgoingKey{}, rawMD{md: md.md, added: added})
  148. }
  149. // FromIncomingContext returns the incoming metadata in ctx if it exists. The
  150. // returned MD should not be modified. Writing to it may cause races.
  151. // Modification should be made to copies of the returned MD.
  152. func FromIncomingContext(ctx context.Context) (md MD, ok bool) {
  153. md, ok = ctx.Value(mdIncomingKey{}).(MD)
  154. return
  155. }
  156. // FromOutgoingContextRaw returns the un-merged, intermediary contents
  157. // of rawMD. Remember to perform strings.ToLower on the keys. The returned
  158. // MD should not be modified. Writing to it may cause races. Modification
  159. // should be made to copies of the returned MD.
  160. //
  161. // This is intended for gRPC-internal use ONLY.
  162. func FromOutgoingContextRaw(ctx context.Context) (MD, [][]string, bool) {
  163. raw, ok := ctx.Value(mdOutgoingKey{}).(rawMD)
  164. if !ok {
  165. return nil, nil, false
  166. }
  167. return raw.md, raw.added, true
  168. }
  169. // FromOutgoingContext returns the outgoing metadata in ctx if it exists. The
  170. // returned MD should not be modified. Writing to it may cause races.
  171. // Modification should be made to copies of the returned MD.
  172. func FromOutgoingContext(ctx context.Context) (MD, bool) {
  173. raw, ok := ctx.Value(mdOutgoingKey{}).(rawMD)
  174. if !ok {
  175. return nil, false
  176. }
  177. mds := make([]MD, 0, len(raw.added)+1)
  178. mds = append(mds, raw.md)
  179. for _, vv := range raw.added {
  180. mds = append(mds, Pairs(vv...))
  181. }
  182. return Join(mds...), ok
  183. }
  184. type rawMD struct {
  185. md MD
  186. added [][]string
  187. }