1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2025-08-10 22:31:50 +02:00

chore: enable gocritic linter (#7095)

#### Description

Enable and fixes several rules from
[gocritic](https://golangci-lint.run/usage/linters/#gocritic) linter

---------

Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
Co-authored-by: Tyler Yahn <MrAlias@users.noreply.github.com>
This commit is contained in:
Matthieu MOREL
2025-07-29 18:20:32 +02:00
committed by GitHub
parent 8955578fef
commit 982391315f
37 changed files with 158 additions and 146 deletions

View File

@@ -10,6 +10,7 @@ linters:
- depguard
- errcheck
- errorlint
- gocritic
- godot
- gosec
- govet
@@ -86,6 +87,20 @@ linters:
deny:
- pkg: go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal
desc: Do not use cross-module internal packages.
gocritic:
disabled-checks:
- appendAssign
- commentedOutCode
- dupArg
- hugeParam
- importShadow
- paramTypeCombine
- ptrToRefParam
- preferDecodeRune
- rangeValCopy
- unnamedResult
- whyNoLint
enable-all: true
godot:
exclude:
# Exclude links.
@@ -225,10 +240,6 @@ linters:
- linters:
- gosec
text: 'G402: TLS MinVersion too low.'
paths:
- third_party$
- builtin$
- examples$
issues:
max-issues-per-linter: 0
max-same-issues: 0
@@ -245,7 +256,3 @@ formatters:
max-len: 120
exclusions:
generated: lax
paths:
- third_party$
- builtin$
- examples$

View File

@@ -96,11 +96,11 @@ func (d *defaultAttrEncoder) Encode(iter Iterator) string {
for iter.Next() {
i, keyValue := iter.IndexedAttribute()
if i > 0 {
_, _ = buf.WriteRune(',')
_ = buf.WriteByte(',')
}
copyAndEscape(buf, string(keyValue.Key))
_, _ = buf.WriteRune('=')
_ = buf.WriteByte('=')
if keyValue.Value.Type() == STRING {
copyAndEscape(buf, keyValue.Value.AsString())
@@ -122,7 +122,7 @@ func copyAndEscape(buf *bytes.Buffer, val string) {
for _, ch := range val {
switch ch {
case '=', ',', escapeChar:
_, _ = buf.WriteRune(escapeChar)
_ = buf.WriteByte(escapeChar)
}
_, _ = buf.WriteRune(ch)
}

View File

@@ -15,7 +15,7 @@ type Filter func(KeyValue) bool
//
// If keys is empty a deny-all filter is returned.
func NewAllowKeysFilter(keys ...Key) Filter {
if len(keys) <= 0 {
if len(keys) == 0 {
return func(kv KeyValue) bool { return false }
}
@@ -34,7 +34,7 @@ func NewAllowKeysFilter(keys ...Key) Filter {
//
// If keys is empty an allow-all filter is returned.
func NewDenyKeysFilter(keys ...Key) Filter {
if len(keys) <= 0 {
if len(keys) == 0 {
return func(kv KeyValue) bool { return true }
}

View File

@@ -812,7 +812,7 @@ var safeKeyCharset = [utf8.RuneSelf]bool{
// validateBaggageName checks if the string is a valid OpenTelemetry Baggage name.
// Baggage name is a valid, non-empty UTF-8 string.
func validateBaggageName(s string) bool {
if len(s) == 0 {
if s == "" {
return false
}
@@ -828,7 +828,7 @@ func validateBaggageValue(s string) bool {
// validateKey checks if the string is a valid W3C Baggage key.
func validateKey(s string) bool {
if len(s) == 0 {
if s == "" {
return false
}

View File

@@ -134,12 +134,10 @@ func TestOTelSpanContextToOC(t *testing.T) {
gotTraceState = strings.Join(gotTraceStateEntries, ",")
}
assert.Equal(t, expectedTraceState, gotTraceState, "Tracestate should preserve entries")
} else {
} else if got.Tracestate != nil {
// For empty tracestate cases, ensure the field is properly handled
if got.Tracestate != nil {
entries := got.Tracestate.Entries()
assert.Empty(t, entries, "Empty tracestate should result in empty entries")
}
entries := got.Tracestate.Entries()
assert.Empty(t, entries, "Empty tracestate should result in empty entries")
}
})
}

View File

@@ -135,7 +135,7 @@ var (
type testTextMapPropagator struct{}
func (t testTextMapPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) {
carrier.Set(testHeader, strings.Join([]string{traceID.String(), spanID.String()}, ":"))
carrier.Set(testHeader, traceID.String()+":"+spanID.String())
// Test for panic
_ = carrier.Get("test")

View File

@@ -86,11 +86,12 @@ func newGRPCDialOptions(cfg config) []grpc.DialOption {
dialOpts = append(dialOpts, grpc.WithDefaultServiceConfig(cfg.serviceConfig.Value))
}
// Prioritize GRPCCredentials over Insecure (passing both is an error).
if cfg.gRPCCredentials.Value != nil {
switch {
case cfg.gRPCCredentials.Value != nil:
dialOpts = append(dialOpts, grpc.WithTransportCredentials(cfg.gRPCCredentials.Value))
} else if cfg.insecure.Value {
case cfg.insecure.Value:
dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
} else {
default:
// Default to using the host's root CA.
dialOpts = append(dialOpts, grpc.WithTransportCredentials(
credentials.NewTLS(nil),

View File

@@ -563,7 +563,7 @@ func loadCertificates(certPath, keyPath string) ([]tls.Certificate, error) {
func insecureFromScheme(prev setting[bool], scheme string) setting[bool] {
if scheme == "https" {
return newSetting(false)
} else if len(scheme) > 0 {
} else if scheme != "" {
return newSetting(true)
}

View File

@@ -525,10 +525,8 @@ func assertTLSConfig(t *testing.T, want, got setting[*tls.Config]) {
if want.Value.RootCAs == nil {
assert.Nil(t, got.Value.RootCAs, "*tls.Config.RootCAs")
} else {
if assert.NotNil(t, got.Value.RootCAs, "RootCAs") {
assert.True(t, want.Value.RootCAs.Equal(got.Value.RootCAs), "RootCAs equal")
}
} else if assert.NotNil(t, got.Value.RootCAs, "RootCAs") {
assert.True(t, want.Value.RootCAs.Equal(got.Value.RootCAs), "RootCAs equal")
}
assert.Equal(t, want.Value.Certificates, got.Value.Certificates, "Certificates")
}

View File

@@ -200,7 +200,7 @@ func (c *httpClient) uploadLogs(ctx context.Context, data []*logpb.ResourceLogs)
return err
}
respStr := strings.TrimSpace(respData.String())
if len(respStr) == 0 {
if respStr == "" {
respStr = "(empty)"
}
bodyErr := fmt.Errorf("body: %s", respStr)
@@ -232,7 +232,7 @@ func (c *httpClient) newRequest(ctx context.Context, body []byte) (request, erro
switch c.compression {
case NoCompression:
r.ContentLength = (int64)(len(body))
r.ContentLength = int64(len(body))
req.bodyReader = bodyReader(body)
case GzipCompression:
// Ensure the content length is not used.

View File

@@ -460,10 +460,8 @@ func assertTLSConfig(t *testing.T, want, got setting[*tls.Config]) {
if want.Value.RootCAs == nil {
assert.Nil(t, got.Value.RootCAs, "*tls.Config.RootCAs")
} else {
if assert.NotNil(t, got.Value.RootCAs, "RootCAs") {
assert.True(t, want.Value.RootCAs.Equal(got.Value.RootCAs), "RootCAs equal")
}
} else if assert.NotNil(t, got.Value.RootCAs, "RootCAs") {
assert.True(t, want.Value.RootCAs.Equal(got.Value.RootCAs), "RootCAs equal")
}
assert.Equal(t, want.Value.Certificates, got.Value.Certificates, "Certificates")
}

View File

@@ -203,7 +203,7 @@ func (c *client) UploadMetrics(ctx context.Context, protoMetrics *metricpb.Resou
return err
}
respStr := strings.TrimSpace(respData.String())
if len(respStr) == 0 {
if respStr == "" {
respStr = "(empty)"
}
bodyErr := fmt.Errorf("body: %s", respStr)
@@ -235,7 +235,7 @@ func (c *client) newRequest(ctx context.Context, body []byte) (request, error) {
switch c.compression {
case NoCompression:
r.ContentLength = (int64)(len(body))
r.ContentLength = int64(len(body))
req.bodyReader = bodyReader(body)
case GzipCompression:
// Ensure the content length is not used.

View File

@@ -209,7 +209,7 @@ func (d *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.Resourc
return err
}
respStr := strings.TrimSpace(respData.String())
if len(respStr) == 0 {
if respStr == "" {
respStr = "(empty)"
}
bodyErr := fmt.Errorf("body: %s", respStr)
@@ -230,7 +230,7 @@ func (d *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.Resourc
func (d *client) newRequest(body []byte) (request, error) {
u := url.URL{Scheme: d.getScheme(), Host: d.cfg.Endpoint, Path: d.cfg.URLPath}
r, err := http.NewRequest(http.MethodPost, u.String(), nil)
r, err := http.NewRequest(http.MethodPost, u.String(), http.NoBody)
if err != nil {
return request{Request: r}, err
}
@@ -246,7 +246,7 @@ func (d *client) newRequest(body []byte) (request, error) {
req := request{Request: r}
switch Compression(d.cfg.Compression) {
case NoCompression:
r.ContentLength = (int64)(len(body))
r.ContentLength = int64(len(body))
req.bodyReader = bodyReader(body)
case GzipCompression:
// Ensure the content length is not used.

View File

@@ -640,8 +640,8 @@ func addExemplars[N int64 | float64](
for i, exemplar := range exemplars {
labels := attributesToLabels(exemplar.FilteredAttributes, labelNamer)
// Overwrite any existing trace ID or span ID attributes
labels[otlptranslator.ExemplarTraceIDKey] = hex.EncodeToString(exemplar.TraceID[:])
labels[otlptranslator.ExemplarSpanIDKey] = hex.EncodeToString(exemplar.SpanID[:])
labels[otlptranslator.ExemplarTraceIDKey] = hex.EncodeToString(exemplar.TraceID)
labels[otlptranslator.ExemplarSpanIDKey] = hex.EncodeToString(exemplar.SpanID)
promExemplars[i] = prometheus.Exemplar{
Value: float64(exemplar.Value),
Timestamp: exemplar.Time,

View File

@@ -150,11 +150,11 @@ func toZipkinAnnotations(events []tracesdk.Event) []zkmodel.Annotation {
func attributesToJSONMapString(attributes []attribute.KeyValue) string {
m := make(map[string]any, len(attributes))
for _, a := range attributes {
m[(string)(a.Key)] = a.Value.AsInterface()
m[string(a.Key)] = a.Value.AsInterface()
}
// if an error happens, the result will be an empty string
jsonBytes, _ := json.Marshal(m)
return (string)(jsonBytes)
return string(jsonBytes)
}
// attributeToStringPair serializes each attribute to a string pair.
@@ -163,18 +163,18 @@ func attributeToStringPair(kv attribute.KeyValue) (string, string) {
// For slice attributes, serialize as JSON list string.
case attribute.BOOLSLICE:
data, _ := json.Marshal(kv.Value.AsBoolSlice())
return (string)(kv.Key), (string)(data)
return string(kv.Key), string(data)
case attribute.INT64SLICE:
data, _ := json.Marshal(kv.Value.AsInt64Slice())
return (string)(kv.Key), (string)(data)
return string(kv.Key), string(data)
case attribute.FLOAT64SLICE:
data, _ := json.Marshal(kv.Value.AsFloat64Slice())
return (string)(kv.Key), (string)(data)
return string(kv.Key), string(data)
case attribute.STRINGSLICE:
data, _ := json.Marshal(kv.Value.AsStringSlice())
return (string)(kv.Key), (string)(data)
return string(kv.Key), string(data)
default:
return (string)(kv.Key), kv.Value.Emit()
return string(kv.Key), kv.Value.Emit()
}
}

View File

@@ -146,7 +146,7 @@ func (e *Exporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpa
req.Header.Set("Content-Type", "application/json")
for k, v := range e.headers {
if strings.ToLower(k) == "host" {
if strings.EqualFold(k, "host") {
req.Host = v
} else {
req.Header.Set(k, v)

View File

@@ -171,7 +171,7 @@ type logStore struct {
}
func (s *logStore) Write(p []byte) (n int, err error) {
msg := (string)(p)
msg := string(p)
if s.T != nil {
s.T.Logf("%s", msg)
}

View File

@@ -91,7 +91,7 @@ func TestLogLevel(t *testing.T) {
func newBuffLogger(buf *bytes.Buffer, verbosity int) logr.Logger {
return funcr.New(func(prefix, args string) {
_, _ = buf.Write([]byte(args))
_, _ = buf.WriteString(args)
}, funcr.Options{
Verbosity: verbosity,
})

View File

@@ -124,7 +124,7 @@ func TestExtractValidBaggage(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
mapCarr := propagation.MapCarrier{}
mapCarr["baggage"] = tt.header
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req.Header.Set("baggage", tt.header)
// test with http header carrier (which implements ValuesGetter)
@@ -183,7 +183,7 @@ func TestExtractValidMultipleBaggageHeaders(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req.Header["Baggage"] = tt.headers
ctx := context.Background()
@@ -239,7 +239,7 @@ func TestExtractInvalidDistributedContextFromHTTPReq(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req.Header.Set("baggage", tt.header)
expected := tt.has.Baggage(t)
@@ -292,7 +292,7 @@ func TestInjectBaggageToHTTPReq(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
ctx := baggage.ContextWithBaggage(context.Background(), tt.mems.Baggage(t))
propagator.Inject(ctx, propagation.HeaderCarrier(req.Header))
@@ -339,7 +339,7 @@ func TestBaggageInjectExtractRoundtrip(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
b := tt.mems.Baggage(t)
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
ctx := baggage.ContextWithBaggage(context.Background(), b)
propagator.Inject(ctx, propagation.HeaderCarrier(req.Header))

View File

@@ -56,7 +56,7 @@ func BenchmarkExtract(b *testing.B) {
func extractSubBenchmarks(b *testing.B, fn func(*testing.B, *http.Request)) {
b.Run("Sampled", func(b *testing.B) {
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req.Header.Set("traceparent", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
b.ReportAllocs()
@@ -64,14 +64,14 @@ func extractSubBenchmarks(b *testing.B, fn func(*testing.B, *http.Request)) {
})
b.Run("BogusVersion", func(b *testing.B) {
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req.Header.Set("traceparent", "qw-00000000000000000000000000000000-0000000000000000-01")
b.ReportAllocs()
fn(b, req)
})
b.Run("FutureAdditionalData", func(b *testing.B) {
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req.Header.Set("traceparent", "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-09-XYZxsf09")
b.ReportAllocs()
fn(b, req)

View File

@@ -19,7 +19,7 @@ import (
// to the case-insensitive string value of "true" (i.e. "True" and "TRUE"
// will also enable this).
var Resource = newFeature("RESOURCE", func(v string) (string, bool) {
if strings.ToLower(v) == "true" {
if strings.EqualFold(v, "true") {
return v, true
}
return "", false

View File

@@ -15,9 +15,9 @@ import (
"go.opentelemetry.io/otel/log"
)
func verifyRing(t *testing.T, r *ring, N int, sum int) {
func verifyRing(t *testing.T, r *ring, num int, sum int) {
// Length.
assert.Equal(t, N, r.Len(), "r.Len()")
assert.Equal(t, num, r.Len(), "r.Len()")
// Iteration.
var n, s int
@@ -28,7 +28,7 @@ func verifyRing(t *testing.T, r *ring, N int, sum int) {
s += int(body.AsInt64())
}
})
assert.Equal(t, N, n, "number of forward iterations")
assert.Equal(t, num, n, "number of forward iterations")
if sum >= 0 {
assert.Equal(t, sum, s, "forward ring sum")
}

View File

@@ -125,13 +125,11 @@ func (r *FixedSizeReservoir) Offer(ctx context.Context, t time.Time, n Value, a
if int(r.count) < cap(r.store) {
r.store[r.count] = newMeasurement(ctx, t, n, a)
} else {
if r.count == r.next {
// Overwrite a random existing measurement with the one offered.
idx := int(rand.Int64N(int64(cap(r.store))))
r.store[idx] = newMeasurement(ctx, t, n, a)
r.advance()
}
} else if r.count == r.next {
// Overwrite a random existing measurement with the one offered.
idx := int(rand.Int64N(int64(cap(r.store))))
r.store[idx] = newMeasurement(ctx, t, n, a)
r.advance()
}
r.count++
}

View File

@@ -183,8 +183,8 @@ func (p *expoHistogramDataPoint[N]) scaleChange(bin, startBin int32, length int)
var count int32
for high-low >= p.maxSize {
low = low >> 1
high = high >> 1
low >>= 1
high >>= 1
count++
if count > expoMaxScale-expoMinScale {
return count
@@ -225,7 +225,7 @@ func (b *expoBuckets) record(bin int32) {
b.counts = append(b.counts, make([]uint64, newLength-len(b.counts))...)
}
copy(b.counts[shift:origLen+int(shift)], b.counts[:])
copy(b.counts[shift:origLen+int(shift)], b.counts)
b.counts = b.counts[:newLength]
for i := 1; i < int(shift); i++ {
b.counts[i] = 0
@@ -264,7 +264,7 @@ func (b *expoBuckets) downscale(delta int32) {
// new Counts: [4, 14, 30, 10]
if len(b.counts) <= 1 || delta < 1 {
b.startBin = b.startBin >> delta
b.startBin >>= delta
return
}
@@ -282,7 +282,7 @@ func (b *expoBuckets) downscale(delta int32) {
lastIdx := (len(b.counts) - 1 + int(offset)) / int(steps)
b.counts = b.counts[:lastIdx+1]
b.startBin = b.startBin >> delta
b.startBin >>= delta
}
// newExponentialHistogram returns an Aggregator that summarizes a set of

View File

@@ -656,7 +656,7 @@ func BenchmarkPrepend(b *testing.B) {
n := math.MaxFloat64
for range 1024 {
agg.record(n)
n = n / 2
n /= 2
}
}
}
@@ -667,7 +667,7 @@ func BenchmarkAppend(b *testing.B) {
n := smallestNonZeroNormalFloat64
for range 1024 {
agg.record(n)
n = n * 2
n *= 2
}
}
}
@@ -1061,7 +1061,7 @@ func FuzzGetBin(f *testing.F) {
f.Fuzz(func(t *testing.T, v float64, scale int32) {
// GetBin only works on positive values.
if math.Signbit(v) {
v = v * -1
v *= -1
}
// GetBin Doesn't work on zero.
if v == 0.0 {

View File

@@ -423,7 +423,7 @@ func (m *meter) Float64ObservableGauge(
}
func validateInstrumentName(name string) error {
if len(name) == 0 {
if name == "" {
return fmt.Errorf("%w: %s: is empty", ErrInstrumentName, name)
}
if len(name) > 255 {

View File

@@ -653,32 +653,31 @@ func TestPipelineProduceErrors(t *testing.T) {
var shouldReturnError bool // When true, the third callback returns an error
var callbackCounts [3]int
// Callback 1: cancels the context during execution but continues to populate data
pipe.callbacks = append(pipe.callbacks, func(ctx context.Context) error {
callbackCounts[0]++
for _, m := range pipe.int64Measures[testObsID] {
m(ctx, 123, *attribute.EmptySet())
}
return nil
})
// Callback 2: populates int64 observable data
pipe.callbacks = append(pipe.callbacks, func(ctx context.Context) error {
callbackCounts[1]++
if shouldCancelContext {
cancelCtx()
}
return nil
})
// Callback 3: return an error
pipe.callbacks = append(pipe.callbacks, func(ctx context.Context) error {
callbackCounts[2]++
if shouldReturnError {
return fmt.Errorf("test callback error")
}
return nil
})
pipe.callbacks = append(pipe.callbacks,
// Callback 1: cancels the context during execution but continues to populate data
func(ctx context.Context) error {
callbackCounts[0]++
for _, m := range pipe.int64Measures[testObsID] {
m(ctx, 123, *attribute.EmptySet())
}
return nil
},
// Callback 2: populates int64 observable data
func(ctx context.Context) error {
callbackCounts[1]++
if shouldCancelContext {
cancelCtx()
}
return nil
},
// Callback 3: return an error
func(ctx context.Context) error {
callbackCounts[2]++
if shouldReturnError {
return fmt.Errorf("test callback error")
}
return nil
})
assertMetrics := func(rm *metricdata.ResourceMetrics, expectVal int64) {
require.Len(t, rm.ScopeMetrics, 1)

View File

@@ -68,7 +68,7 @@ func parseOSReleaseFile(file io.Reader) map[string]string {
func skip(line string) bool {
line = strings.TrimSpace(line)
return len(line) == 0 || strings.HasPrefix(line, "#")
return line == "" || strings.HasPrefix(line, "#")
}
// parse attempts to split the provided line on the first '=' character, and then
@@ -76,7 +76,7 @@ func skip(line string) bool {
func parse(line string) (string, string, bool) {
k, v, found := strings.Cut(line, "=")
if !found || len(k) == 0 {
if !found || k == "" {
return "", "", false
}

View File

@@ -505,7 +505,7 @@ func TestBatchSpanProcessorDropBatchIfFailed(t *testing.T) {
func assertMaxSpanDiff(t *testing.T, want, got, maxDif int) {
spanDifference := want - got
if spanDifference < 0 {
spanDifference = spanDifference * -1
spanDifference *= -1
}
if spanDifference > maxDif {
t.Errorf("number of exported span not equal to or within %d less than: got %+v, want %+v\n",
@@ -514,7 +514,7 @@ func assertMaxSpanDiff(t *testing.T, want, got, maxDif int) {
}
type indefiniteExporter struct {
stop chan (struct{})
stop chan struct{}
}
func newIndefiniteExporter(t *testing.T) indefiniteExporter {

View File

@@ -16,7 +16,7 @@ import (
// to the case-insensitive string value of "true" (i.e. "True" and "TRUE"
// will also enable this).
var SelfObservability = newFeature("SELF_OBSERVABILITY", func(v string) (string, bool) {
if strings.ToLower(v) == "true" {
if strings.EqualFold(v, "true") {
return v, true
}
return "", false

View File

@@ -92,13 +92,14 @@ func (tr *tracer) Start(
// Determine the sampling result and create the corresponding attribute.
var attrSamplingResult attribute.KeyValue
if s.SpanContext().IsSampled() && s.IsRecording() {
switch {
case s.SpanContext().IsSampled() && s.IsRecording():
attrSamplingResult = tr.spanStartedMetric.AttrSpanSamplingResult(
otelconv.SpanSamplingResultRecordAndSample,
)
} else if s.IsRecording() {
case s.IsRecording():
attrSamplingResult = tr.spanStartedMetric.AttrSpanSamplingResult(otelconv.SpanSamplingResultRecordOnly)
} else {
default:
attrSamplingResult = tr.spanStartedMetric.AttrSpanSamplingResult(otelconv.SpanSamplingResultDrop)
}

View File

@@ -1008,7 +1008,7 @@ func kvStr(kvs []attribute.KeyValue) string {
if idx > 0 {
_, _ = sb.WriteString(", ")
}
_, _ = sb.WriteString((string)(attr.Key))
_, _ = sb.WriteString(string(attr.Key))
_, _ = sb.WriteString(": ")
_, _ = sb.WriteString(attr.Value.Emit())
}

View File

@@ -91,8 +91,7 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue {
}
attrs := make([]attribute.KeyValue, 0, n)
attrs = append(attrs, c.method(req.Method))
attrs = append(attrs, c.proto(req.Proto))
attrs = append(attrs, c.method(req.Method), c.proto(req.Proto))
var u string
if req.URL != nil {
@@ -103,9 +102,11 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue {
// Restore any username/password info that was removed.
req.URL.User = userinfo
}
attrs = append(attrs, c.HTTPURLKey.String(u))
attrs = append(attrs, c.NetConv.PeerName(peer))
attrs = append(
attrs,
c.HTTPURLKey.String(u),
c.NetConv.PeerName(peer),
)
if port > 0 {
attrs = append(attrs, c.NetConv.PeerPort(port))
}
@@ -191,10 +192,13 @@ func (c *HTTPConv) ServerRequest(server string, req *http.Request) []attribute.K
}
attrs := make([]attribute.KeyValue, 0, n)
attrs = append(attrs, c.method(req.Method))
attrs = append(attrs, c.scheme(req.TLS != nil))
attrs = append(attrs, c.proto(req.Proto))
attrs = append(attrs, c.NetConv.HostName(host))
attrs = append(
attrs,
c.method(req.Method),
c.scheme(req.TLS != nil),
c.proto(req.Proto),
c.NetConv.HostName(host),
)
if hostPort > 0 {
attrs = append(attrs, c.NetConv.HostPort(hostPort))

View File

@@ -91,8 +91,7 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue {
}
attrs := make([]attribute.KeyValue, 0, n)
attrs = append(attrs, c.method(req.Method))
attrs = append(attrs, c.proto(req.Proto))
attrs = append(attrs, c.method(req.Method), c.proto(req.Proto))
var u string
if req.URL != nil {
@@ -103,9 +102,11 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue {
// Restore any username/password info that was removed.
req.URL.User = userinfo
}
attrs = append(attrs, c.HTTPURLKey.String(u))
attrs = append(attrs, c.NetConv.PeerName(peer))
attrs = append(
attrs,
c.HTTPURLKey.String(u),
c.NetConv.PeerName(peer),
)
if port > 0 {
attrs = append(attrs, c.NetConv.PeerPort(port))
}
@@ -191,10 +192,13 @@ func (c *HTTPConv) ServerRequest(server string, req *http.Request) []attribute.K
}
attrs := make([]attribute.KeyValue, 0, n)
attrs = append(attrs, c.method(req.Method))
attrs = append(attrs, c.scheme(req.TLS != nil))
attrs = append(attrs, c.proto(req.Proto))
attrs = append(attrs, c.NetConv.HostName(host))
attrs = append(
attrs,
c.method(req.Method),
c.scheme(req.TLS != nil),
c.proto(req.Proto),
c.NetConv.HostName(host),
)
if hostPort > 0 {
attrs = append(attrs, c.NetConv.HostPort(hostPort))

View File

@@ -92,8 +92,7 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue {
}
attrs := make([]attribute.KeyValue, 0, n)
attrs = append(attrs, c.method(req.Method))
attrs = append(attrs, c.proto(req.Proto))
attrs = append(attrs, c.method(req.Method), c.proto(req.Proto))
var u string
if req.URL != nil {
@@ -104,9 +103,11 @@ func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue {
// Restore any username/password info that was removed.
req.URL.User = userinfo
}
attrs = append(attrs, c.HTTPURLKey.String(u))
attrs = append(attrs, c.NetConv.PeerName(peer))
attrs = append(
attrs,
c.HTTPURLKey.String(u),
c.NetConv.PeerName(peer),
)
if port > 0 {
attrs = append(attrs, c.NetConv.PeerPort(port))
}
@@ -192,10 +193,13 @@ func (c *HTTPConv) ServerRequest(server string, req *http.Request) []attribute.K
}
attrs := make([]attribute.KeyValue, 0, n)
attrs = append(attrs, c.method(req.Method))
attrs = append(attrs, c.scheme(req.TLS != nil))
attrs = append(attrs, c.proto(req.Proto))
attrs = append(attrs, c.NetConv.HostName(host))
attrs = append(
attrs,
c.method(req.Method),
c.scheme(req.TLS != nil),
c.proto(req.Proto),
c.NetConv.HostName(host),
)
if hostPort > 0 {
attrs = append(attrs, c.NetConv.HostPort(hostPort))

View File

@@ -165,7 +165,7 @@ func (tf TraceFlags) MarshalJSON() ([]byte, error) {
// String returns the hex string representation form of TraceFlags.
func (tf TraceFlags) String() string {
return hex.EncodeToString([]byte{byte(tf)}[:])
return hex.EncodeToString([]byte{byte(tf)})
}
// SpanContextConfig contains mutable fields usable for constructing

View File

@@ -80,7 +80,7 @@ func checkKeyRemain(key string) bool {
//
// param n is remain part length, should be 255 in simple-key or 13 in system-id.
func checkKeyPart(key string, n int) bool {
if len(key) == 0 {
if key == "" {
return false
}
first := key[0] // key's first char
@@ -102,7 +102,7 @@ func isAlphaNum(c byte) bool {
//
// param n is remain part length, should be 240 exactly.
func checkKeyTenant(key string, n int) bool {
if len(key) == 0 {
if key == "" {
return false
}
return isAlphaNum(key[0]) && len(key[1:]) <= n && checkKeyRemain(key[1:])
@@ -191,7 +191,7 @@ func ParseTraceState(ts string) (TraceState, error) {
for ts != "" {
var memberStr string
memberStr, ts, _ = strings.Cut(ts, listDelimiters)
if len(memberStr) == 0 {
if memberStr == "" {
continue
}