-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbaggage.go
72 lines (58 loc) · 1.92 KB
/
baggage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package oteltag
import (
"reflect"
"strings"
"go.opentelemetry.io/otel/baggage"
"github.com/remychantenay/otel-tag/internal"
)
// BaggageMembers takes in a struct and spits out OpenTelemetry baggage members
// based on the struct tags.
func BaggageMembers(res any) []baggage.Member {
return structToBaggageMembers(res)
}
// structToBaggageMembers returns a slice of [baggage.Member] for a struct.
func structToBaggageMembers(s any) []baggage.Member {
structValue := reflect.ValueOf(s)
structType := structValue.Type()
fieldCount := structValue.NumField()
if fieldCount == 0 {
return nil
}
members := make([]baggage.Member, 0, fieldCount)
for i := 0; i < fieldCount; i++ {
field, fieldValue := structType.Field(i), structValue.Field(i)
if field.Type.Kind() == reflect.Struct && fieldValue.IsValid() {
members = append(members, structToBaggageMembers(fieldValue.Interface())...)
} else if field.Type.Kind() == reflect.Pointer && fieldValue.IsValid() { // Known shortcoming, assuming a pointer can only be a struct.
members = append(members, structToBaggageMembers(fieldValue.Elem().Interface())...)
} else {
member := basicTypeToBaggageMember(structType, structValue, i)
if member.Key() == "" {
continue
}
members = append(members, member)
}
}
return members
}
// basicTypeToBaggageMember returns an [attribute.Member] for a basic type.
func basicTypeToBaggageMember(structType reflect.Type, structValue reflect.Value, index int) baggage.Member {
tag := internal.ExtractTag(structValue, index)
if tag == "" {
return baggage.Member{}
}
var omitEmpty bool
before, after, found := strings.Cut(tag, ",")
if found {
tag = before
if after == flagOmitEmpty {
omitEmpty = true
}
}
field, fieldValue := structType.Field(index), structValue.Field(index)
attr, zeroValue := internal.BaggageMember(field, fieldValue, tag)
if zeroValue && omitEmpty {
return baggage.Member{}
}
return attr
}