From df0197455b5bb49a628f86edb269d94ae20b38d0 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Wed, 30 Oct 2024 23:32:03 +0100 Subject: [PATCH] [chore]: enable usestdlibvars linter (part 2) Signed-off-by: Matthieu MOREL --- .golangci.yml | 1 + .../internal/clientutil/api.go | 3 +- .../internal/clientutil/error_converter.go | 2 +- .../clientutil/error_converter_test.go | 6 ++-- .../internal/clientutil/retrier_test.go | 2 +- .../elasticsearchexporter/bulkindexer_test.go | 6 ++-- exporter/influxdbexporter/writer.go | 6 ++-- exporter/lokiexporter/exporter.go | 2 +- .../prometheusremotewriteexporter/exporter.go | 2 +- exporter/signalfxexporter/dpclient.go | 2 +- exporter/signalfxexporter/eventclient.go | 2 +- .../internal/apm/correlations/client_test.go | 2 +- .../internal/dimensions/dimclient.go | 2 +- exporter/splunkhecexporter/hec_worker.go | 2 +- exporter/sumologicexporter/exporter_test.go | 8 ++--- exporter/sumologicexporter/sender.go | 6 ++-- exporter/sumologicexporter/sender_test.go | 14 ++++---- exporter/zipkinexporter/zipkin.go | 2 +- extension/asapauthextension/extension_test.go | 2 +- .../bearertokenauth_test.go | 8 ++--- extension/opampextension/auth.go | 2 +- extension/sumologicextension/extension.go | 4 +-- .../sumologicextension/extension_test.go | 32 +++++++++---------- internal/metadataproviders/azure/metadata.go | 2 +- .../jaeger/jaegerproto_to_traces_test.go | 3 +- .../translator/stats_translator_test.go | 5 +-- .../traces_exporter.go | 2 +- 27 files changed, 67 insertions(+), 63 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index e7d4a3846078..c4b5b692e199 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -164,6 +164,7 @@ linters: - unconvert - unparam - unused + - usestdlibvars - wastedassign issues: diff --git a/exporter/datadogexporter/internal/clientutil/api.go b/exporter/datadogexporter/internal/clientutil/api.go index 346591e7eac7..33e71a700c0e 100644 --- a/exporter/datadogexporter/internal/clientutil/api.go +++ b/exporter/datadogexporter/internal/clientutil/api.go @@ -6,6 +6,7 @@ package clientutil // import "github.com/open-telemetry/opentelemetry-collector- import ( "context" "errors" + "net/http" "github.com/DataDog/datadog-api-client-go/v2/api/datadog" "github.com/DataDog/datadog-api-client-go/v2/api/datadogV1" @@ -45,7 +46,7 @@ func ValidateAPIKey(ctx context.Context, apiKey string, logger *zap.Logger, apiC return nil } if err != nil { - if httpresp != nil && httpresp.StatusCode == 403 { + if httpresp != nil && httpresp.StatusCode == http.StatusForbidden { return WrapError(ErrInvalidAPI, httpresp) } logger.Warn("Error while validating API key", zap.Error(err)) diff --git a/exporter/datadogexporter/internal/clientutil/error_converter.go b/exporter/datadogexporter/internal/clientutil/error_converter.go index b4b2417ce170..638c4d993c28 100644 --- a/exporter/datadogexporter/internal/clientutil/error_converter.go +++ b/exporter/datadogexporter/internal/clientutil/error_converter.go @@ -18,5 +18,5 @@ func WrapError(err error, resp *http.Response) error { } func isNonRetriable(resp *http.Response) bool { - return resp.StatusCode == 400 || resp.StatusCode == 404 || resp.StatusCode == 413 || resp.StatusCode == 403 + return resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusRequestEntityTooLarge || resp.StatusCode == http.StatusForbidden } diff --git a/exporter/datadogexporter/internal/clientutil/error_converter_test.go b/exporter/datadogexporter/internal/clientutil/error_converter_test.go index 656ec60e2e6c..d699762d3a4c 100644 --- a/exporter/datadogexporter/internal/clientutil/error_converter_test.go +++ b/exporter/datadogexporter/internal/clientutil/error_converter_test.go @@ -13,9 +13,9 @@ import ( ) func TestWrapError(t *testing.T) { - respOK := http.Response{StatusCode: 200} - respRetriable := http.Response{StatusCode: 402} - respNonRetriable := http.Response{StatusCode: 404} + respOK := http.Response{StatusCode: http.StatusOK} + respRetriable := http.Response{StatusCode: http.StatusPaymentRequired} + respNonRetriable := http.Response{StatusCode: http.StatusNotFound} err := fmt.Errorf("Test error") assert.False(t, consumererror.IsPermanent(WrapError(err, &respOK))) assert.False(t, consumererror.IsPermanent(WrapError(err, &respRetriable))) diff --git a/exporter/datadogexporter/internal/clientutil/retrier_test.go b/exporter/datadogexporter/internal/clientutil/retrier_test.go index 15685294bb48..0c76b7a03004 100644 --- a/exporter/datadogexporter/internal/clientutil/retrier_test.go +++ b/exporter/datadogexporter/internal/clientutil/retrier_test.go @@ -46,7 +46,7 @@ func TestNoRetriesOnPermanentError(t *testing.T) { scrubber := scrub.NewScrubber() retrier := NewRetrier(zap.NewNop(), configretry.NewDefaultBackOffConfig(), scrubber) ctx := context.Background() - respNonRetriable := http.Response{StatusCode: 404} + respNonRetriable := http.Response{StatusCode: http.StatusNotFound} retryNum, err := retrier.DoWithRetries(ctx, func(context.Context) error { return WrapError(fmt.Errorf("test"), &respNonRetriable) diff --git a/exporter/elasticsearchexporter/bulkindexer_test.go b/exporter/elasticsearchexporter/bulkindexer_test.go index 194890e69aa6..e0213adaab79 100644 --- a/exporter/elasticsearchexporter/bulkindexer_test.go +++ b/exporter/elasticsearchexporter/bulkindexer_test.go @@ -171,7 +171,7 @@ func TestAsyncBulkIndexer_flush_error(t *testing.T) { name: "500", roundTripFunc: func(*http.Request) (*http.Response, error) { return &http.Response{ - StatusCode: 500, + StatusCode: http.StatusInternalServerError, Header: http.Header{"X-Elastic-Product": []string{"Elasticsearch"}}, Body: io.NopCloser(strings.NewReader("error")), }, nil @@ -182,7 +182,7 @@ func TestAsyncBulkIndexer_flush_error(t *testing.T) { name: "429", roundTripFunc: func(*http.Request) (*http.Response, error) { return &http.Response{ - StatusCode: 429, + StatusCode: http.StatusTooManyRequests, Header: http.Header{"X-Elastic-Product": []string{"Elasticsearch"}}, Body: io.NopCloser(strings.NewReader("error")), }, nil @@ -200,7 +200,7 @@ func TestAsyncBulkIndexer_flush_error(t *testing.T) { name: "known version conflict error", roundTripFunc: func(*http.Request) (*http.Response, error) { return &http.Response{ - StatusCode: 200, + StatusCode: http.StatusOK, Header: http.Header{"X-Elastic-Product": []string{"Elasticsearch"}}, Body: io.NopCloser(strings.NewReader( `{"items":[{"create":{"_index":".ds-metrics-generic.otel-default","status":400,"error":{"type":"version_conflict_engine_exception","reason":""}}}]}`)), diff --git a/exporter/influxdbexporter/writer.go b/exporter/influxdbexporter/writer.go index 5009b489d232..f2235d21314b 100644 --- a/exporter/influxdbexporter/writer.go +++ b/exporter/influxdbexporter/writer.go @@ -205,10 +205,10 @@ func (b *influxHTTPWriterBatch) WriteBatch(ctx context.Context) error { if err = res.Body.Close(); err != nil { return err } - switch res.StatusCode / 100 { - case 2: // Success + switch { + case res.StatusCode >= 200 && res.StatusCode < 300: // Success break - case 5: // Retryable error + case res.StatusCode >= 500 && res.StatusCode < 600: // Retryable error return fmt.Errorf("line protocol write returned %q %q", res.Status, string(body)) default: // Terminal error return consumererror.NewPermanent(fmt.Errorf("line protocol write returned %q %q", res.Status, string(body))) diff --git a/exporter/lokiexporter/exporter.go b/exporter/lokiexporter/exporter.go index 75b445838771..9c79578d34b4 100644 --- a/exporter/lokiexporter/exporter.go +++ b/exporter/lokiexporter/exporter.go @@ -90,7 +90,7 @@ func (l *lokiExporter) sendPushRequest(ctx context.Context, tenant string, reque return consumererror.NewPermanent(err) } - req, err := http.NewRequestWithContext(ctx, "POST", l.config.ClientConfig.Endpoint, bytes.NewReader(buf)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, l.config.ClientConfig.Endpoint, bytes.NewReader(buf)) if err != nil { return consumererror.NewPermanent(err) } diff --git a/exporter/prometheusremotewriteexporter/exporter.go b/exporter/prometheusremotewriteexporter/exporter.go index 04632cbcb751..aa4a58082416 100644 --- a/exporter/prometheusremotewriteexporter/exporter.go +++ b/exporter/prometheusremotewriteexporter/exporter.go @@ -292,7 +292,7 @@ func (prwe *prwExporter) execute(ctx context.Context, writeReq *prompb.WriteRequ } // Create the HTTP POST request to send to the endpoint - req, err := http.NewRequestWithContext(ctx, "POST", prwe.endpointURL.String(), bytes.NewReader(compressedData)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, prwe.endpointURL.String(), bytes.NewReader(compressedData)) if err != nil { return backoff.Permanent(consumererror.NewPermanent(err)) } diff --git a/exporter/signalfxexporter/dpclient.go b/exporter/signalfxexporter/dpclient.go index 82748947f4be..2ba8a5b5ea3d 100644 --- a/exporter/signalfxexporter/dpclient.go +++ b/exporter/signalfxexporter/dpclient.go @@ -119,7 +119,7 @@ func (s *sfxDPClient) postData(ctx context.Context, body io.Reader, headers map[ if !strings.HasSuffix(datapointURL.Path, "v2/datapoint") { datapointURL.Path = path.Join(datapointURL.Path, "v2/datapoint") } - req, err := http.NewRequestWithContext(ctx, "POST", datapointURL.String(), body) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, datapointURL.String(), body) if err != nil { return consumererror.NewPermanent(err) } diff --git a/exporter/signalfxexporter/eventclient.go b/exporter/signalfxexporter/eventclient.go index 9ba8bab68702..8bb12082cfa1 100644 --- a/exporter/signalfxexporter/eventclient.go +++ b/exporter/signalfxexporter/eventclient.go @@ -58,7 +58,7 @@ func (s *sfxEventClient) pushLogsData(ctx context.Context, ld plog.Logs) (int, e if !strings.HasSuffix(eventURL.Path, "v2/event") { eventURL.Path = path.Join(eventURL.Path, "v2/event") } - req, err := http.NewRequestWithContext(ctx, "POST", eventURL.String(), body) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, eventURL.String(), body) if err != nil { return ld.LogRecordCount(), consumererror.NewPermanent(err) } diff --git a/exporter/signalfxexporter/internal/apm/correlations/client_test.go b/exporter/signalfxexporter/internal/apm/correlations/client_test.go index 3dbad5e70b0a..023ddbbe9320 100644 --- a/exporter/signalfxexporter/internal/apm/correlations/client_test.go +++ b/exporter/signalfxexporter/internal/apm/correlations/client_test.go @@ -85,7 +85,7 @@ func makeHandler(t *testing.T, corCh chan<- *request, forcedRespCode *atomic.Val body, err := io.ReadAll(r.Body) if err != nil { - rw.WriteHeader(400) + rw.WriteHeader(http.StatusBadRequest) return } cor = &request{ diff --git a/exporter/signalfxexporter/internal/dimensions/dimclient.go b/exporter/signalfxexporter/internal/dimensions/dimclient.go index 62366b433331..ccfdf0c03fac 100644 --- a/exporter/signalfxexporter/internal/dimensions/dimclient.go +++ b/exporter/signalfxexporter/internal/dimensions/dimclient.go @@ -330,7 +330,7 @@ func (dc *DimensionClient) makePatchRequest(ctx context.Context, dim *DimensionU req, err := http.NewRequestWithContext( ctx, - "PATCH", + http.MethodPatch, strings.TrimRight(url.String(), "/")+"/_/sfxagent", bytes.NewReader(json)) if err != nil { diff --git a/exporter/splunkhecexporter/hec_worker.go b/exporter/splunkhecexporter/hec_worker.go index d89a80311247..f17ca8d5ee3a 100644 --- a/exporter/splunkhecexporter/hec_worker.go +++ b/exporter/splunkhecexporter/hec_worker.go @@ -32,7 +32,7 @@ func (hec *defaultHecWorker) send(ctx context.Context, buf buffer, headers map[s nb := make([]byte, buf.Len()) copy(nb, buf.Bytes()) bodyBuf := bytes.NewReader(nb) - req, err := http.NewRequestWithContext(ctx, "POST", hec.url.String(), bodyBuf) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, hec.url.String(), bodyBuf) if err != nil { return consumererror.NewPermanent(err) } diff --git a/exporter/sumologicexporter/exporter_test.go b/exporter/sumologicexporter/exporter_test.go index 74f67aa4f94c..3347deb7e1a9 100644 --- a/exporter/sumologicexporter/exporter_test.go +++ b/exporter/sumologicexporter/exporter_test.go @@ -166,7 +166,7 @@ func TestLogsResourceAttributesSentAsFields(t *testing.T) { func TestAllFailed(t *testing.T) { test := prepareExporterTest(t, createTestConfig(), []func(w http.ResponseWriter, req *http.Request){ func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) body := extractBody(t, req) assert.Equal(t, "Example log\nAnother example log", body) @@ -204,7 +204,7 @@ func TestPartiallyFailed(t *testing.T) { assert.Empty(t, req.Header.Get("X-Sumo-Fields")) }, func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) body := extractBody(t, req) assert.Equal(t, "Another example log", body) @@ -395,7 +395,7 @@ func TestAllMetricsFailed(t *testing.T) { name: "sent together when metrics under the same resource", callbacks: []func(w http.ResponseWriter, req *http.Request){ func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) body := extractBody(t, req) expected := `test.metric.data{test="test_value",test2="second_value"} 14500 1605534165000 @@ -421,7 +421,7 @@ gauge_metric_name{test="test_value",test2="second_value",remote_name="156955",ur name: "sent together when metrics under different resources", callbacks: []func(w http.ResponseWriter, req *http.Request){ func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) body := extractBody(t, req) expected := `test.metric.data{test="test_value",test2="second_value"} 14500 1605534165000 diff --git a/exporter/sumologicexporter/sender.go b/exporter/sumologicexporter/sender.go index 2ab24946ff29..d556b9906547 100644 --- a/exporter/sumologicexporter/sender.go +++ b/exporter/sumologicexporter/sender.go @@ -215,7 +215,7 @@ func (s *sender) handleReceiverResponse(resp *http.Response) error { // API responds with a 200 or 204 with ConentLength set to 0 when all data // has been successfully ingested. - if resp.ContentLength == 0 && (resp.StatusCode == 200 || resp.StatusCode == 204) { + if resp.ContentLength == 0 && (resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusNoContent) { return nil } @@ -229,7 +229,7 @@ func (s *sender) handleReceiverResponse(resp *http.Response) error { // API responds with a 200 or 204 with a JSON body describing what issues // were encountered when processing the sent data. switch resp.StatusCode { - case 200, 204: + case http.StatusOK, http.StatusNoContent: if resp.ContentLength < 0 { s.logger.Warn("Unknown length of server response") return nil @@ -259,7 +259,7 @@ func (s *sender) handleReceiverResponse(resp *http.Response) error { l.Warn("There was an issue sending data") return nil - case 401: + case http.StatusUnauthorized: return errUnauthorized default: diff --git a/exporter/sumologicexporter/sender_test.go b/exporter/sumologicexporter/sender_test.go index 6fdd98f0e01e..ea7ada4f09d2 100644 --- a/exporter/sumologicexporter/sender_test.go +++ b/exporter/sumologicexporter/sender_test.go @@ -329,7 +329,7 @@ func TestSendLogsSplit(t *testing.T) { func TestSendLogsSplitFailedOne(t *testing.T) { test := prepareSenderTest(t, NoCompression, []func(w http.ResponseWriter, req *http.Request){ func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) _, err := fmt.Fprintf( w, `{"id":"1TIRY-KGIVX-TPQRJ","errors":[{"code":"internal.error","message":"Internal server error."}]}`, @@ -368,7 +368,7 @@ func TestSendLogsSplitFailedOne(t *testing.T) { func TestSendLogsSplitFailedAll(t *testing.T) { test := prepareSenderTest(t, NoCompression, []func(w http.ResponseWriter, req *http.Request){ func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) body := extractBody(t, req) assert.Equal(t, "Example log", body) @@ -687,7 +687,7 @@ func TestSendLogsJsonSplit(t *testing.T) { func TestSendLogsJsonSplitFailedOne(t *testing.T) { test := prepareSenderTest(t, NoCompression, []func(w http.ResponseWriter, req *http.Request){ func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) body := extractBody(t, req) @@ -732,7 +732,7 @@ func TestSendLogsJsonSplitFailedOne(t *testing.T) { func TestSendLogsJsonSplitFailedAll(t *testing.T) { test := prepareSenderTest(t, NoCompression, []func(w http.ResponseWriter, req *http.Request){ func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) body := extractBody(t, req) @@ -1192,7 +1192,7 @@ func TestSendMetricsSplitBySource(t *testing.T) { func TestSendMetricsSplitFailedOne(t *testing.T) { test := prepareSenderTest(t, NoCompression, []func(w http.ResponseWriter, req *http.Request){ func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) body := extractBody(t, req) expected := `test.metric.data{test="test_value",test2="second_value"} 14500 1605534165000` @@ -1233,7 +1233,7 @@ func TestSendMetricsSplitFailedOne(t *testing.T) { func TestSendMetricsSplitFailedAll(t *testing.T) { test := prepareSenderTest(t, NoCompression, []func(w http.ResponseWriter, req *http.Request){ func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) body := extractBody(t, req) expected := `test.metric.data{test="test_value",test2="second_value"} 14500 1605534165000` @@ -1302,7 +1302,7 @@ func TestSendMetricsUnexpectedFormat(t *testing.T) { func TestBadRequestCausesPermanentError(t *testing.T) { test := prepareSenderTest(t, NoCompression, []func(w http.ResponseWriter, req *http.Request){ func(res http.ResponseWriter, _ *http.Request) { - res.WriteHeader(400) + res.WriteHeader(http.StatusBadRequest) }, }) test.s.config.MetricFormat = OTLPMetricFormat diff --git a/exporter/zipkinexporter/zipkin.go b/exporter/zipkinexporter/zipkin.go index 23e45bb13527..825a00277a69 100644 --- a/exporter/zipkinexporter/zipkin.go +++ b/exporter/zipkinexporter/zipkin.go @@ -74,7 +74,7 @@ func (ze *zipkinExporter) pushTraces(ctx context.Context, td ptrace.Traces) erro return consumererror.NewPermanent(fmt.Errorf("failed to push trace data via Zipkin exporter: %w", err)) } - req, err := http.NewRequestWithContext(ctx, "POST", ze.url, bytes.NewReader(body)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, ze.url, bytes.NewReader(body)) if err != nil { return fmt.Errorf("failed to push trace data via Zipkin exporter: %w", err) } diff --git a/extension/asapauthextension/extension_test.go b/extension/asapauthextension/extension_test.go index ea136105f4e4..865a1a76ec25 100644 --- a/extension/asapauthextension/extension_test.go +++ b/extension/asapauthextension/extension_test.go @@ -53,7 +53,7 @@ func TestRoundTripper(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, roundTripper) - req := &http.Request{Method: "Get", Header: map[string][]string{}} + req := &http.Request{Method: http.MethodGet, Header: map[string][]string{}} resp, err := roundTripper.RoundTrip(req) assert.NoError(t, err) authHeaderValue := resp.Header.Get("Authorization") diff --git a/extension/bearertokenauthextension/bearertokenauth_test.go b/extension/bearertokenauthextension/bearertokenauth_test.go index 4bdec8b461e6..2ed8dc81283b 100644 --- a/extension/bearertokenauthextension/bearertokenauth_test.go +++ b/extension/bearertokenauthextension/bearertokenauth_test.go @@ -57,7 +57,7 @@ func TestBearerAuthenticatorHttp(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, c) - request := &http.Request{Method: "Get"} + request := &http.Request{Method: http.MethodGet} resp, err := c.RoundTrip(request) assert.NoError(t, err) authHeaderValue := resp.Header.Get("Authorization") @@ -171,7 +171,7 @@ func TestBearerTokenFileContentUpdate(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, rt) - request := &http.Request{Method: "Get"} + request := &http.Request{Method: http.MethodGet} resp, err := rt.RoundTrip(request) assert.NoError(t, err) authHeaderValue := resp.Header.Get("Authorization") @@ -185,7 +185,7 @@ func TestBearerTokenFileContentUpdate(t *testing.T) { assert.NoError(t, err) // check if request is updated with the new token - request = &http.Request{Method: "Get"} + request = &http.Request{Method: http.MethodGet} resp, err = rt.RoundTrip(request) assert.NoError(t, err) authHeaderValue = resp.Header.Get("Authorization") @@ -196,7 +196,7 @@ func TestBearerTokenFileContentUpdate(t *testing.T) { time.Sleep(5 * time.Second) // check if request is updated with the old token - request = &http.Request{Method: "Get"} + request = &http.Request{Method: http.MethodGet} resp, err = rt.RoundTrip(request) assert.NoError(t, err) authHeaderValue = resp.Header.Get("Authorization") diff --git a/extension/opampextension/auth.go b/extension/opampextension/auth.go index 00540ad239b9..b1af4b7af078 100644 --- a/extension/opampextension/auth.go +++ b/extension/opampextension/auth.go @@ -25,7 +25,7 @@ func (h *headerCaptureRoundTripper) RoundTrip(req *http.Request) (*http.Response // Dummy response is recorded here return &http.Response{ Status: "200 OK", - StatusCode: 200, + StatusCode: http.StatusOK, Proto: "HTTP/1.0", ProtoMajor: 1, ProtoMinor: 0, diff --git a/extension/sumologicextension/extension.go b/extension/sumologicextension/extension.go index 86dee0e9a563..ae73938d14d7 100644 --- a/extension/sumologicextension/extension.go +++ b/extension/sumologicextension/extension.go @@ -460,7 +460,7 @@ func (se *SumologicExtension) registerCollector(ctx context.Context, collectorNa if res.StatusCode < 200 || res.StatusCode >= 400 { return credentials.CollectorCredentials{}, se.handleRegistrationError(res) - } else if res.StatusCode == 301 { + } else if res.StatusCode == http.StatusMovedPermanently { // Use the URL from Location header for subsequent requests. u := strings.TrimSuffix(res.Header.Get("Location"), "/") se.SetBaseURL(u) @@ -511,7 +511,7 @@ func (se *SumologicExtension) handleRegistrationError(res *http.Response) error ) // Return unrecoverable error for 4xx status codes except 429 - if res.StatusCode >= 400 && res.StatusCode < 500 && res.StatusCode != 429 { + if res.StatusCode >= 400 && res.StatusCode < 500 && res.StatusCode != http.StatusTooManyRequests { return backoff.Permanent(fmt.Errorf( "failed to register the collector, got HTTP status code: %d", res.StatusCode, diff --git a/extension/sumologicextension/extension_test.go b/extension/sumologicextension/extension_test.go index 948ee93b4279..29477f352383 100644 --- a/extension/sumologicextension/extension_test.go +++ b/extension/sumologicextension/extension_test.go @@ -118,7 +118,7 @@ func TestBasicStart(t *testing.T) { // heartbeat case 3: assert.Equal(t, heartbeatURL, req.URL.Path) - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) // should not produce any more requests default: @@ -180,7 +180,7 @@ func TestStoreCredentials(t *testing.T) { // heartbeat case 3: assert.Equal(t, heartbeatURL, req.URL.Path) - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) // should not produce any more requests default: @@ -318,7 +318,7 @@ func TestStoreCredentials_PreexistingCredentialsAreUsed(t *testing.T) { // heartbeat case 1: assert.Equal(t, heartbeatURL, req.URL.Path) - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) // metadata case 2: @@ -423,7 +423,7 @@ func TestLocalFSCredentialsStore_WorkCorrectlyForMultipleExtensions(t *testing.T // heartbeat case 3: assert.Equal(t, heartbeatURL, req.URL.Path) - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) // should not produce any more requests default: @@ -532,7 +532,7 @@ func TestRegisterEmptyCollectorName(t *testing.T) { // heartbeat case 3: assert.Equal(t, heartbeatURL, req.URL.Path) - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) // should not produce any more requests default: @@ -695,7 +695,7 @@ func TestCollectorSendsBasicAuthHeadersOnRegistration(t *testing.T) { // heartbeat case 3: assert.Equal(t, heartbeatURL, req.URL.Path) - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) // should not produce any more requests default: @@ -788,7 +788,7 @@ func TestCollectorCheckingCredentialsFoundInLocalStorage(t *testing.T) { assert.Equal(t, "Basic "+token, authHeader, "collector didn't send correct Authorization header with heartbeat request") - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) // metadata case 2: @@ -852,7 +852,7 @@ func TestCollectorCheckingCredentialsFoundInLocalStorage(t *testing.T) { assert.Equal(t, "Basic "+token, authHeader, "collector didn't send correct Authorization header with heartbeat request") - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) // metadata case 3: @@ -925,7 +925,7 @@ func TestCollectorCheckingCredentialsFoundInLocalStorage(t *testing.T) { // heartbeat case 4: - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) // should not produce any more requests default: @@ -977,7 +977,7 @@ func TestCollectorCheckingCredentialsFoundInLocalStorage(t *testing.T) { // heartbeat case 3: - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) // should not produce any more requests default: @@ -1075,7 +1075,7 @@ func TestRegisterEmptyCollectorNameWithBackoff(t *testing.T) { // heartbeat case reqNum == retriesLimit+2: assert.Equal(t, heartbeatURL, req.URL.Path) - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) // should not produce any more requests default: @@ -1190,12 +1190,12 @@ func TestRegistrationRedirect(t *testing.T) { // heartbeat case 3: assert.Equal(t, heartbeatURL, req.URL.Path) - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) // heartbeat case 4: assert.Equal(t, heartbeatURL, req.URL.Path) - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) // metadata case 5: @@ -1205,7 +1205,7 @@ func TestRegistrationRedirect(t *testing.T) { // heartbeat case 6: assert.Equal(t, heartbeatURL, req.URL.Path) - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) // should not produce any more requests default: @@ -1330,7 +1330,7 @@ func TestCollectorReregistersAfterHTTPUnathorizedFromHeartbeat(t *testing.T) { // heartbeat case 3: assert.Equal(t, heartbeatURL, req.URL.Path) - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) // heartbeat case 4: @@ -1345,7 +1345,7 @@ func TestCollectorReregistersAfterHTTPUnathorizedFromHeartbeat(t *testing.T) { default: assert.Equal(t, heartbeatURL, req.URL.Path) - w.WriteHeader(204) + w.WriteHeader(http.StatusNoContent) } }) }()) diff --git a/internal/metadataproviders/azure/metadata.go b/internal/metadataproviders/azure/metadata.go index d64576e1efb6..820974ff36b0 100644 --- a/internal/metadataproviders/azure/metadata.go +++ b/internal/metadataproviders/azure/metadata.go @@ -82,7 +82,7 @@ func (p *azureProviderImpl) Metadata(ctx context.Context) (*ComputeMetadata, err return nil, fmt.Errorf("failed to query Azure IMDS: %w", err) } defer resp.Body.Close() - if resp.StatusCode != 200 { + if resp.StatusCode != http.StatusOK { //lint:ignore ST1005 Azure is a capitalized proper noun here return nil, fmt.Errorf("Azure IMDS replied with status code: %s", resp.Status) } diff --git a/pkg/translator/jaeger/jaegerproto_to_traces_test.go b/pkg/translator/jaeger/jaegerproto_to_traces_test.go index 96eb84d64a54..ae0ea0b8911e 100644 --- a/pkg/translator/jaeger/jaegerproto_to_traces_test.go +++ b/pkg/translator/jaeger/jaegerproto_to_traces_test.go @@ -5,6 +5,7 @@ package jaeger import ( "encoding/binary" + "net/http" "strconv" "testing" "time" @@ -465,7 +466,7 @@ func TestSetInternalSpanStatus(t *testing.T) { name: "Ignore http.status_code == 200 if error set to true.", attrs: map[string]any{ tracetranslator.TagError: true, - conventions.AttributeHTTPStatusCode: 200, + conventions.AttributeHTTPStatusCode: http.StatusOK, }, status: errorStatus, attrsModifiedLen: 1, diff --git a/receiver/datadogreceiver/internal/translator/stats_translator_test.go b/receiver/datadogreceiver/internal/translator/stats_translator_test.go index fd92c98a27ea..0577345796f6 100644 --- a/receiver/datadogreceiver/internal/translator/stats_translator_test.go +++ b/receiver/datadogreceiver/internal/translator/stats_translator_test.go @@ -4,6 +4,7 @@ package translator import ( + "net/http" "strings" "testing" @@ -168,14 +169,14 @@ func TestProcessStats(t *testing.T) { Service: "service", Name: "name------", Resource: "resource", - HTTPStatusCode: 200, + HTTPStatusCode: http.StatusOK, Type: "web", }, { Service: "redis_service", Name: "name-2", Resource: "SET k v", - HTTPStatusCode: 200, + HTTPStatusCode: http.StatusOK, Type: "redis", }, }, diff --git a/testbed/mockdatasenders/mockdatadogagentexporter/traces_exporter.go b/testbed/mockdatasenders/mockdatadogagentexporter/traces_exporter.go index e884414a1cfb..6822aa2b107e 100644 --- a/testbed/mockdatasenders/mockdatadogagentexporter/traces_exporter.go +++ b/testbed/mockdatasenders/mockdatadogagentexporter/traces_exporter.go @@ -87,7 +87,7 @@ func (dd *ddExporter) pushTraces(ctx context.Context, td ptrace.Traces) error { return consumererror.NewPermanent(fmt.Errorf("failed to encode msgp: %w", err)) } - req, err := http.NewRequestWithContext(ctx, "POST", dd.endpoint, &buf) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, dd.endpoint, &buf) if err != nil { return fmt.Errorf("failed to push trace data via DD exporter: %w", err) }