khenaidoo | 5fc5cea | 2021-08-11 17:39:16 -0400 | [diff] [blame] | 1 | /* |
| 2 | * |
| 3 | * Copyright 2020 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 | |
| 19 | // Package metadata contains functions to set and get metadata from addresses. |
| 20 | // |
| 21 | // This package is experimental. |
| 22 | package metadata |
| 23 | |
| 24 | import ( |
| 25 | "google.golang.org/grpc/metadata" |
| 26 | "google.golang.org/grpc/resolver" |
| 27 | ) |
| 28 | |
| 29 | type mdKeyType string |
| 30 | |
| 31 | const mdKey = mdKeyType("grpc.internal.address.metadata") |
| 32 | |
khenaidoo | 5cb0d40 | 2021-12-08 14:09:16 -0500 | [diff] [blame] | 33 | type mdValue metadata.MD |
| 34 | |
| 35 | func (m mdValue) Equal(o interface{}) bool { |
| 36 | om, ok := o.(mdValue) |
| 37 | if !ok { |
| 38 | return false |
| 39 | } |
| 40 | if len(m) != len(om) { |
| 41 | return false |
| 42 | } |
| 43 | for k, v := range m { |
| 44 | ov := om[k] |
| 45 | if len(ov) != len(v) { |
| 46 | return false |
| 47 | } |
| 48 | for i, ve := range v { |
| 49 | if ov[i] != ve { |
| 50 | return false |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | return true |
| 55 | } |
| 56 | |
khenaidoo | 5fc5cea | 2021-08-11 17:39:16 -0400 | [diff] [blame] | 57 | // Get returns the metadata of addr. |
| 58 | func Get(addr resolver.Address) metadata.MD { |
| 59 | attrs := addr.Attributes |
| 60 | if attrs == nil { |
| 61 | return nil |
| 62 | } |
khenaidoo | 5cb0d40 | 2021-12-08 14:09:16 -0500 | [diff] [blame] | 63 | md, _ := attrs.Value(mdKey).(mdValue) |
| 64 | return metadata.MD(md) |
khenaidoo | 5fc5cea | 2021-08-11 17:39:16 -0400 | [diff] [blame] | 65 | } |
| 66 | |
| 67 | // Set sets (overrides) the metadata in addr. |
| 68 | // |
| 69 | // When a SubConn is created with this address, the RPCs sent on it will all |
| 70 | // have this metadata. |
| 71 | func Set(addr resolver.Address, md metadata.MD) resolver.Address { |
khenaidoo | 5cb0d40 | 2021-12-08 14:09:16 -0500 | [diff] [blame] | 72 | addr.Attributes = addr.Attributes.WithValue(mdKey, mdValue(md)) |
khenaidoo | 5fc5cea | 2021-08-11 17:39:16 -0400 | [diff] [blame] | 73 | return addr |
| 74 | } |