Skip to content

Commit

Permalink
[chore]: enable usestdlibvars linter (part 2) (open-telemetry#36101)
Browse files Browse the repository at this point in the history
#### Description

[usestdlibvars](https://golangci-lint.run/usage/linters/#usestdlibvars)
is a linter that detect the possibility to use variables/constants from
the Go standard library.

Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
  • Loading branch information
mmorel-35 authored Oct 31, 2024
1 parent 26c6f7b commit 92e336e
Show file tree
Hide file tree
Showing 27 changed files with 67 additions and 63 deletions.
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ linters:
- unconvert
- unparam
- unused
- usestdlibvars
- wastedassign

issues:
Expand Down
3 changes: 2 additions & 1 deletion exporter/datadogexporter/internal/clientutil/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions exporter/elasticsearchexporter/bulkindexer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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":""}}}]}`)),
Expand Down
6 changes: 3 additions & 3 deletions exporter/influxdbexporter/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
Expand Down
2 changes: 1 addition & 1 deletion exporter/lokiexporter/exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion exporter/prometheusremotewriteexporter/exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down
2 changes: 1 addition & 1 deletion exporter/signalfxexporter/dpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion exporter/signalfxexporter/eventclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down
2 changes: 1 addition & 1 deletion exporter/signalfxexporter/internal/dimensions/dimclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion exporter/splunkhecexporter/hec_worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
8 changes: 4 additions & 4 deletions exporter/sumologicexporter/exporter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
6 changes: 3 additions & 3 deletions exporter/sumologicexporter/sender.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down
14 changes: 7 additions & 7 deletions exporter/sumologicexporter/sender_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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."}]}`,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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`
Expand Down Expand Up @@ -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`
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion exporter/zipkinexporter/zipkin.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion extension/asapauthextension/extension_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
8 changes: 4 additions & 4 deletions extension/bearertokenauthextension/bearertokenauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand All @@ -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")
Expand All @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion extension/opampextension/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions extension/sumologicextension/extension.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down
Loading

0 comments on commit 92e336e

Please sign in to comment.