dubbo.apache.org/dubbo-go/v3@v3.1.1/filter/otel/trace/attachment.go (about) 1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. 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 trace 19 20 import ( 21 "context" 22 ) 23 24 import ( 25 "go.opentelemetry.io/otel/baggage" 26 27 "go.opentelemetry.io/otel/propagation" 28 29 "go.opentelemetry.io/otel/trace" 30 ) 31 32 type metadataSupplier struct { 33 metadata map[string]interface{} 34 } 35 36 var _ propagation.TextMapCarrier = &metadataSupplier{} 37 38 func (s *metadataSupplier) Get(key string) string { 39 if s.metadata == nil { 40 return "" 41 } 42 item, ok := s.metadata[key].([]string) 43 if !ok { 44 return "" 45 } 46 if len(item) == 0 { 47 return "" 48 } 49 return item[0] 50 } 51 52 func (s *metadataSupplier) Set(key string, value string) { 53 if s.metadata == nil { 54 s.metadata = map[string]interface{}{} 55 } 56 s.metadata[key] = value 57 } 58 59 func (s *metadataSupplier) Keys() []string { 60 out := make([]string, 0, len(s.metadata)) 61 for key := range s.metadata { 62 out = append(out, key) 63 } 64 return out 65 } 66 67 // Inject injects correlation context and span context into the dubbo 68 // metadata object. This function is meant to be used on outgoing 69 // requests. 70 func Inject(ctx context.Context, metadata map[string]interface{}, propagators propagation.TextMapPropagator) { 71 propagators.Inject(ctx, &metadataSupplier{ 72 metadata: metadata, 73 }) 74 } 75 76 // Extract returns the baggage and span context that 77 // another service encoded in the dubbo metadata object with Inject. 78 // This function is meant to be used on incoming requests. 79 func Extract(ctx context.Context, metadata map[string]interface{}, propagators propagation.TextMapPropagator) (baggage.Baggage, trace.SpanContext) { 80 ctx = propagators.Extract(ctx, &metadataSupplier{ 81 metadata: metadata, 82 }) 83 return baggage.FromContext(ctx), trace.SpanContextFromContext(ctx) 84 }