Skip to content

Commit

Permalink
[chore]: enable usestdlibvars linter (part 1) (open-telemetry#36009)
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.

Notice that's only the first part, the full conformity wil be ensured
with one or two other PR as this one is already big to review

Signed-off-by: Matthieu MOREL <[email protected]>
  • Loading branch information
mmorel-35 authored and zzhlogin committed Nov 12, 2024
1 parent 45e9ef8 commit b38e65c
Show file tree
Hide file tree
Showing 53 changed files with 253 additions and 252 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func NewHTTPHealthChecker(endpoint string) *HTTPHealthChecker {
}

func (h *HTTPHealthChecker) Check(ctx context.Context) error {
req, err := http.NewRequestWithContext(ctx, "GET", h.endpoint, nil)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.endpoint, nil)
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion examples/demo/client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ func makeRequest(ctx context.Context) {
}

// Make sure we pass the context to the request to avoid broken traces.
req, err := http.NewRequestWithContext(ctx, "GET", demoServerAddr, nil)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, demoServerAddr, nil)
if err != nil {
handleErr(err, "failed to http request")
}
Expand Down
2 changes: 1 addition & 1 deletion exporter/alertmanagerexporter/alertmanager_exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ func (s *alertmanagerExporter) postAlert(ctx context.Context, payload []model.Al
return fmt.Errorf("error marshaling alert to JSON: %w", err)
}

req, err := http.NewRequestWithContext(ctx, "POST", s.endpoint, bytes.NewBuffer(msg))
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.endpoint, bytes.NewBuffer(msg))
if err != nil {
return fmt.Errorf("error creating HTTP request: %w", err)
}
Expand Down
2 changes: 1 addition & 1 deletion exporter/mezmoexporter/exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ func (m *mezmoExporter) logDataToMezmo(ld plog.Logs) error {
}

func (m *mezmoExporter) sendLinesToMezmo(post string) (errs error) {
req, _ := http.NewRequest("POST", m.config.IngestURL, strings.NewReader(post))
req, _ := http.NewRequest(http.MethodPost, m.config.IngestURL, strings.NewReader(post))
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("User-Agent", m.userAgentString)
Expand Down
4 changes: 2 additions & 2 deletions exporter/opensearchexporter/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func TestOpenSearchTraceExporter(t *testing.T) {
assert.LessOrEqualf(t, requestCount, len(tc.RequestHandlers), "Test case generated more requests than it has response for.")
tc.RequestHandlers[requestCount].ValidateReceivedDocuments(t, requestCount, docs)

w.WriteHeader(200)
w.WriteHeader(http.StatusOK)
response, _ := os.ReadFile(tc.RequestHandlers[requestCount].ResponseJSONPath)
_, err = w.Write(response)
assert.NoError(t, err)
Expand Down Expand Up @@ -246,7 +246,7 @@ func TestOpenSearchLogExporter(t *testing.T) {
assert.LessOrEqualf(t, requestCount, len(tc.RequestHandlers), "Test case generated more requests than it has response for.")
tc.RequestHandlers[requestCount].ValidateReceivedDocuments(t, requestCount, docs)

w.WriteHeader(200)
w.WriteHeader(http.StatusOK)
response, _ := os.ReadFile(tc.RequestHandlers[requestCount].ResponseJSONPath)
_, err = w.Write(response)
assert.NoError(t, 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 @@ -326,7 +326,7 @@ func (prwe *prwExporter) execute(ctx context.Context, writeReq *prompb.WriteRequ

// 429 errors are recoverable and the exporter should retry if RetryOnHTTP429 enabled
// Reference: https://github.com/prometheus/prometheus/pull/12677
if prwe.retryOnHTTP429 && resp.StatusCode == 429 {
if prwe.retryOnHTTP429 && resp.StatusCode == http.StatusTooManyRequests {
return rerr
}

Expand Down
2 changes: 1 addition & 1 deletion exporter/sapmexporter/exporter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ func TestCompression(t *testing.T) {
err = sapm.Unmarshal(payload)
assert.NoError(t, err)

w.WriteHeader(200)
w.WriteHeader(http.StatusOK)
tracesReceived = true
},
),
Expand Down
3 changes: 2 additions & 1 deletion exporter/sentryexporter/sentry_exporter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
"net/http"
"testing"

"github.com/getsentry/sentry-go"
Expand Down Expand Up @@ -380,7 +381,7 @@ func TestGenerateSpanDescriptors(t *testing.T) {
testName: "http-server",
name: "/api/users/{user_id}",
attrs: map[string]any{
conventions.AttributeHTTPMethod: "POST",
conventions.AttributeHTTPMethod: http.MethodPost,
},
spanKind: ptrace.SpanKindServer,
op: "http.server",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func makeHandler(t *testing.T, corCh chan<- *request, forcedRespCode *atomic.Val
case http.MethodGet:
match := getPathRegexp.FindStringSubmatch(r.URL.Path)
if len(match) < 3 {
rw.WriteHeader(404)
rw.WriteHeader(http.StatusNotFound)
return
}
corCh <- &request{
Expand All @@ -79,7 +79,7 @@ func makeHandler(t *testing.T, corCh chan<- *request, forcedRespCode *atomic.Val
case http.MethodPut:
match := putPathRegexp.FindStringSubmatch(r.URL.Path)
if len(match) < 4 {
rw.WriteHeader(404)
rw.WriteHeader(http.StatusNotFound)
return
}

Expand All @@ -101,7 +101,7 @@ func makeHandler(t *testing.T, corCh chan<- *request, forcedRespCode *atomic.Val
case http.MethodDelete:
match := deletePathRegexp.FindStringSubmatch(r.URL.Path)
if len(match) < 5 {
rw.WriteHeader(404)
rw.WriteHeader(http.StatusNotFound)
return
}
cor = &request{
Expand All @@ -114,13 +114,13 @@ func makeHandler(t *testing.T, corCh chan<- *request, forcedRespCode *atomic.Val
},
}
default:
rw.WriteHeader(404)
rw.WriteHeader(http.StatusNotFound)
return
}

corCh <- cor

rw.WriteHeader(200)
rw.WriteHeader(http.StatusOK)
})
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,13 @@ func makeHandler(dimCh chan<- dim, forcedResp *atomic.Int32) http.HandlerFunc {
log.Printf("Test server got request: %s", r.URL.Path)

if r.Method != "PATCH" {
rw.WriteHeader(404)
rw.WriteHeader(http.StatusNotFound)
return
}

match := patchPathRegexp.FindStringSubmatch(r.URL.Path)
if match == nil {
rw.WriteHeader(404)
rw.WriteHeader(http.StatusNotFound)
return
}

Expand All @@ -83,7 +83,7 @@ func makeHandler(dimCh chan<- dim, forcedResp *atomic.Int32) http.HandlerFunc {

dimCh <- bodyDim

rw.WriteHeader(200)
rw.WriteHeader(http.StatusOK)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func getSplunkSearchResults(user string, password string, baseURL string, jobID
logger := log.New(os.Stdout, "", log.LstdFlags)
eventURL := fmt.Sprintf("%s/services/search/jobs/%s/events?output_mode=json", baseURL, jobID)
logger.Println("URL: " + eventURL)
reqEvents, err := http.NewRequest("GET", eventURL, nil)
reqEvents, err := http.NewRequest(http.MethodGet, eventURL, nil)
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -89,7 +89,7 @@ func checkSearchJobStatusCode(user string, password string, baseURL string, jobI
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
checkReqEvents, err := http.NewRequest("GET", checkEventURL, nil)
checkReqEvents, err := http.NewRequest(http.MethodGet, checkEventURL, nil)
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -129,7 +129,7 @@ func postSearchRequest(user string, password string, baseURL string, searchQuery
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
req, err := http.NewRequest("POST", searchURL, strings.NewReader(data.Encode()))
req, err := http.NewRequest(http.MethodPost, searchURL, strings.NewReader(data.Encode()))
if err != nil {
logger.Printf("Error while preparing POST request")
panic(err)
Expand Down Expand Up @@ -172,7 +172,7 @@ func CheckMetricsFromSplunk(index string, metricName string) []any {
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr, Timeout: 10 * time.Second}
req, err := http.NewRequest("GET", apiURL, nil)
req, err := http.NewRequest(http.MethodGet, apiURL, nil)
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -209,7 +209,7 @@ func CreateAnIndexInSplunk(index string, indexType string) {
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
req, err := http.NewRequest("POST", indexURL, strings.NewReader(data.Encode()))
req, err := http.NewRequest(http.MethodPost, indexURL, strings.NewReader(data.Encode()))
if err != nil {
logger.Printf("Error while preparing POST request")
panic(err)
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 @@ -374,7 +374,7 @@ func TestSendLogsSplitFailedAll(t *testing.T) {
assert.Equal(t, "Example log", body)
},
func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(404)
w.WriteHeader(http.StatusNotFound)

body := extractBody(t, req)
assert.Equal(t, "Another example log", body)
Expand Down Expand Up @@ -741,7 +741,7 @@ func TestSendLogsJsonSplitFailedAll(t *testing.T) {
assert.Regexp(t, regex, body)
},
func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(404)
w.WriteHeader(http.StatusNotFound)

body := extractBody(t, req)

Expand Down Expand Up @@ -984,7 +984,7 @@ func TestInvalidPipeline(t *testing.T) {
func TestSendCompressGzip(t *testing.T) {
test := prepareSenderTest(t, configcompression.TypeGzip, []func(res http.ResponseWriter, req *http.Request){
func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(200)
res.WriteHeader(http.StatusOK)
if _, err := res.Write([]byte("")); err != nil {
res.WriteHeader(http.StatusInternalServerError)
assert.Fail(t, "err: %v", err)
Expand All @@ -1005,7 +1005,7 @@ func TestSendCompressGzip(t *testing.T) {
func TestSendCompressGzipDeprecated(t *testing.T) {
test := prepareSenderTest(t, "default", []func(res http.ResponseWriter, req *http.Request){
func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(200)
res.WriteHeader(http.StatusOK)
if _, err := res.Write([]byte("")); err != nil {
res.WriteHeader(http.StatusInternalServerError)
assert.Fail(t, "err: %v", err)
Expand All @@ -1026,7 +1026,7 @@ func TestSendCompressGzipDeprecated(t *testing.T) {
func TestSendCompressZstd(t *testing.T) {
test := prepareSenderTest(t, configcompression.TypeZstd, []func(res http.ResponseWriter, req *http.Request){
func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(200)
res.WriteHeader(http.StatusOK)
if _, err := res.Write([]byte("")); err != nil {
res.WriteHeader(http.StatusInternalServerError)
assert.Fail(t, "err: %v", err)
Expand All @@ -1047,7 +1047,7 @@ func TestSendCompressZstd(t *testing.T) {
func TestSendCompressDeflate(t *testing.T) {
test := prepareSenderTest(t, configcompression.TypeDeflate, []func(res http.ResponseWriter, req *http.Request){
func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(200)
res.WriteHeader(http.StatusOK)
if _, err := res.Write([]byte("")); err != nil {
res.WriteHeader(http.StatusInternalServerError)
assert.Fail(t, "err: %v", err)
Expand Down Expand Up @@ -1240,7 +1240,7 @@ func TestSendMetricsSplitFailedAll(t *testing.T) {
assert.Equal(t, expected, body)
},
func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(404)
w.WriteHeader(http.StatusNotFound)

body := extractBody(t, req)
expected := `` +
Expand Down
2 changes: 1 addition & 1 deletion exporter/zipkinexporter/zipkin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ func (r *mockZipkinReporter) Flush() error {
return err
}

req, err := http.NewRequest("POST", r.url, bytes.NewReader(body))
req, err := http.NewRequest(http.MethodPost, r.url, bytes.NewReader(body))
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion extension/headerssetterextension/extension_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func TestRoundTripper(t *testing.T) {
Metadata: tt.metadata,
},
)
req, err := http.NewRequestWithContext(ctx, "GET", "", nil)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "", nil)
assert.NoError(t, err)
assert.NotNil(t, req)

Expand Down
4 changes: 2 additions & 2 deletions extension/oauth2clientauthextension/extension_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ func TestOAuth2PerRPCCredentials(t *testing.T) {

func TestFailContactingOAuth(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(200)
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("not-json"))
assert.NoError(t, err)
}))
Expand Down Expand Up @@ -306,7 +306,7 @@ func TestFailContactingOAuth(t *testing.T) {
Transport: roundTripper,
}

req, err := http.NewRequest("POST", "http://example.com/", nil)
req, err := http.NewRequest(http.MethodPost, "http://example.com/", nil)
require.NoError(t, err)
_, err = client.Do(req)
assert.ErrorIs(t, err, errFailedToGetSecurityToken)
Expand Down
2 changes: 1 addition & 1 deletion extension/opampextension/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func makeHeadersFunc(logger *zap.Logger, serverCfg *OpAMPServer, host component.
// This is a workaround while websocket authentication is being worked on.
// Currently, we are waiting on the auth module to be stabilized.
// See for more info: https://github.com/open-telemetry/opentelemetry-collector/issues/10864
dummyReq, err := http.NewRequest("GET", "http://example.com", nil)
dummyReq, err := http.NewRequest(http.MethodGet, "http://example.com", nil)
if err != nil {
logger.Error("Failed to create dummy request for authentication.", zap.Error(err))
return h
Expand Down
4 changes: 2 additions & 2 deletions extension/sigv4authextension/extension_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,10 @@ func TestGetCredsProviderFromConfig(t *testing.T) {
}

func TestCloneRequest(t *testing.T) {
req1, err := http.NewRequest("GET", "https://example.com", nil)
req1, err := http.NewRequest(http.MethodGet, "https://example.com", nil)
assert.NoError(t, err)

req2, err := http.NewRequest("GET", "https://example.com", nil)
req2, err := http.NewRequest(http.MethodGet, "https://example.com", nil)
assert.NoError(t, err)
req2.Header.Add("Header1", "val1")

Expand Down
20 changes: 10 additions & 10 deletions extension/sigv4authextension/signingroundtripper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func TestRoundTrip(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, body, string(content))

w.WriteHeader(200)
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
serverURL, _ := url.Parse(server.URL)
Expand All @@ -79,7 +79,7 @@ func TestRoundTrip(t *testing.T) {
assert.NoError(t, err)

newBody := strings.NewReader(body)
req, err := http.NewRequest("POST", serverURL.String(), newBody)
req, err := http.NewRequest(http.MethodPost, serverURL.String(), newBody)
assert.NoError(t, err)

res, err := rt.RoundTrip(req)
Expand All @@ -95,19 +95,19 @@ func TestRoundTrip(t *testing.T) {
}

func TestInferServiceAndRegion(t *testing.T) {
req1, err := http.NewRequest("GET", "https://example.com", nil)
req1, err := http.NewRequest(http.MethodGet, "https://example.com", nil)
assert.NoError(t, err)

req2, err := http.NewRequest("GET", "https://aps-workspaces.us-east-1.amazonaws.com/workspaces/ws-XXX/api/v1/remote_write", nil)
req2, err := http.NewRequest(http.MethodGet, "https://aps-workspaces.us-east-1.amazonaws.com/workspaces/ws-XXX/api/v1/remote_write", nil)
assert.NoError(t, err)

req3, err := http.NewRequest("GET", "https://search-my-domain.us-east-1.es.amazonaws.com/_search?q=house", nil)
req3, err := http.NewRequest(http.MethodGet, "https://search-my-domain.us-east-1.es.amazonaws.com/_search?q=house", nil)
assert.NoError(t, err)

req4, err := http.NewRequest("GET", "https://example.com", nil)
req4, err := http.NewRequest(http.MethodGet, "https://example.com", nil)
assert.NoError(t, err)

req5, err := http.NewRequest("GET", "https://aps-workspaces.us-east-1.amazonaws.com/workspaces/ws-XXX/api/v1/remote_write", nil)
req5, err := http.NewRequest(http.MethodGet, "https://aps-workspaces.us-east-1.amazonaws.com/workspaces/ws-XXX/api/v1/remote_write", nil)
assert.NoError(t, err)

tests := []struct {
Expand Down Expand Up @@ -172,13 +172,13 @@ func TestInferServiceAndRegion(t *testing.T) {
}

func TestHashPayload(t *testing.T) {
req1, err := http.NewRequest("GET", "https://example.com", nil)
req1, err := http.NewRequest(http.MethodGet, "https://example.com", nil)
assert.NoError(t, err)

req2, err := http.NewRequest("GET", "https://example.com", bytes.NewReader([]byte("This is a test.")))
req2, err := http.NewRequest(http.MethodGet, "https://example.com", bytes.NewReader([]byte("This is a test.")))
assert.NoError(t, err)

req3, err := http.NewRequest("GET", "https://example.com", nil)
req3, err := http.NewRequest(http.MethodGet, "https://example.com", nil)
assert.NoError(t, err)
req3.GetBody = func() (io.ReadCloser, error) { return nil, errors.New("this will always fail") }

Expand Down
Loading

0 comments on commit b38e65c

Please sign in to comment.