blob: b8733dbf340daeca041d077f73d9c6bd015a46eb [file] [log] [blame]
khenaidoo5fc5cea2021-08-11 17:39:16 -04001/*
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.
22package metadata
23
24import (
25 "google.golang.org/grpc/metadata"
26 "google.golang.org/grpc/resolver"
27)
28
29type mdKeyType string
30
31const mdKey = mdKeyType("grpc.internal.address.metadata")
32
khenaidoo5cb0d402021-12-08 14:09:16 -050033type mdValue metadata.MD
34
35func (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
khenaidoo5fc5cea2021-08-11 17:39:16 -040057// Get returns the metadata of addr.
58func Get(addr resolver.Address) metadata.MD {
59 attrs := addr.Attributes
60 if attrs == nil {
61 return nil
62 }
khenaidoo5cb0d402021-12-08 14:09:16 -050063 md, _ := attrs.Value(mdKey).(mdValue)
64 return metadata.MD(md)
khenaidoo5fc5cea2021-08-11 17:39:16 -040065}
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.
71func Set(addr resolver.Address, md metadata.MD) resolver.Address {
khenaidoo5cb0d402021-12-08 14:09:16 -050072 addr.Attributes = addr.Attributes.WithValue(mdKey, mdValue(md))
khenaidoo5fc5cea2021-08-11 17:39:16 -040073 return addr
74}