callctx.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Copyright 2023, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. // Package callctx provides helpers for storing and retrieving values out of
  30. // [context.Context]. These values are used by our client libraries in various
  31. // ways across the stack.
  32. package callctx
  33. import (
  34. "context"
  35. "fmt"
  36. )
  37. const (
  38. // XGoogFieldMaskHeader is the canonical header key for the [System Parameter]
  39. // that specifies the response read mask. The value(s) for this header
  40. // must adhere to format described in [fieldmaskpb].
  41. //
  42. // [System Parameter]: https://cloud.google.com/apis/docs/system-parameters
  43. // [fieldmaskpb]: https://google.golang.org/protobuf/types/known/fieldmaskpb
  44. XGoogFieldMaskHeader = "x-goog-fieldmask"
  45. headerKey = contextKey("header")
  46. )
  47. // contextKey is a private type used to store/retrieve context values.
  48. type contextKey string
  49. // HeadersFromContext retrieves headers set from [SetHeaders]. These headers
  50. // can then be cast to http.Header or metadata.MD to send along on requests.
  51. func HeadersFromContext(ctx context.Context) map[string][]string {
  52. m, ok := ctx.Value(headerKey).(map[string][]string)
  53. if !ok {
  54. return nil
  55. }
  56. return m
  57. }
  58. // SetHeaders stores key value pairs in the returned context that can later
  59. // be retrieved by [HeadersFromContext]. Values stored in this manner will
  60. // automatically be retrieved by client libraries and sent as outgoing headers
  61. // on all requests. keyvals should have a corresponding value for every key
  62. // provided. If there is an odd number of keyvals this method will panic.
  63. func SetHeaders(ctx context.Context, keyvals ...string) context.Context {
  64. if len(keyvals)%2 != 0 {
  65. panic(fmt.Sprintf("callctx: an even number of key value pairs must be provided, got %d", len(keyvals)))
  66. }
  67. h, ok := ctx.Value(headerKey).(map[string][]string)
  68. if !ok {
  69. h = make(map[string][]string)
  70. } else {
  71. h = cloneHeaders(h)
  72. }
  73. for i := 0; i < len(keyvals); i = i + 2 {
  74. h[keyvals[i]] = append(h[keyvals[i]], keyvals[i+1])
  75. }
  76. return context.WithValue(ctx, headerKey, h)
  77. }
  78. // cloneHeaders makes a new key-value map while reusing the value slices.
  79. // As such, new values should be appended to the value slice, and modifying
  80. // indexed values is not thread safe.
  81. //
  82. // TODO: Replace this with maps.Clone when Go 1.21 is the minimum version.
  83. func cloneHeaders(h map[string][]string) map[string][]string {
  84. c := make(map[string][]string, len(h))
  85. for k, v := range h {
  86. vc := make([]string, len(v))
  87. copy(vc, v)
  88. c[k] = vc
  89. }
  90. return c
  91. }