Girish Kumar | 93e9174 | 2020-07-27 16:43:19 +0000 | [diff] [blame] | 1 | // Copyright 2017 Michal Witkowski. All Rights Reserved. |
| 2 | // See LICENSE for licensing terms. |
| 3 | |
| 4 | package grpc_opentracing |
| 5 | |
| 6 | import ( |
| 7 | "encoding/base64" |
| 8 | "strings" |
| 9 | |
Girish Kumar | 93e9174 | 2020-07-27 16:43:19 +0000 | [diff] [blame] | 10 | "google.golang.org/grpc/metadata" |
| 11 | ) |
| 12 | |
| 13 | const ( |
| 14 | binHdrSuffix = "-bin" |
| 15 | ) |
| 16 | |
| 17 | // metadataTextMap extends a metadata.MD to be an opentracing textmap |
| 18 | type metadataTextMap metadata.MD |
| 19 | |
| 20 | // Set is a opentracing.TextMapReader interface that extracts values. |
| 21 | func (m metadataTextMap) Set(key, val string) { |
| 22 | // gRPC allows for complex binary values to be written. |
| 23 | encodedKey, encodedVal := encodeKeyValue(key, val) |
| 24 | // The metadata object is a multimap, and previous values may exist, but for opentracing headers, we do not append |
| 25 | // we just override. |
| 26 | m[encodedKey] = []string{encodedVal} |
| 27 | } |
| 28 | |
| 29 | // ForeachKey is a opentracing.TextMapReader interface that extracts values. |
| 30 | func (m metadataTextMap) ForeachKey(callback func(key, val string) error) error { |
| 31 | for k, vv := range m { |
| 32 | for _, v := range vv { |
khenaidoo | 106c61a | 2021-08-11 18:05:46 -0400 | [diff] [blame] | 33 | if err := callback(k, v); err != nil { |
| 34 | return err |
Girish Kumar | 93e9174 | 2020-07-27 16:43:19 +0000 | [diff] [blame] | 35 | } |
| 36 | } |
| 37 | } |
| 38 | return nil |
| 39 | } |
| 40 | |
| 41 | // encodeKeyValue encodes key and value qualified for transmission via gRPC. |
| 42 | // note: copy pasted from private values of grpc.metadata |
| 43 | func encodeKeyValue(k, v string) (string, string) { |
| 44 | k = strings.ToLower(k) |
| 45 | if strings.HasSuffix(k, binHdrSuffix) { |
| 46 | val := base64.StdEncoding.EncodeToString([]byte(v)) |
| 47 | v = string(val) |
| 48 | } |
| 49 | return k, v |
| 50 | } |