From 54a9acd338b753ca8ee8ed6e063364958f10402c Mon Sep 17 00:00:00 2001 From: hc-github-team-nomad-core <82989552+hc-github-team-nomad-core@users.noreply.github.com> Date: Wed, 26 Jul 2023 10:39:00 -0500 Subject: [PATCH] Backport of chore(lint): use Go stdlib variables for HTTP methods and status codes into release/1.5.x (#18073) Co-authored-by: Ville Vesilehto Co-authored-by: James Rasell --- .golangci.yml | 1 + client/allocrunner/checks_hook_test.go | 4 +- client/fingerprint/env_azure.go | 4 +- client/fingerprint/env_azure_test.go | 2 +- client/fingerprint/env_digitalocean_test.go | 2 +- client/fingerprint/env_gce.go | 4 +- client/fingerprint/env_gce_test.go | 2 +- client/serviceregistration/checks/client.go | 4 +- .../serviceregistration/checks/client_test.go | 8 +- command/agent/acl_endpoint.go | 18 +-- command/agent/acl_endpoint_test.go | 30 ++--- command/agent/agent_endpoint.go | 10 +- command/agent/agent_endpoint_test.go | 116 +++++++++--------- command/agent/alloc_endpoint.go | 4 +- command/agent/alloc_endpoint_test.go | 60 ++++----- command/agent/csi_endpoint_test.go | 16 +-- command/agent/deployment_endpoint_test.go | 16 +-- command/agent/eval_endpoint.go | 4 +- command/agent/eval_endpoint_test.go | 18 +-- command/agent/event_endpoint_test.go | 4 +- command/agent/fs_endpoint_test.go | 48 ++++---- command/agent/http.go | 10 +- command/agent/http_test.go | 56 ++++----- command/agent/job_endpoint.go | 22 ++-- command/agent/job_endpoint_test.go | 80 ++++++------ command/agent/metrics_endpoint.go | 2 +- command/agent/metrics_endpoint_test.go | 12 +- command/agent/namespace_endpoint.go | 10 +- command/agent/namespace_endpoint_test.go | 10 +- command/agent/node_endpoint.go | 14 +-- command/agent/node_endpoint_test.go | 22 ++-- command/agent/operator_endpoint.go | 18 +-- command/agent/operator_endpoint_oss.go | 4 +- command/agent/operator_endpoint_test.go | 38 +++--- command/agent/region_endpoint.go | 2 +- command/agent/region_endpoint_test.go | 2 +- command/agent/scaling_endpoint.go | 4 +- command/agent/scaling_endpoint_test.go | 8 +- command/agent/search_endpoint_test.go | 48 ++++---- command/agent/stats_endpoint_test.go | 8 +- command/agent/status_endpoint.go | 4 +- command/agent/status_endpoint_test.go | 4 +- command/agent/system_endpoint.go | 4 +- command/agent/system_endpoint_test.go | 4 +- command/agent/testagent.go | 2 +- command/operator_debug.go | 4 +- command/operator_debug_test.go | 2 +- testutil/server.go | 4 +- 48 files changed, 387 insertions(+), 386 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index cc7e7a47669..1e7da83b3ca 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -100,5 +100,6 @@ linters: # - errchkjson (todo) # - errorlint (todo) - exportloopref + - usestdlibvars fast: false diff --git a/client/allocrunner/checks_hook_test.go b/client/allocrunner/checks_hook_test.go index b204c2e8059..2a85560fe9d 100644 --- a/client/allocrunner/checks_hook_test.go +++ b/client/allocrunner/checks_hook_test.go @@ -127,13 +127,13 @@ func allocWithDifferentNomadChecks(id, addr, port string) *structs.Allocation { var checkHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/fail": - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) _, _ = io.WriteString(w, "500 problem") case "/hang": time.Sleep(2 * time.Second) _, _ = io.WriteString(w, "too slow") default: - w.WriteHeader(200) + w.WriteHeader(http.StatusOK) _, _ = io.WriteString(w, "200 ok") } }) diff --git a/client/fingerprint/env_azure.go b/client/fingerprint/env_azure.go index c49b6cfd7ed..20ed6a7a73a 100644 --- a/client/fingerprint/env_azure.go +++ b/client/fingerprint/env_azure.go @@ -79,7 +79,7 @@ func (f *EnvAzureFingerprint) Get(attribute string, format string) (string, erro } req := &http.Request{ - Method: "GET", + Method: http.MethodGet, URL: parsedURL, Header: http.Header{ "Metadata": []string{"true"}, @@ -103,7 +103,7 @@ func (f *EnvAzureFingerprint) Get(attribute string, format string) (string, erro return "", err } - if res.StatusCode >= 400 { + if res.StatusCode >= http.StatusBadRequest { return "", ReqError{res.StatusCode} } diff --git a/client/fingerprint/env_azure_test.go b/client/fingerprint/env_azure_test.go index bc6d7dd4528..5eb73e2a4fb 100644 --- a/client/fingerprint/env_azure_test.go +++ b/client/fingerprint/env_azure_test.go @@ -88,7 +88,7 @@ func testFingerprint_Azure(t *testing.T, withExternalIp bool) { } if !found { - w.WriteHeader(404) + w.WriteHeader(http.StatusNotFound) } })) defer ts.Close() diff --git a/client/fingerprint/env_digitalocean_test.go b/client/fingerprint/env_digitalocean_test.go index a7d82eaf63d..dee50c1441e 100644 --- a/client/fingerprint/env_digitalocean_test.go +++ b/client/fingerprint/env_digitalocean_test.go @@ -74,7 +74,7 @@ func TestFingerprint_DigitalOcean(t *testing.T) { } if !found { - w.WriteHeader(404) + w.WriteHeader(http.StatusNotFound) } })) defer ts.Close() diff --git a/client/fingerprint/env_gce.go b/client/fingerprint/env_gce.go index 9a4900093f2..890760cd4f7 100644 --- a/client/fingerprint/env_gce.go +++ b/client/fingerprint/env_gce.go @@ -94,7 +94,7 @@ func (f *EnvGCEFingerprint) Get(attribute string, recursive bool) (string, error } req := &http.Request{ - Method: "GET", + Method: http.MethodGet, URL: parsedUrl, Header: http.Header{ "Metadata-Flavor": []string{"Google"}, @@ -118,7 +118,7 @@ func (f *EnvGCEFingerprint) Get(attribute string, recursive bool) (string, error return "", err } - if res.StatusCode >= 400 { + if res.StatusCode >= http.StatusBadRequest { return "", ReqError{res.StatusCode} } diff --git a/client/fingerprint/env_gce_test.go b/client/fingerprint/env_gce_test.go index c4228bcadda..b73564f3d4f 100644 --- a/client/fingerprint/env_gce_test.go +++ b/client/fingerprint/env_gce_test.go @@ -85,7 +85,7 @@ func testFingerprint_GCE(t *testing.T, withExternalIp bool) { } if !found { - w.WriteHeader(404) + w.WriteHeader(http.StatusNotFound) } })) defer ts.Close() diff --git a/client/serviceregistration/checks/client.go b/client/serviceregistration/checks/client.go index 7a1caf2069e..20c2aaa55d6 100644 --- a/client/serviceregistration/checks/client.go +++ b/client/serviceregistration/checks/client.go @@ -200,11 +200,11 @@ func (c *checker) checkHTTP(ctx context.Context, qc *QueryContext, q *Query) *st qr.StatusCode = result.StatusCode switch { - case result.StatusCode == 200: + case result.StatusCode == http.StatusOK: qr.Status = structs.CheckSuccess qr.Output = "nomad: http ok" return qr - case result.StatusCode < 400: + case result.StatusCode < http.StatusBadRequest: qr.Status = structs.CheckSuccess default: qr.Status = structs.CheckFailure diff --git a/client/serviceregistration/checks/client_test.go b/client/serviceregistration/checks/client_test.go index c76b076c76b..662084fc301 100644 --- a/client/serviceregistration/checks/client_test.go +++ b/client/serviceregistration/checks/client_test.go @@ -51,19 +51,19 @@ func TestChecker_Do_HTTP(t *testing.T) { switch r.URL.Path { case "/fail": - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) _, _ = io.WriteString(w, "500 problem") case "/hang": time.Sleep(1 * time.Second) _, _ = io.WriteString(w, "too slow") case "/long-fail": - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) _, _ = io.WriteString(w, tooLong) case "/long-not-fail": - w.WriteHeader(201) + w.WriteHeader(http.StatusCreated) _, _ = io.WriteString(w, tooLong) default: - w.WriteHeader(200) + w.WriteHeader(http.StatusOK) _, _ = io.WriteString(w, "200 ok") } })) diff --git a/command/agent/acl_endpoint.go b/command/agent/acl_endpoint.go index 089ba73d890..2ee4cad97e7 100644 --- a/command/agent/acl_endpoint.go +++ b/command/agent/acl_endpoint.go @@ -9,7 +9,7 @@ import ( ) func (s *HTTPServer) ACLPoliciesRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } @@ -36,11 +36,11 @@ func (s *HTTPServer) ACLPolicySpecificRequest(resp http.ResponseWriter, req *htt return nil, CodedError(400, "Missing Policy Name") } switch req.Method { - case "GET": + case http.MethodGet: return s.aclPolicyQuery(resp, req, name) - case "PUT", "POST": + case http.MethodPut, http.MethodPost: return s.aclPolicyUpdate(resp, req, name) - case "DELETE": + case http.MethodDelete: return s.aclPolicyDelete(resp, req, name) default: return nil, CodedError(405, ErrInvalidMethod) @@ -112,7 +112,7 @@ func (s *HTTPServer) aclPolicyDelete(resp http.ResponseWriter, req *http.Request } func (s *HTTPServer) ACLTokensRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } @@ -184,11 +184,11 @@ func (s *HTTPServer) aclTokenCrud(resp http.ResponseWriter, req *http.Request, } switch req.Method { - case "GET": + case http.MethodGet: return s.aclTokenQuery(resp, req, tokenAccessor) - case "PUT", "POST": + case http.MethodPut, http.MethodPost: return s.aclTokenUpdate(resp, req, tokenAccessor) - case "DELETE": + case http.MethodDelete: return s.aclTokenDelete(resp, req, tokenAccessor) default: return nil, CodedError(405, ErrInvalidMethod) @@ -217,7 +217,7 @@ func (s *HTTPServer) aclTokenQuery(resp http.ResponseWriter, req *http.Request, } func (s *HTTPServer) aclTokenSelf(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } args := structs.ResolveACLTokenRequest{} diff --git a/command/agent/acl_endpoint_test.go b/command/agent/acl_endpoint_test.go index ff86a076195..b002a8f2af3 100644 --- a/command/agent/acl_endpoint_test.go +++ b/command/agent/acl_endpoint_test.go @@ -39,7 +39,7 @@ func TestHTTP_ACLPolicyList(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/acl/policies", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/acl/policies", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -88,7 +88,7 @@ func TestHTTP_ACLPolicyQuery(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/acl/policy/"+p1.Name, nil) + req, err := http.NewRequest(http.MethodGet, "/v1/acl/policy/"+p1.Name, nil) if err != nil { t.Fatalf("err: %v", err) } @@ -126,7 +126,7 @@ func TestHTTP_ACLPolicyCreate(t *testing.T) { // Make the HTTP request p1 := mock.ACLPolicy() buf := encodeReq(p1) - req, err := http.NewRequest("PUT", "/v1/acl/policy/"+p1.Name, buf) + req, err := http.NewRequest(http.MethodPut, "/v1/acl/policy/"+p1.Name, buf) must.NoError(t, err) respW := httptest.NewRecorder() @@ -187,7 +187,7 @@ func TestHTTP_ACLPolicyDelete(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("DELETE", "/v1/acl/policy/"+p1.Name, nil) + req, err := http.NewRequest(http.MethodDelete, "/v1/acl/policy/"+p1.Name, nil) if err != nil { t.Fatalf("err: %v", err) } @@ -220,7 +220,7 @@ func TestHTTP_ACLTokenBootstrap(t *testing.T) { } httpTest(t, conf, func(s *TestAgent) { // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/acl/bootstrap", nil) + req, err := http.NewRequest(http.MethodPut, "/v1/acl/bootstrap", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -259,7 +259,7 @@ func TestHTTP_ACLTokenBootstrapOperator(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/acl/bootstrap", buf) + req, err := http.NewRequest(http.MethodPut, "/v1/acl/bootstrap", buf) if err != nil { t.Fatalf("err: %v", err) } @@ -309,7 +309,7 @@ func TestHTTP_ACLTokenList(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/acl/tokens", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/acl/tokens", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -360,7 +360,7 @@ func TestHTTP_ACLTokenQuery(t *testing.T) { out := resp.Tokens[0] // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/acl/token/"+out.AccessorID, nil) + req, err := http.NewRequest(http.MethodGet, "/v1/acl/token/"+out.AccessorID, nil) if err != nil { t.Fatalf("err: %v", err) } @@ -409,7 +409,7 @@ func TestHTTP_ACLTokenSelf(t *testing.T) { out := resp.Tokens[0] // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/acl/token/self", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/acl/token/self", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -446,7 +446,7 @@ func TestHTTP_ACLTokenCreate(t *testing.T) { p1 := mock.ACLToken() p1.AccessorID = "" buf := encodeReq(p1) - req, err := http.NewRequest("PUT", "/v1/acl/token", buf) + req, err := http.NewRequest(http.MethodPut, "/v1/acl/token", buf) if err != nil { t.Fatalf("err: %v", err) } @@ -488,7 +488,7 @@ func TestHTTP_ACLTokenCreateExpirationTTL(t *testing.T) { "Global": false }` - req, err := http.NewRequest("PUT", "/v1/acl/token", bytes.NewReader([]byte(aclToken))) + req, err := http.NewRequest(http.MethodPut, "/v1/acl/token", bytes.NewReader([]byte(aclToken))) must.NoError(t, err) respW := httptest.NewRecorder() @@ -534,7 +534,7 @@ func TestHTTP_ACLTokenDelete(t *testing.T) { ID := resp.Tokens[0].AccessorID // Make the HTTP request - req, err := http.NewRequest("DELETE", "/v1/acl/token/"+ID, nil) + req, err := http.NewRequest(http.MethodDelete, "/v1/acl/token/"+ID, nil) if err != nil { t.Fatalf("err: %v", err) } @@ -582,7 +582,7 @@ func TestHTTP_OneTimeToken(t *testing.T) { // Make a HTTP request to get a one-time token - req, err := http.NewRequest("POST", "/v1/acl/token/onetime", nil) + req, err := http.NewRequest(http.MethodPost, "/v1/acl/token/onetime", nil) require.NoError(t, err) req.Header.Set("X-Nomad-Token", aclSecret) respW := httptest.NewRecorder() @@ -599,7 +599,7 @@ func TestHTTP_OneTimeToken(t *testing.T) { buf := encodeReq(structs.OneTimeTokenExchangeRequest{ OneTimeSecretID: ott.OneTimeToken.OneTimeSecretID}) - req, err = http.NewRequest("POST", "/v1/acl/token/onetime/exchange", buf) + req, err = http.NewRequest(http.MethodPost, "/v1/acl/token/onetime/exchange", buf) require.NoError(t, err) respW = httptest.NewRecorder() @@ -615,7 +615,7 @@ func TestHTTP_OneTimeToken(t *testing.T) { buf = encodeReq(structs.OneTimeTokenExchangeRequest{ OneTimeSecretID: ott.OneTimeToken.OneTimeSecretID}) - req, err = http.NewRequest("POST", "/v1/acl/token/onetime/exchange", buf) + req, err = http.NewRequest(http.MethodPost, "/v1/acl/token/onetime/exchange", buf) require.NoError(t, err) respW = httptest.NewRecorder() diff --git a/command/agent/agent_endpoint.go b/command/agent/agent_endpoint.go index 21df7c3b3b2..7a9784b3c2c 100644 --- a/command/agent/agent_endpoint.go +++ b/command/agent/agent_endpoint.go @@ -56,7 +56,7 @@ func nomadMember(m serf.Member) Member { } func (s *HTTPServer) AgentSelfRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } @@ -128,7 +128,7 @@ func (s *HTTPServer) AgentJoinRequest(resp http.ResponseWriter, req *http.Reques } func (s *HTTPServer) AgentMembersRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } @@ -415,9 +415,9 @@ func (s *HTTPServer) agentPprof(reqType pprof.ReqType, resp http.ResponseWriter, // servers for a given agent. func (s *HTTPServer) AgentServersRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { switch req.Method { - case "PUT", "POST": + case http.MethodPut, http.MethodPost: return s.updateServers(resp, req) - case "GET": + case http.MethodGet: return s.listServers(resp, req) default: return nil, CodedError(405, ErrInvalidMethod) @@ -549,7 +549,7 @@ type joinResult struct { } func (s *HTTPServer) HealthRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } diff --git a/command/agent/agent_endpoint_test.go b/command/agent/agent_endpoint_test.go index 592649f5f49..b265adb656b 100644 --- a/command/agent/agent_endpoint_test.go +++ b/command/agent/agent_endpoint_test.go @@ -38,7 +38,7 @@ func TestHTTP_AgentSelf(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/agent/self", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/self", nil) require.NoError(err) respW := httptest.NewRecorder() @@ -103,7 +103,7 @@ func TestHTTP_AgentSelf_ACL(t *testing.T) { state := s.Agent.server.State() // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/agent/self", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/self", nil) require.Nil(err) // Try request without a token and expect failure @@ -159,7 +159,7 @@ func TestHTTP_AgentJoin(t *testing.T) { addr := net.JoinHostPort(member.Addr.String(), strconv.Itoa(int(member.Port))) // Make the HTTP request - req, err := http.NewRequest("PUT", + req, err := http.NewRequest(http.MethodPut, fmt.Sprintf("/v1/agent/join?address=%s&address=%s", addr, addr), nil) if err != nil { t.Fatalf("err: %v", err) @@ -187,7 +187,7 @@ func TestHTTP_AgentMembers(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/agent/members", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/members", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -215,7 +215,7 @@ func TestHTTP_AgentMembers_ACL(t *testing.T) { state := s.Agent.server.State() // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/agent/members", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/members", nil) require.Nil(err) // Try request without a token and expect failure @@ -266,7 +266,7 @@ func TestHTTP_AgentMonitor(t *testing.T) { t.Run("invalid log_json parameter", func(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { - req, err := http.NewRequest("GET", "/v1/agent/monitor?log_json=no", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/monitor?log_json=no", nil) require.NoError(t, err) resp := newClosableRecorder() @@ -279,7 +279,7 @@ func TestHTTP_AgentMonitor(t *testing.T) { t.Run("unknown log_level", func(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { - req, err := http.NewRequest("GET", "/v1/agent/monitor?log_level=unknown", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/monitor?log_level=unknown", nil) require.NoError(t, err) resp := newClosableRecorder() @@ -292,7 +292,7 @@ func TestHTTP_AgentMonitor(t *testing.T) { t.Run("check for specific log level", func(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { - req, err := http.NewRequest("GET", "/v1/agent/monitor?log_level=warn", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/monitor?log_level=warn", nil) require.NoError(t, err) resp := newClosableRecorder() defer resp.Close() @@ -326,7 +326,7 @@ func TestHTTP_AgentMonitor(t *testing.T) { t.Run("plain output", func(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { - req, err := http.NewRequest("GET", "/v1/agent/monitor?log_level=debug&plain=true", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/monitor?log_level=debug&plain=true", nil) require.NoError(t, err) resp := newClosableRecorder() defer resp.Close() @@ -360,7 +360,7 @@ func TestHTTP_AgentMonitor(t *testing.T) { t.Run("logs for a specific node", func(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { - req, err := http.NewRequest("GET", "/v1/agent/monitor?log_level=warn&node_id="+s.client.NodeID(), nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/monitor?log_level=warn&node_id="+s.client.NodeID(), nil) require.NoError(t, err) resp := newClosableRecorder() defer resp.Close() @@ -400,7 +400,7 @@ func TestHTTP_AgentMonitor(t *testing.T) { t.Run("logs for a local client with no server running on agent", func(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { - req, err := http.NewRequest("GET", "/v1/agent/monitor?log_level=warn", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/monitor?log_level=warn", nil) require.NoError(t, err) resp := newClosableRecorder() defer resp.Close() @@ -505,7 +505,7 @@ func TestAgent_PprofRequest_Permissions(t *testing.T) { httpTest(t, cb, func(s *TestAgent) { state := s.Agent.server.State() url := "/v1/agent/pprof/cmdline" - req, err := http.NewRequest("GET", url, nil) + req, err := http.NewRequest(http.MethodGet, url, nil) require.NoError(t, err) respW := httptest.NewRecorder() @@ -602,7 +602,7 @@ func TestAgent_PprofRequest(t *testing.T) { s.Agent.server = nil } - req, err := http.NewRequest("GET", url, nil) + req, err := http.NewRequest(http.MethodGet, url, nil) require.NoError(t, err) respW := httptest.NewRecorder() @@ -643,7 +643,7 @@ func TestHTTP_AgentForceLeave(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/agent/force-leave?node=foo", nil) + req, err := http.NewRequest(http.MethodPut, "/v1/agent/force-leave?node=foo", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -665,7 +665,7 @@ func TestHTTP_AgentForceLeave_ACL(t *testing.T) { state := s.Agent.server.State() // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/agent/force-leave?node=foo", nil) + req, err := http.NewRequest(http.MethodPut, "/v1/agent/force-leave?node=foo", nil) require.Nil(err) // Try request without a token and expect failure @@ -734,7 +734,7 @@ func TestHTTP_AgentSetServers(t *testing.T) { }) // Create the request - req, err := http.NewRequest("PUT", "/v1/agent/servers", nil) + req, err := http.NewRequest(http.MethodPut, "/v1/agent/servers", nil) require.Nil(err) // Send the request @@ -744,7 +744,7 @@ func TestHTTP_AgentSetServers(t *testing.T) { require.Contains(err.Error(), "missing server address") // Create a valid request - req, err = http.NewRequest("PUT", "/v1/agent/servers?address=127.0.0.1%3A4647&address=127.0.0.2%3A4647&address=127.0.0.3%3A4647", nil) + req, err = http.NewRequest(http.MethodPut, "/v1/agent/servers?address=127.0.0.1%3A4647&address=127.0.0.2%3A4647&address=127.0.0.3%3A4647", nil) require.Nil(err) // Send the request which should fail @@ -753,7 +753,7 @@ func TestHTTP_AgentSetServers(t *testing.T) { require.NotNil(err) // Retrieve the servers again - req, err = http.NewRequest("GET", "/v1/agent/servers", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/agent/servers", nil) require.Nil(err) respW = httptest.NewRecorder() @@ -799,7 +799,7 @@ func TestHTTP_AgentSetServers_ACL(t *testing.T) { // Make the HTTP request path := fmt.Sprintf("/v1/agent/servers?address=%s", url.QueryEscape(s.GetConfig().AdvertiseAddrs.RPC)) - req, err := http.NewRequest("PUT", path, nil) + req, err := http.NewRequest(http.MethodPut, path, nil) require.Nil(err) // Try request without a token and expect failure @@ -849,7 +849,7 @@ func TestHTTP_AgentListServers_ACL(t *testing.T) { state := s.Agent.server.State() // Create list request - req, err := http.NewRequest("GET", "/v1/agent/servers", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/servers", nil) require.Nil(err) expected := []string{ @@ -914,7 +914,7 @@ func TestHTTP_AgentListKeys(t *testing.T) { httpTest(t, func(c *Config) { c.Server.EncryptKey = key1 }, func(s *TestAgent) { - req, err := http.NewRequest("GET", "/v1/agent/keyring/list", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/keyring/list", nil) if err != nil { t.Fatalf("err: %s", err) } @@ -941,7 +941,7 @@ func TestHTTP_AgentListKeys_ACL(t *testing.T) { state := s.Agent.server.State() // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/agent/keyring/list", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/keyring/list", nil) require.Nil(err) // Try request without a token and expect failure @@ -1000,7 +1000,7 @@ func TestHTTP_AgentInstallKey(t *testing.T) { if err != nil { t.Fatalf("err: %v", err) } - req, err := http.NewRequest("GET", "/v1/agent/keyring/install", bytes.NewReader(b)) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/keyring/install", bytes.NewReader(b)) if err != nil { t.Fatalf("err: %s", err) } @@ -1010,7 +1010,7 @@ func TestHTTP_AgentInstallKey(t *testing.T) { if err != nil { t.Fatalf("err: %s", err) } - req, err = http.NewRequest("GET", "/v1/agent/keyring/list", bytes.NewReader(b)) + req, err = http.NewRequest(http.MethodGet, "/v1/agent/keyring/list", bytes.NewReader(b)) if err != nil { t.Fatalf("err: %s", err) } @@ -1041,7 +1041,7 @@ func TestHTTP_AgentRemoveKey(t *testing.T) { t.Fatalf("err: %v", err) } - req, err := http.NewRequest("GET", "/v1/agent/keyring/install", bytes.NewReader(b)) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/keyring/install", bytes.NewReader(b)) if err != nil { t.Fatalf("err: %s", err) } @@ -1051,7 +1051,7 @@ func TestHTTP_AgentRemoveKey(t *testing.T) { t.Fatalf("err: %s", err) } - req, err = http.NewRequest("GET", "/v1/agent/keyring/remove", bytes.NewReader(b)) + req, err = http.NewRequest(http.MethodGet, "/v1/agent/keyring/remove", bytes.NewReader(b)) if err != nil { t.Fatalf("err: %s", err) } @@ -1060,7 +1060,7 @@ func TestHTTP_AgentRemoveKey(t *testing.T) { t.Fatalf("err: %s", err) } - req, err = http.NewRequest("GET", "/v1/agent/keyring/list", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/agent/keyring/list", nil) if err != nil { t.Fatalf("err: %s", err) } @@ -1084,7 +1084,7 @@ func TestHTTP_AgentHealth_Ok(t *testing.T) { httpACLTest(t, nil, func(s *TestAgent) { // No ?type= { - req, err := http.NewRequest("GET", "/v1/agent/health", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/health", nil) require.Nil(err) respW := httptest.NewRecorder() @@ -1103,7 +1103,7 @@ func TestHTTP_AgentHealth_Ok(t *testing.T) { // type=client { - req, err := http.NewRequest("GET", "/v1/agent/health?type=client", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/health?type=client", nil) require.Nil(err) respW := httptest.NewRecorder() @@ -1120,7 +1120,7 @@ func TestHTTP_AgentHealth_Ok(t *testing.T) { // type=server { - req, err := http.NewRequest("GET", "/v1/agent/health?type=server", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/health?type=server", nil) require.Nil(err) respW := httptest.NewRecorder() @@ -1137,7 +1137,7 @@ func TestHTTP_AgentHealth_Ok(t *testing.T) { // type=client&type=server { - req, err := http.NewRequest("GET", "/v1/agent/health?type=client&type=server", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/health?type=client&type=server", nil) require.Nil(err) respW := httptest.NewRecorder() @@ -1172,7 +1172,7 @@ func TestHTTP_AgentHealth_BadServer(t *testing.T) { // No ?type= means server is just skipped { - req, err := http.NewRequest("GET", "/v1/agent/health", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/health", nil) require.Nil(err) respW := httptest.NewRecorder() @@ -1189,7 +1189,7 @@ func TestHTTP_AgentHealth_BadServer(t *testing.T) { // type=server means server is considered unhealthy { - req, err := http.NewRequest("GET", "/v1/agent/health?type=server", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/health?type=server", nil) require.Nil(err) respW := httptest.NewRecorder() @@ -1215,7 +1215,7 @@ func TestHTTP_AgentHealth_BadClient(t *testing.T) { httpACLTest(t, cb, func(s *TestAgent) { // No ?type= means client is just skipped { - req, err := http.NewRequest("GET", "/v1/agent/health", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/health", nil) require.Nil(err) respW := httptest.NewRecorder() @@ -1232,7 +1232,7 @@ func TestHTTP_AgentHealth_BadClient(t *testing.T) { // type=client means client is considered unhealthy { - req, err := http.NewRequest("GET", "/v1/agent/health?type=client", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/health?type=client", nil) require.Nil(err) respW := httptest.NewRecorder() @@ -1393,7 +1393,7 @@ func TestHTTP_XSS_Monitor(t *testing.T) { defer s.Shutdown() path := fmt.Sprintf("%s/v1/agent/monitor?error_level=error&plain=%t", s.HTTPAddr(), !tc.JSON) - req, err := http.NewRequest("GET", path, nil) + req, err := http.NewRequest(http.MethodGet, path, nil) require.NoError(t, err) resp := NewFakeRW() closedErr := errors.New("sentinel error") @@ -1559,7 +1559,7 @@ func schedulerWorkerInfoTest_testCases() []schedulerWorkerAPITest_testCase { { name: "get without token", request: schedulerWorkerAPITest_testRequest{ - verb: "GET", + verb: http.MethodGet, aclToken: "", requestBody: "", }, @@ -1569,7 +1569,7 @@ func schedulerWorkerInfoTest_testCases() []schedulerWorkerAPITest_testCase { { name: "get with management token", request: schedulerWorkerAPITest_testRequest{ - verb: "GET", + verb: http.MethodGet, aclToken: "management", requestBody: "", }, @@ -1579,7 +1579,7 @@ func schedulerWorkerInfoTest_testCases() []schedulerWorkerAPITest_testCase { { name: "get with read token", request: schedulerWorkerAPITest_testRequest{ - verb: "GET", + verb: http.MethodGet, aclToken: "agent_read", requestBody: "", }, @@ -1589,7 +1589,7 @@ func schedulerWorkerInfoTest_testCases() []schedulerWorkerAPITest_testCase { { name: "get with invalid token", request: schedulerWorkerAPITest_testRequest{ - verb: "GET", + verb: http.MethodGet, aclToken: "node_write", requestBody: "", }, @@ -1733,7 +1733,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "get without token", request: schedulerWorkerConfigTest_testRequest{ - verb: "GET", + verb: http.MethodGet, aclToken: "", requestBody: "", }, @@ -1743,7 +1743,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "get with management token", request: schedulerWorkerConfigTest_testRequest{ - verb: "GET", + verb: http.MethodGet, aclToken: "management", requestBody: "", }, @@ -1753,7 +1753,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "get with read token", request: schedulerWorkerConfigTest_testRequest{ - verb: "GET", + verb: http.MethodGet, aclToken: "agent_read", requestBody: "", }, @@ -1763,7 +1763,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "get with write token", request: schedulerWorkerConfigTest_testRequest{ - verb: "GET", + verb: http.MethodGet, aclToken: "agent_write", requestBody: "", }, @@ -1773,7 +1773,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "post with no token", request: schedulerWorkerConfigTest_testRequest{ - verb: "POST", + verb: http.MethodPost, aclToken: "", requestBody: `{"num_schedulers":9,"enabled_schedulers":["_core", "batch"]}`, }, @@ -1783,7 +1783,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "put with no token", request: schedulerWorkerConfigTest_testRequest{ - verb: "PUT", + verb: http.MethodPut, aclToken: "", requestBody: `{"num_schedulers":8,"enabled_schedulers":["_core", "batch"]}`, }, @@ -1793,7 +1793,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "post with invalid token", request: schedulerWorkerConfigTest_testRequest{ - verb: "POST", + verb: http.MethodPost, aclToken: "node_write", requestBody: `{"num_schedulers":9,"enabled_schedulers":["_core", "batch"]}`, }, @@ -1803,7 +1803,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "put with invalid token", request: schedulerWorkerConfigTest_testRequest{ - verb: "PUT", + verb: http.MethodPut, aclToken: "node_write", requestBody: `{"num_schedulers":8,"enabled_schedulers":["_core", "batch"]}`, }, @@ -1813,7 +1813,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "post with valid token", request: schedulerWorkerConfigTest_testRequest{ - verb: "POST", + verb: http.MethodPost, aclToken: "agent_write", requestBody: `{"num_schedulers":9,"enabled_schedulers":["_core", "batch"]}`, }, @@ -1823,7 +1823,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "put with valid token", request: schedulerWorkerConfigTest_testRequest{ - verb: "PUT", + verb: http.MethodPut, aclToken: "agent_write", requestBody: `{"num_schedulers":8,"enabled_schedulers":["_core", "batch"]}`, }, @@ -1833,7 +1833,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "post with good token and bad value", request: schedulerWorkerConfigTest_testRequest{ - verb: "POST", + verb: http.MethodPost, aclToken: "agent_write", requestBody: `{"num_schedulers":-1,"enabled_schedulers":["_core", "batch"]}`, }, @@ -1843,7 +1843,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "post with bad token and bad value", request: schedulerWorkerConfigTest_testRequest{ - verb: "POST", + verb: http.MethodPost, aclToken: "node_write", requestBody: `{"num_schedulers":-1,"enabled_schedulers":["_core", "batch"]}`, }, @@ -1853,7 +1853,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "put with good token and bad value", request: schedulerWorkerConfigTest_testRequest{ - verb: "PUT", + verb: http.MethodPut, aclToken: "agent_write", requestBody: `{"num_schedulers":-1,"enabled_schedulers":["_core", "batch"]}`, }, @@ -1863,7 +1863,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "put with bad token and bad value", request: schedulerWorkerConfigTest_testRequest{ - verb: "PUT", + verb: http.MethodPut, aclToken: "node_write", requestBody: `{"num_schedulers":-1,"enabled_schedulers":["_core", "batch"]}`, }, @@ -1873,7 +1873,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "post with bad json", request: schedulerWorkerConfigTest_testRequest{ - verb: "POST", + verb: http.MethodPost, aclToken: "agent_write", requestBody: `{num_schedulers:-1,"enabled_schedulers":["_core", "batch"]}`, }, @@ -1883,7 +1883,7 @@ func schedulerWorkerConfigTest_testCases() []scheduleWorkerConfigTest_workerRequ { name: "put with bad json", request: schedulerWorkerConfigTest_testRequest{ - verb: "PUT", + verb: http.MethodPut, aclToken: "agent_write", requestBody: `{num_schedulers:-1,"enabled_schedulers":["_core", "batch"]}`, }, @@ -2016,7 +2016,7 @@ func schedulerWorkerTest_parseError(t *testing.T, isACLEnabled bool, tc schedule func TestHTTP_AgentSchedulerWorkerInfoRequest_Client(t *testing.T) { ci.Parallel(t) - verbs := []string{"GET", "POST", "PUT"} + verbs := []string{http.MethodGet, http.MethodPost, http.MethodPut} path := "schedulers" for _, verb := range verbs { @@ -2042,7 +2042,7 @@ func TestHTTP_AgentSchedulerWorkerInfoRequest_Client(t *testing.T) { func TestHTTP_AgentSchedulerWorkerConfigRequest_Client(t *testing.T) { ci.Parallel(t) - verbs := []string{"GET", "POST", "PUT"} + verbs := []string{http.MethodGet, http.MethodPost, http.MethodPut} path := "schedulers/config" for _, verb := range verbs { diff --git a/command/agent/alloc_endpoint.go b/command/agent/alloc_endpoint.go index 15b38428883..e17369a4c80 100644 --- a/command/agent/alloc_endpoint.go +++ b/command/agent/alloc_endpoint.go @@ -24,7 +24,7 @@ const ( ) func (s *HTTPServer) AllocsRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } @@ -96,7 +96,7 @@ func (s *HTTPServer) AllocSpecificRequest(resp http.ResponseWriter, req *http.Re } func (s *HTTPServer) allocGet(allocID string, resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } diff --git a/command/agent/alloc_endpoint_test.go b/command/agent/alloc_endpoint_test.go index f6e1478caa6..94ad4786332 100644 --- a/command/agent/alloc_endpoint_test.go +++ b/command/agent/alloc_endpoint_test.go @@ -49,7 +49,7 @@ func TestHTTP_AllocsList(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/allocations", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/allocations", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -116,7 +116,7 @@ func TestHTTP_AllocsPrefixList(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/allocations?prefix=aaab", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/allocations?prefix=aaab", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -167,7 +167,7 @@ func TestHTTP_AllocQuery(t *testing.T) { require.NoError(state.UpsertAllocs(structs.MsgTypeTestSetup, 1000, []*structs.Allocation{alloc})) // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/allocation/"+alloc.ID, nil) + req, err := http.NewRequest(http.MethodGet, "/v1/allocation/"+alloc.ID, nil) require.NoError(err) respW := httptest.NewRecorder() @@ -218,7 +218,7 @@ func TestHTTP_AllocQuery_Payload(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/allocation/"+alloc.ID, nil) + req, err := http.NewRequest(http.MethodGet, "/v1/allocation/"+alloc.ID, nil) if err != nil { t.Fatalf("err: %v", err) } @@ -264,7 +264,7 @@ func TestHTTP_AllocRestart(t *testing.T) { { // Make the HTTP request buf := encodeReq(map[string]string{}) - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/allocation/%s/restart", uuid.Generate()), buf) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/allocation/%s/restart", uuid.Generate()), buf) if err != nil { t.Fatalf("err: %v", err) } @@ -282,7 +282,7 @@ func TestHTTP_AllocRestart(t *testing.T) { s.server = nil buf := encodeReq(map[string]string{}) - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/allocation/%s/restart", uuid.Generate()), buf) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/allocation/%s/restart", uuid.Generate()), buf) require.Nil(err) respW := httptest.NewRecorder() @@ -309,7 +309,7 @@ func TestHTTP_AllocRestart(t *testing.T) { }) buf := encodeReq(map[string]string{}) - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/allocation/%s/restart", uuid.Generate()), buf) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/allocation/%s/restart", uuid.Generate()), buf) require.Nil(err) respW := httptest.NewRecorder() @@ -332,7 +332,7 @@ func TestHTTP_AllocRestart_ACL(t *testing.T) { // If there's no token, we expect the request to fail. { buf := encodeReq(map[string]string{}) - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/allocation/%s/restart", uuid.Generate()), buf) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/allocation/%s/restart", uuid.Generate()), buf) require.NoError(err) respW := httptest.NewRecorder() @@ -344,7 +344,7 @@ func TestHTTP_AllocRestart_ACL(t *testing.T) { // Try request with an invalid token and expect it to fail { buf := encodeReq(map[string]string{}) - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/allocation/%s/restart", uuid.Generate()), buf) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/allocation/%s/restart", uuid.Generate()), buf) require.NoError(err) respW := httptest.NewRecorder() @@ -359,7 +359,7 @@ func TestHTTP_AllocRestart_ACL(t *testing.T) { // Still returns an error because the alloc does not exist { buf := encodeReq(map[string]string{}) - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/allocation/%s/restart", uuid.Generate()), buf) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/allocation/%s/restart", uuid.Generate()), buf) require.NoError(err) respW := httptest.NewRecorder() @@ -375,7 +375,7 @@ func TestHTTP_AllocRestart_ACL(t *testing.T) { // Still returns an error because the alloc does not exist { buf := encodeReq(map[string]string{}) - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/allocation/%s/restart", uuid.Generate()), buf) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/allocation/%s/restart", uuid.Generate()), buf) require.NoError(err) respW := httptest.NewRecorder() @@ -401,7 +401,7 @@ func TestHTTP_AllocStop(t *testing.T) { // Test that the happy path works { // Make the HTTP request - req, err := http.NewRequest("POST", "/v1/allocation/"+alloc.ID+"/stop", nil) + req, err := http.NewRequest(http.MethodPost, "/v1/allocation/"+alloc.ID+"/stop", nil) require.NoError(err) respW := httptest.NewRecorder() @@ -419,7 +419,7 @@ func TestHTTP_AllocStop(t *testing.T) { // Test that we 404 when the allocid is invalid { // Make the HTTP request - req, err := http.NewRequest("POST", "/v1/allocation/"+uuid.Generate()+"/stop", nil) + req, err := http.NewRequest(http.MethodPost, "/v1/allocation/"+uuid.Generate()+"/stop", nil) require.NoError(err) respW := httptest.NewRecorder() @@ -554,7 +554,7 @@ func TestHTTP_AllocStats(t *testing.T) { // Local node, local resp { // Make the HTTP request - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/allocation/%s/stats", uuid.Generate()), nil) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/allocation/%s/stats", uuid.Generate()), nil) if err != nil { t.Fatalf("err: %v", err) } @@ -571,7 +571,7 @@ func TestHTTP_AllocStats(t *testing.T) { srv := s.server s.server = nil - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/allocation/%s/stats", uuid.Generate()), nil) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/allocation/%s/stats", uuid.Generate()), nil) require.Nil(err) respW := httptest.NewRecorder() @@ -597,7 +597,7 @@ func TestHTTP_AllocStats(t *testing.T) { t.Fatalf("should have client: %v", err) }) - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/allocation/%s/stats", uuid.Generate()), nil) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/allocation/%s/stats", uuid.Generate()), nil) require.Nil(err) respW := httptest.NewRecorder() @@ -618,7 +618,7 @@ func TestHTTP_AllocStats_ACL(t *testing.T) { state := s.Agent.server.State() // Make the HTTP request - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/allocation/%s/stats", uuid.Generate()), nil) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/allocation/%s/stats", uuid.Generate()), nil) if err != nil { t.Fatalf("err: %v", err) } @@ -669,7 +669,7 @@ func TestHTTP_AllocSnapshot(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/client/allocation/123/snapshot", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/client/allocation/123/snapshot", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -688,7 +688,7 @@ func TestHTTP_AllocSnapshot_WithMigrateToken(t *testing.T) { require := require.New(t) httpACLTest(t, nil, func(s *TestAgent) { // Request without a token fails - req, err := http.NewRequest("GET", "/v1/client/allocation/123/snapshot", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/client/allocation/123/snapshot", nil) require.Nil(err) // Make the unauthorized request @@ -705,7 +705,7 @@ func TestHTTP_AllocSnapshot_WithMigrateToken(t *testing.T) { // Request with a token succeeds url := fmt.Sprintf("/v1/client/allocation/%s/snapshot", alloc.ID) - req, err = http.NewRequest("GET", url, nil) + req, err = http.NewRequest(http.MethodGet, url, nil) require.Nil(err) req.Header.Set("X-Nomad-Token", validMigrateToken) @@ -776,7 +776,7 @@ func TestHTTP_AllocSnapshot_Atomic(t *testing.T) { // streamed over a 200 HTTP response the only way to signal an // error is by writing a marker file. respW := httptest.NewRecorder() - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/allocation/%s/snapshot", alloc.ID), nil) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/allocation/%s/snapshot", alloc.ID), nil) if err != nil { t.Fatalf("err: %v", err) } @@ -835,7 +835,7 @@ func TestHTTP_AllocGC(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { // Local node, local resp { - req, err := http.NewRequest("GET", path, nil) + req, err := http.NewRequest(http.MethodGet, path, nil) if err != nil { t.Fatalf("err: %v", err) } @@ -852,7 +852,7 @@ func TestHTTP_AllocGC(t *testing.T) { srv := s.server s.server = nil - req, err := http.NewRequest("GET", path, nil) + req, err := http.NewRequest(http.MethodGet, path, nil) if err != nil { t.Fatalf("err: %v", err) } @@ -881,7 +881,7 @@ func TestHTTP_AllocGC(t *testing.T) { t.Fatalf("should have client: %v", err) }) - req, err := http.NewRequest("GET", path, nil) + req, err := http.NewRequest(http.MethodGet, path, nil) if err != nil { t.Fatalf("err: %v", err) } @@ -907,7 +907,7 @@ func TestHTTP_AllocGC_ACL(t *testing.T) { state := s.Agent.server.State() // Make the HTTP request - req, err := http.NewRequest("GET", path, nil) + req, err := http.NewRequest(http.MethodGet, path, nil) if err != nil { t.Fatalf("err: %v", err) } @@ -960,7 +960,7 @@ func TestHTTP_AllocAllGC(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { // Local node, local resp { - req, err := http.NewRequest("GET", "/v1/client/gc", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/client/gc", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -977,7 +977,7 @@ func TestHTTP_AllocAllGC(t *testing.T) { srv := s.server s.server = nil - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/gc?node_id=%s", uuid.Generate()), nil) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/gc?node_id=%s", uuid.Generate()), nil) require.Nil(err) respW := httptest.NewRecorder() @@ -1003,7 +1003,7 @@ func TestHTTP_AllocAllGC(t *testing.T) { t.Fatalf("should have client: %v", err) }) - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/gc?node_id=%s", c.NodeID()), nil) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/gc?node_id=%s", c.NodeID()), nil) require.Nil(err) respW := httptest.NewRecorder() @@ -1023,7 +1023,7 @@ func TestHTTP_AllocAllGC_ACL(t *testing.T) { state := s.Agent.server.State() // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/client/gc", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/client/gc", nil) require.Nil(err) // Try request without a token and expect failure @@ -1106,7 +1106,7 @@ func TestHTTP_ReadWsHandshake(t *testing.T) { return nil } - req := httptest.NewRequest("PUT", "/target", nil) + req := httptest.NewRequest(http.MethodPut, "/target", nil) if c.handshake { req.URL.RawQuery = "ws_handshake=true" } diff --git a/command/agent/csi_endpoint_test.go b/command/agent/csi_endpoint_test.go index f8187fa9a7c..951f3fb80ae 100644 --- a/command/agent/csi_endpoint_test.go +++ b/command/agent/csi_endpoint_test.go @@ -21,7 +21,7 @@ func TestHTTP_CSIEndpointPlugin(t *testing.T) { defer cleanup() body := bytes.NewBuffer(nil) - req, err := http.NewRequest("GET", "/v1/plugin/csi/foo", body) + req, err := http.NewRequest(http.MethodGet, "/v1/plugin/csi/foo", body) require.NoError(t, err) resp := httptest.NewRecorder() @@ -63,7 +63,7 @@ func TestHTTP_CSIParseSecrets(t *testing.T) { structs.CSISecrets(map[string]string{"one": "value_one=two", "two": "value_two"})}, } for _, tc := range testCases { - req, _ := http.NewRequest("GET", "/v1/plugin/csi/foo", nil) + req, _ := http.NewRequest(http.MethodGet, "/v1/plugin/csi/foo", nil) req.Header.Add("X-Nomad-CSI-Secrets", tc.val) require.Equal(t, tc.expect, parseCSISecrets(req), tc.val) } @@ -87,13 +87,13 @@ func TestHTTP_CSIEndpointRegisterVolume(t *testing.T) { }}, } body := encodeReq(args) - req, err := http.NewRequest("PUT", "/v1/volumes", body) + req, err := http.NewRequest(http.MethodPut, "/v1/volumes", body) require.NoError(t, err) resp := httptest.NewRecorder() _, err = s.Server.CSIVolumesRequest(resp, req) require.NoError(t, err, "put error") - req, err = http.NewRequest("GET", "/v1/volume/csi/bar", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/volume/csi/bar", nil) require.NoError(t, err) resp = httptest.NewRecorder() raw, err := s.Server.CSIVolumeSpecificRequest(resp, req) @@ -103,7 +103,7 @@ func TestHTTP_CSIEndpointRegisterVolume(t *testing.T) { require.Equal(t, 1, out.ControllersHealthy) require.Equal(t, 2, out.NodesHealthy) - req, err = http.NewRequest("DELETE", "/v1/volume/csi/bar/detach", nil) + req, err = http.NewRequest(http.MethodDelete, "/v1/volume/csi/bar/detach", nil) require.NoError(t, err) resp = httptest.NewRecorder() _, err = s.Server.CSIVolumeSpecificRequest(resp, req) @@ -129,13 +129,13 @@ func TestHTTP_CSIEndpointCreateVolume(t *testing.T) { }}, } body := encodeReq(args) - req, err := http.NewRequest("PUT", "/v1/volumes/create", body) + req, err := http.NewRequest(http.MethodPut, "/v1/volumes/create", body) require.NoError(t, err) resp := httptest.NewRecorder() _, err = s.Server.CSIVolumesRequest(resp, req) require.Error(t, err, "controller validate volume: No path to node") - req, err = http.NewRequest("DELETE", "/v1/volume/csi/baz", nil) + req, err = http.NewRequest(http.MethodDelete, "/v1/volume/csi/baz", nil) require.NoError(t, err) resp = httptest.NewRecorder() _, err = s.Server.CSIVolumeSpecificRequest(resp, req) @@ -158,7 +158,7 @@ func TestHTTP_CSIEndpointSnapshot(t *testing.T) { }}, } body := encodeReq(args) - req, err := http.NewRequest("PUT", "/v1/volumes/snapshot", body) + req, err := http.NewRequest(http.MethodPut, "/v1/volumes/snapshot", body) require.NoError(t, err) resp := httptest.NewRecorder() _, err = s.Server.CSISnapshotsRequest(resp, req) diff --git a/command/agent/deployment_endpoint_test.go b/command/agent/deployment_endpoint_test.go index 2a17421574d..23e75257d43 100644 --- a/command/agent/deployment_endpoint_test.go +++ b/command/agent/deployment_endpoint_test.go @@ -23,7 +23,7 @@ func TestHTTP_DeploymentList(t *testing.T) { assert.Nil(state.UpsertDeployment(1000, d2), "UpsertDeployment") // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/deployments", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/deployments", nil) assert.Nil(err, "HTTP Request") respW := httptest.NewRecorder() @@ -56,7 +56,7 @@ func TestHTTP_DeploymentPrefixList(t *testing.T) { assert.Nil(state.UpsertDeployment(1000, d2), "UpsertDeployment") // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/deployments?prefix=aaab", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/deployments?prefix=aaab", nil) assert.Nil(err, "HTTP Request") respW := httptest.NewRecorder() @@ -113,7 +113,7 @@ func TestHTTP_DeploymentAllocations(t *testing.T) { assert.Nil(state.UpsertAllocs(structs.MsgTypeTestSetup, 1000, []*structs.Allocation{a1, a2}), "UpsertAllocs") // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/deployment/allocations/"+d.ID, nil) + req, err := http.NewRequest(http.MethodGet, "/v1/deployment/allocations/"+d.ID, nil) assert.Nil(err, "HTTP Request") respW := httptest.NewRecorder() @@ -147,7 +147,7 @@ func TestHTTP_DeploymentQuery(t *testing.T) { assert.Nil(state.UpsertDeployment(1000, d), "UpsertDeployment") // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/deployment/"+d.ID, nil) + req, err := http.NewRequest(http.MethodGet, "/v1/deployment/"+d.ID, nil) assert.Nil(err, "HTTP Request") respW := httptest.NewRecorder() @@ -190,7 +190,7 @@ func TestHTTP_DeploymentPause(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/deployment/pause/"+d.ID, buf) + req, err := http.NewRequest(http.MethodPut, "/v1/deployment/pause/"+d.ID, buf) assert.Nil(err, "HTTP Request") respW := httptest.NewRecorder() @@ -231,7 +231,7 @@ func TestHTTP_DeploymentPromote(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/deployment/pause/"+d.ID, buf) + req, err := http.NewRequest(http.MethodPut, "/v1/deployment/pause/"+d.ID, buf) assert.Nil(err, "HTTP Request") respW := httptest.NewRecorder() @@ -276,7 +276,7 @@ func TestHTTP_DeploymentAllocHealth(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/deployment/allocation-health/"+d.ID, buf) + req, err := http.NewRequest(http.MethodPut, "/v1/deployment/allocation-health/"+d.ID, buf) assert.Nil(err, "HTTP Request") respW := httptest.NewRecorder() @@ -306,7 +306,7 @@ func TestHTTP_DeploymentFail(t *testing.T) { assert.Nil(state.UpsertDeployment(999, d), "UpsertDeployment") // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/deployment/fail/"+d.ID, nil) + req, err := http.NewRequest(http.MethodPut, "/v1/deployment/fail/"+d.ID, nil) assert.Nil(err, "HTTP Request") respW := httptest.NewRecorder() diff --git a/command/agent/eval_endpoint.go b/command/agent/eval_endpoint.go index e52285a0c77..11c173fc9a1 100644 --- a/command/agent/eval_endpoint.go +++ b/command/agent/eval_endpoint.go @@ -96,7 +96,7 @@ func (s *HTTPServer) EvalSpecificRequest(resp http.ResponseWriter, req *http.Req } func (s *HTTPServer) evalAllocations(resp http.ResponseWriter, req *http.Request, evalID string) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } @@ -120,7 +120,7 @@ func (s *HTTPServer) evalAllocations(resp http.ResponseWriter, req *http.Request } func (s *HTTPServer) evalQuery(resp http.ResponseWriter, req *http.Request, evalID string) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } diff --git a/command/agent/eval_endpoint_test.go b/command/agent/eval_endpoint_test.go index 8891506d657..7c9b49c37a4 100644 --- a/command/agent/eval_endpoint_test.go +++ b/command/agent/eval_endpoint_test.go @@ -27,7 +27,7 @@ func TestHTTP_EvalList(t *testing.T) { require.NoError(t, err) // simple list request - req, err := http.NewRequest("GET", "/v1/evaluations", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/evaluations", nil) require.NoError(t, err) respW := httptest.NewRecorder() obj, err := s.Server.EvalsRequest(respW, req) @@ -40,7 +40,7 @@ func TestHTTP_EvalList(t *testing.T) { require.Len(t, obj.([]*structs.Evaluation), 2, "expected 2 evals") // paginated list request - req, err = http.NewRequest("GET", "/v1/evaluations?per_page=1", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/evaluations?per_page=1", nil) require.NoError(t, err) respW = httptest.NewRecorder() obj, err = s.Server.EvalsRequest(respW, req) @@ -50,7 +50,7 @@ func TestHTTP_EvalList(t *testing.T) { require.Len(t, obj.([]*structs.Evaluation), 1, "expected 1 eval") // filtered list request - req, err = http.NewRequest("GET", + req, err = http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/evaluations?per_page=10&job=%s", eval2.JobID), nil) require.NoError(t, err) respW = httptest.NewRecorder() @@ -78,7 +78,7 @@ func TestHTTP_EvalPrefixList(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/evaluations?prefix=aaab", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/evaluations?prefix=aaab", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -261,7 +261,7 @@ func TestHTTP_EvalAllocations(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", + req, err := http.NewRequest(http.MethodGet, "/v1/evaluation/"+alloc1.EvalID+"/allocations", nil) if err != nil { t.Fatalf("err: %v", err) @@ -305,7 +305,7 @@ func TestHTTP_EvalQuery(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/evaluation/"+eval.ID, nil) + req, err := http.NewRequest(http.MethodGet, "/v1/evaluation/"+eval.ID, nil) if err != nil { t.Fatalf("err: %v", err) } @@ -352,7 +352,7 @@ func TestHTTP_EvalQueryWithRelated(t *testing.T) { require.NoError(t, err) // Make the HTTP request - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/evaluation/%s?related=true", eval1.ID), nil) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/evaluation/%s?related=true", eval1.ID), nil) require.NoError(t, err) respW := httptest.NewRecorder() @@ -388,7 +388,7 @@ func TestHTTP_EvalCount(t *testing.T) { must.NoError(t, err) // simple count request - req, err := http.NewRequest("GET", "/v1/evaluations/count", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/evaluations/count", nil) must.NoError(t, err) respW := httptest.NewRecorder() obj, err := s.Server.EvalsCountRequest(respW, req) @@ -408,7 +408,7 @@ func TestHTTP_EvalCount(t *testing.T) { // filtered count request v := url.Values{} v.Add("filter", fmt.Sprintf("JobID==\"%s\"", eval2.JobID)) - req, err = http.NewRequest("GET", "/v1/evaluations/count?"+v.Encode(), nil) + req, err = http.NewRequest(http.MethodGet, "/v1/evaluations/count?"+v.Encode(), nil) must.NoError(t, err) respW = httptest.NewRecorder() obj, err = s.Server.EvalsCountRequest(respW, req) diff --git a/command/agent/event_endpoint_test.go b/command/agent/event_endpoint_test.go index 209b4596033..15efea130f7 100644 --- a/command/agent/event_endpoint_test.go +++ b/command/agent/event_endpoint_test.go @@ -29,7 +29,7 @@ func TestEventStream(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { ctx, cancel := context.WithCancel(context.Background()) - req, err := http.NewRequestWithContext(ctx, "GET", "/v1/event/stream", nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "/v1/event/stream", nil) require.Nil(t, err) resp := httptest.NewRecorder() @@ -76,7 +76,7 @@ func TestEventStream_NamespaceQuery(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - req, err := http.NewRequestWithContext(ctx, "GET", "/v1/event/stream?namespace=foo", nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "/v1/event/stream?namespace=foo", nil) require.Nil(t, err) resp := httptest.NewRecorder() diff --git a/command/agent/fs_endpoint_test.go b/command/agent/fs_endpoint_test.go index 90b3d01cf44..b04f592cd52 100644 --- a/command/agent/fs_endpoint_test.go +++ b/command/agent/fs_endpoint_test.go @@ -118,7 +118,7 @@ func TestHTTP_FS_List_MissingParams(t *testing.T) { ci.Parallel(t) require := require.New(t) httpTest(t, nil, func(s *TestAgent) { - req, err := http.NewRequest("GET", "/v1/client/fs/ls/", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/client/fs/ls/", nil) require.Nil(err) respW := httptest.NewRecorder() _, err = s.Server.DirectoryListRequest(respW, req) @@ -130,14 +130,14 @@ func TestHTTP_FS_Stat_MissingParams(t *testing.T) { ci.Parallel(t) require := require.New(t) httpTest(t, nil, func(s *TestAgent) { - req, err := http.NewRequest("GET", "/v1/client/fs/stat/", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/client/fs/stat/", nil) require.Nil(err) respW := httptest.NewRecorder() _, err = s.Server.FileStatRequest(respW, req) require.EqualError(err, allocIDNotPresentErr.Error()) - req, err = http.NewRequest("GET", "/v1/client/fs/stat/foo", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/client/fs/stat/foo", nil) require.Nil(err) respW = httptest.NewRecorder() @@ -150,19 +150,19 @@ func TestHTTP_FS_ReadAt_MissingParams(t *testing.T) { ci.Parallel(t) require := require.New(t) httpTest(t, nil, func(s *TestAgent) { - req, err := http.NewRequest("GET", "/v1/client/fs/readat/", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/client/fs/readat/", nil) require.NoError(err) _, err = s.Server.FileReadAtRequest(httptest.NewRecorder(), req) require.Error(err) - req, err = http.NewRequest("GET", "/v1/client/fs/readat/foo", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/client/fs/readat/foo", nil) require.NoError(err) _, err = s.Server.FileReadAtRequest(httptest.NewRecorder(), req) require.Error(err) - req, err = http.NewRequest("GET", "/v1/client/fs/readat/foo?path=/path/to/file", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/client/fs/readat/foo?path=/path/to/file", nil) require.NoError(err) _, err = s.Server.FileReadAtRequest(httptest.NewRecorder(), req) @@ -174,14 +174,14 @@ func TestHTTP_FS_Cat_MissingParams(t *testing.T) { ci.Parallel(t) require := require.New(t) httpTest(t, nil, func(s *TestAgent) { - req, err := http.NewRequest("GET", "/v1/client/fs/cat/", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/client/fs/cat/", nil) require.Nil(err) respW := httptest.NewRecorder() _, err = s.Server.FileCatRequest(respW, req) require.EqualError(err, allocIDNotPresentErr.Error()) - req, err = http.NewRequest("GET", "/v1/client/fs/stat/foo", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/client/fs/stat/foo", nil) require.Nil(err) respW = httptest.NewRecorder() @@ -194,21 +194,21 @@ func TestHTTP_FS_Stream_MissingParams(t *testing.T) { ci.Parallel(t) require := require.New(t) httpTest(t, nil, func(s *TestAgent) { - req, err := http.NewRequest("GET", "/v1/client/fs/stream/", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/client/fs/stream/", nil) require.NoError(err) respW := httptest.NewRecorder() _, err = s.Server.Stream(respW, req) require.EqualError(err, allocIDNotPresentErr.Error()) - req, err = http.NewRequest("GET", "/v1/client/fs/stream/foo", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/client/fs/stream/foo", nil) require.NoError(err) respW = httptest.NewRecorder() _, err = s.Server.Stream(respW, req) require.EqualError(err, fileNameNotPresentErr.Error()) - req, err = http.NewRequest("GET", "/v1/client/fs/stream/foo?path=/path/to/file", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/client/fs/stream/foo?path=/path/to/file", nil) require.NoError(err) respW = httptest.NewRecorder() @@ -225,7 +225,7 @@ func TestHTTP_FS_Logs_MissingParams(t *testing.T) { require := require.New(t) httpTest(t, nil, func(s *TestAgent) { // AllocID Not Present - req, err := http.NewRequest("GET", "/v1/client/fs/logs/", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/client/fs/logs/", nil) require.NoError(err) respW := httptest.NewRecorder() @@ -234,7 +234,7 @@ func TestHTTP_FS_Logs_MissingParams(t *testing.T) { require.Equal(400, respW.Code) // Task Not Present - req, err = http.NewRequest("GET", "/v1/client/fs/logs/foo", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/client/fs/logs/foo", nil) require.NoError(err) respW = httptest.NewRecorder() @@ -243,7 +243,7 @@ func TestHTTP_FS_Logs_MissingParams(t *testing.T) { require.Equal(400, respW.Code) // Log Type Not Present - req, err = http.NewRequest("GET", "/v1/client/fs/logs/foo?task=foo", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/client/fs/logs/foo?task=foo", nil) require.NoError(err) respW = httptest.NewRecorder() @@ -252,7 +252,7 @@ func TestHTTP_FS_Logs_MissingParams(t *testing.T) { require.Equal(400, respW.Code) // case where all parameters are set but alloc isn't found - req, err = http.NewRequest("GET", "/v1/client/fs/logs/foo?task=foo&type=stdout", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/client/fs/logs/foo?task=foo&type=stdout", nil) require.NoError(err) respW = httptest.NewRecorder() @@ -269,7 +269,7 @@ func TestHTTP_FS_List(t *testing.T) { a := mockFSAlloc(s.client.NodeID(), nil) addAllocToClient(s, a, terminalClientAlloc) - req, err := http.NewRequest("GET", "/v1/client/fs/ls/"+a.ID, nil) + req, err := http.NewRequest(http.MethodGet, "/v1/client/fs/ls/"+a.ID, nil) require.Nil(err) respW := httptest.NewRecorder() raw, err := s.Server.DirectoryListRequest(respW, req) @@ -290,7 +290,7 @@ func TestHTTP_FS_Stat(t *testing.T) { addAllocToClient(s, a, terminalClientAlloc) path := fmt.Sprintf("/v1/client/fs/stat/%s?path=alloc/", a.ID) - req, err := http.NewRequest("GET", path, nil) + req, err := http.NewRequest(http.MethodGet, path, nil) require.Nil(err) respW := httptest.NewRecorder() raw, err := s.Server.FileStatRequest(respW, req) @@ -316,7 +316,7 @@ func TestHTTP_FS_ReadAt(t *testing.T) { path := fmt.Sprintf("/v1/client/fs/readat/%s?path=alloc/logs/web.stdout.0&offset=%d&limit=%d", a.ID, offset, limit) - req, err := http.NewRequest("GET", path, nil) + req, err := http.NewRequest(http.MethodGet, path, nil) require.Nil(err) respW := httptest.NewRecorder() _, err = s.Server.FileReadAtRequest(respW, req) @@ -362,7 +362,7 @@ func TestHTTP_FS_Cat(t *testing.T) { path := fmt.Sprintf("/v1/client/fs/cat/%s?path=alloc/logs/web.stdout.0", a.ID) - req, err := http.NewRequest("GET", path, nil) + req, err := http.NewRequest(http.MethodGet, path, nil) require.Nil(err) respW := httptest.NewRecorder() _, err = s.Server.FileCatRequest(respW, req) @@ -411,7 +411,7 @@ func TestHTTP_FS_Stream_NoFollow(t *testing.T) { path := fmt.Sprintf("/v1/client/fs/stream/%s?path=alloc/logs/web.stdout.0&offset=%d&origin=end&follow=false", a.ID, offset) - req, err := http.NewRequest("GET", path, nil) + req, err := http.NewRequest(http.MethodGet, path, nil) require.Nil(err) respW := testutil.NewResponseRecorder() doneCh := make(chan struct{}) @@ -475,7 +475,7 @@ func TestHTTP_FS_Stream_Follow(t *testing.T) { path := fmt.Sprintf("/v1/client/fs/stream/%s?path=alloc/logs/web.stdout.0&offset=%d&origin=end", a.ID, offset) - req, err := http.NewRequest("GET", path, nil) + req, err := http.NewRequest(http.MethodGet, path, nil) require.Nil(err) respW := httptest.NewRecorder() doneCh := make(chan struct{}) @@ -518,7 +518,7 @@ func TestHTTP_FS_Logs(t *testing.T) { path := fmt.Sprintf("/v1/client/fs/logs/%s?type=stdout&task=web&offset=%d&origin=end&plain=true", a.ID, offset) - req, err := http.NewRequest("GET", path, nil) + req, err := http.NewRequest(http.MethodGet, path, nil) require.Nil(err) respW := testutil.NewResponseRecorder() go func() { @@ -577,7 +577,7 @@ func TestHTTP_FS_Logs_Follow(t *testing.T) { path := fmt.Sprintf("/v1/client/fs/logs/%s?type=stdout&task=web&offset=%d&origin=end&plain=true&follow=true", a.ID, offset) - req, err := http.NewRequest("GET", path, nil) + req, err := http.NewRequest(http.MethodGet, path, nil) require.Nil(err) respW := testutil.NewResponseRecorder() errCh := make(chan error, 1) @@ -613,7 +613,7 @@ func TestHTTP_FS_Logs_PropagatesErrors(t *testing.T) { path := fmt.Sprintf("/v1/client/fs/logs/%s?type=stdout&task=web&offset=0&origin=end&plain=true", uuid.Generate()) - req, err := http.NewRequest("GET", path, nil) + req, err := http.NewRequest(http.MethodGet, path, nil) require.NoError(t, err) respW := testutil.NewResponseRecorder() diff --git a/command/agent/http.go b/command/agent/http.go index 9c062a53cff..571b5687e47 100644 --- a/command/agent/http.go +++ b/command/agent/http.go @@ -655,7 +655,7 @@ func (s *HTTPServer) handleRootFallthrough() http.Handler { if req.URL.RawQuery != "" { url = url + "?" + req.URL.RawQuery } - http.Redirect(w, req, url, 307) + http.Redirect(w, req, url, http.StatusTemporaryRedirect) } else { w.WriteHeader(http.StatusNotFound) } @@ -871,7 +871,7 @@ func parseWait(resp http.ResponseWriter, req *http.Request, b *structs.QueryOpti if wait := query.Get("wait"); wait != "" { dur, err := time.ParseDuration(wait) if err != nil { - resp.WriteHeader(400) + resp.WriteHeader(http.StatusBadRequest) resp.Write([]byte("Invalid wait time")) return true } @@ -880,7 +880,7 @@ func parseWait(resp http.ResponseWriter, req *http.Request, b *structs.QueryOpti if idx := query.Get("index"); idx != "" { index, err := strconv.ParseUint(idx, 10, 64) if err != nil { - resp.WriteHeader(400) + resp.WriteHeader(http.StatusBadRequest) resp.Write([]byte("Invalid index")) return true } @@ -899,7 +899,7 @@ func parseConsistency(resp http.ResponseWriter, req *http.Request, b *structs.Qu } staleQuery, err := strconv.ParseBool(staleVal[0]) if err != nil { - resp.WriteHeader(400) + resp.WriteHeader(http.StatusBadRequest) _, _ = resp.Write([]byte(fmt.Sprintf("Expect `true` or `false` for `stale` query string parameter, got %s", staleVal[0]))) return } @@ -1131,7 +1131,7 @@ func (a *authMiddleware) ServeHTTP(resp http.ResponseWriter, req *http.Request) } a.srv.logger.Error("error authenticating built API request", "error", err, "url", req.URL, "method", req.Method) - resp.WriteHeader(500) + resp.WriteHeader(http.StatusInternalServerError) resp.Write([]byte("Server error authenticating request\n")) return } diff --git a/command/agent/http_test.go b/command/agent/http_test.go index cda8854b903..dfde10b5508 100644 --- a/command/agent/http_test.go +++ b/command/agent/http_test.go @@ -64,7 +64,7 @@ func BenchmarkHTTPRequests(b *testing.B) { b.RunParallel(func(pb *testing.PB) { for pb.Next() { resp := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "/v1/kv/key", nil) + req, _ := http.NewRequest(http.MethodGet, "/v1/kv/key", nil) s.Server.wrap(handler)(resp, req) } }) @@ -225,7 +225,7 @@ func TestSetHeaders(t *testing.T) { return &structs.Job{Name: "foo"}, nil } - req, _ := http.NewRequest("GET", "/v1/kv/key", nil) + req, _ := http.NewRequest(http.MethodGet, "/v1/kv/key", nil) s.Server.wrap(handler)(resp, req) header := resp.Header().Get("foo") @@ -246,7 +246,7 @@ func TestContentTypeIsJSON(t *testing.T) { return &structs.Job{Name: "foo"}, nil } - req, _ := http.NewRequest("GET", "/v1/kv/key", nil) + req, _ := http.NewRequest(http.MethodGet, "/v1/kv/key", nil) s.Server.wrap(handler)(resp, req) contentType := resp.Header().Get("Content-Type") @@ -267,7 +267,7 @@ func TestWrapNonJSON(t *testing.T) { return []byte("test response"), nil } - req, _ := http.NewRequest("GET", "/v1/kv/key", nil) + req, _ := http.NewRequest(http.MethodGet, "/v1/kv/key", nil) s.Server.wrapNonJSON(handler)(resp, req) respBody, _ := io.ReadAll(resp.Body) @@ -291,7 +291,7 @@ func TestWrapNonJSON_Error(t *testing.T) { // RPC coded error { resp := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "/v1/kv/key", nil) + req, _ := http.NewRequest(http.MethodGet, "/v1/kv/key", nil) s.Server.wrapNonJSON(handlerRPCErr)(resp, req) respBody, _ := io.ReadAll(resp.Body) require.Equal(t, []byte("not found"), respBody) @@ -301,7 +301,7 @@ func TestWrapNonJSON_Error(t *testing.T) { // CodedError { resp := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "/v1/kv/key", nil) + req, _ := http.NewRequest(http.MethodGet, "/v1/kv/key", nil) s.Server.wrapNonJSON(handlerCodedErr)(resp, req) respBody, _ := io.ReadAll(resp.Body) require.Equal(t, []byte("unprocessable"), respBody) @@ -337,7 +337,7 @@ func testPrettyPrint(pretty string, prettyFmt bool, t *testing.T) { } urlStr := "/v1/job/foo?" + pretty - req, _ := http.NewRequest("GET", urlStr, nil) + req, _ := http.NewRequest(http.MethodGet, urlStr, nil) s.Server.wrap(handler)(resp, req) var expected bytes.Buffer @@ -375,7 +375,7 @@ func TestPermissionDenied(t *testing.T) { return nil, structs.ErrPermissionDenied } - req, _ := http.NewRequest("GET", "/v1/job/foo", nil) + req, _ := http.NewRequest(http.MethodGet, "/v1/job/foo", nil) s.Server.wrap(handler)(resp, req) assert.Equal(t, resp.Code, 403) } @@ -387,7 +387,7 @@ func TestPermissionDenied(t *testing.T) { return nil, fmt.Errorf("rpc error: %v", structs.ErrPermissionDenied) } - req, _ := http.NewRequest("GET", "/v1/job/foo", nil) + req, _ := http.NewRequest(http.MethodGet, "/v1/job/foo", nil) s.Server.wrap(handler)(resp, req) assert.Equal(t, resp.Code, 403) } @@ -405,7 +405,7 @@ func TestTokenNotFound(t *testing.T) { } urlStr := "/v1/job/foo" - req, _ := http.NewRequest("GET", urlStr, nil) + req, _ := http.NewRequest(http.MethodGet, urlStr, nil) s.Server.wrap(handler)(resp, req) assert.Equal(t, resp.Code, 403) } @@ -415,7 +415,7 @@ func TestParseWait(t *testing.T) { resp := httptest.NewRecorder() var b structs.QueryOptions - req, err := http.NewRequest("GET", + req, err := http.NewRequest(http.MethodGet, "/v1/catalog/nodes?wait=60s&index=1000", nil) if err != nil { t.Fatalf("err: %v", err) @@ -438,7 +438,7 @@ func TestParseWait_InvalidTime(t *testing.T) { resp := httptest.NewRecorder() var b structs.QueryOptions - req, err := http.NewRequest("GET", + req, err := http.NewRequest(http.MethodGet, "/v1/catalog/nodes?wait=60foo&index=1000", nil) if err != nil { t.Fatalf("err: %v", err) @@ -458,7 +458,7 @@ func TestParseWait_InvalidIndex(t *testing.T) { resp := httptest.NewRecorder() var b structs.QueryOptions - req, err := http.NewRequest("GET", + req, err := http.NewRequest(http.MethodGet, "/v1/catalog/nodes?wait=60s&index=foo", nil) if err != nil { t.Fatalf("err: %v", err) @@ -480,20 +480,20 @@ func TestParseConsistency(t *testing.T) { testCases := [2]string{"/v1/catalog/nodes?stale", "/v1/catalog/nodes?stale=true"} for _, urlPath := range testCases { - req, err := http.NewRequest("GET", urlPath, nil) + req, err := http.NewRequest(http.MethodGet, urlPath, nil) must.NoError(t, err) resp = httptest.NewRecorder() parseConsistency(resp, req, &b) must.True(t, b.AllowStale) } - req, err := http.NewRequest("GET", "/v1/catalog/nodes?stale=false", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/catalog/nodes?stale=false", nil) must.NoError(t, err) resp = httptest.NewRecorder() parseConsistency(resp, req, &b) must.False(t, b.AllowStale) - req, err = http.NewRequest("GET", "/v1/catalog/nodes?stale=random", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/catalog/nodes?stale=random", nil) must.NoError(t, err) resp = httptest.NewRecorder() parseConsistency(resp, req, &b) @@ -501,7 +501,7 @@ func TestParseConsistency(t *testing.T) { must.EqOp(t, 400, resp.Code) b = structs.QueryOptions{} - req, err = http.NewRequest("GET", "/v1/catalog/nodes?consistent", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/catalog/nodes?consistent", nil) must.NoError(t, err) resp = httptest.NewRecorder() @@ -514,7 +514,7 @@ func TestParseRegion(t *testing.T) { s := makeHTTPServer(t, nil) defer s.Shutdown() - req, err := http.NewRequest("GET", + req, err := http.NewRequest(http.MethodGet, "/v1/jobs?region=foo", nil) if err != nil { t.Fatalf("err: %v", err) @@ -527,7 +527,7 @@ func TestParseRegion(t *testing.T) { } region = "" - req, err = http.NewRequest("GET", "/v1/jobs", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/jobs", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -572,7 +572,7 @@ func TestParseToken(t *testing.T) { for i := range cases { tc := cases[i] t.Run(tc.Name, func(t *testing.T) { - req, err := http.NewRequest("GET", "/v1/jobs", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/jobs", nil) req.Header.Add(tc.HeaderKey, tc.HeaderValue) if err != nil { t.Fatalf("err: %v", err) @@ -712,7 +712,7 @@ func TestParsePagination(t *testing.T) { tc := cases[i] t.Run("Input-"+tc.Input, func(t *testing.T) { - req, err := http.NewRequest("GET", + req, err := http.NewRequest(http.MethodGet, "/v1/volumes/csi/external?"+tc.Input, nil) require.NoError(t, err) @@ -763,7 +763,7 @@ func TestHTTP_VerifyHTTPSClient(t *testing.T) { reqURL := fmt.Sprintf("https://%s/v1/agent/self", s.Agent.config.AdvertiseAddrs.HTTP) - request, err := http.NewRequest("GET", reqURL, nil) + request, err := http.NewRequest(http.MethodGet, reqURL, nil) must.NoError(t, err, must.Sprintf("error creating request: %v", err)) resp, err := clnt.Do(request) @@ -796,7 +796,7 @@ func TestHTTP_VerifyHTTPSClient(t *testing.T) { } transport := &http.Transport{TLSClientConfig: tlsConf} client := &http.Client{Transport: transport} - req, err := http.NewRequest("GET", reqURL, nil) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) if err != nil { t.Fatalf("error creating request: %v", err) } @@ -824,7 +824,7 @@ func TestHTTP_VerifyHTTPSClient(t *testing.T) { } tlsConf.RootCAs = x509.NewCertPool() tlsConf.RootCAs.AppendCertsFromPEM(cacertBytes) - req, err = http.NewRequest("GET", reqURL, nil) + req, err = http.NewRequest(http.MethodGet, reqURL, nil) if err != nil { t.Fatalf("error creating request: %v", err) } @@ -859,7 +859,7 @@ func TestHTTP_VerifyHTTPSClient(t *testing.T) { } transport = &http.Transport{TLSClientConfig: tlsConf} client = &http.Client{Transport: transport} - req, err = http.NewRequest("GET", reqURL, nil) + req, err = http.NewRequest(http.MethodGet, reqURL, nil) if err != nil { t.Fatalf("error creating request: %v", err) } @@ -868,7 +868,7 @@ func TestHTTP_VerifyHTTPSClient(t *testing.T) { t.Fatalf("unexpected error: %v", err) } resp.Body.Close() - if resp.StatusCode != 200 { + if resp.StatusCode != http.StatusOK { t.Fatalf("expected 200 status code but got: %d", resp.StatusCode) } } @@ -934,7 +934,7 @@ func TestHTTP_VerifyHTTPSClient_AfterConfigReload(t *testing.T) { transport := &http.Transport{TLSClientConfig: tlsConf} client := &http.Client{Transport: transport} - req, err := http.NewRequest("GET", httpsReqURL, nil) + req, err := http.NewRequest(http.MethodGet, httpsReqURL, nil) assert.Nil(err) // Check that we get an error that the certificate isn't valid for the @@ -965,7 +965,7 @@ func TestHTTP_VerifyHTTPSClient_AfterConfigReload(t *testing.T) { transport = &http.Transport{TLSClientConfig: tlsConf} client = &http.Client{Transport: transport} - req, err = http.NewRequest("GET", httpsReqURL, nil) + req, err = http.NewRequest(http.MethodGet, httpsReqURL, nil) assert.Nil(err) resp, err := client.Do(req) diff --git a/command/agent/job_endpoint.go b/command/agent/job_endpoint.go index fe6f32251e1..103c0307ed1 100644 --- a/command/agent/job_endpoint.go +++ b/command/agent/job_endpoint.go @@ -22,9 +22,9 @@ const jobNotFoundErr = "job not found" func (s *HTTPServer) JobsRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { switch req.Method { - case "GET": + case http.MethodGet: return s.jobListRequest(resp, req) - case "PUT", "POST": + case http.MethodPut, http.MethodPost: return s.jobUpdate(resp, req, "") default: return nil, CodedError(405, ErrInvalidMethod) @@ -231,7 +231,7 @@ func (s *HTTPServer) periodicForceRequest(resp http.ResponseWriter, req *http.Re } func (s *HTTPServer) jobAllocations(resp http.ResponseWriter, req *http.Request, jobID string) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } allAllocs, _ := strconv.ParseBool(req.URL.Query().Get("all")) @@ -260,7 +260,7 @@ func (s *HTTPServer) jobAllocations(resp http.ResponseWriter, req *http.Request, } func (s *HTTPServer) jobEvaluations(resp http.ResponseWriter, req *http.Request, jobID string) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } args := structs.JobSpecificRequest{ @@ -283,7 +283,7 @@ func (s *HTTPServer) jobEvaluations(resp http.ResponseWriter, req *http.Request, } func (s *HTTPServer) jobDeployments(resp http.ResponseWriter, req *http.Request, jobID string) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } all, _ := strconv.ParseBool(req.URL.Query().Get("all")) @@ -308,7 +308,7 @@ func (s *HTTPServer) jobDeployments(resp http.ResponseWriter, req *http.Request, } func (s *HTTPServer) jobLatestDeployment(resp http.ResponseWriter, req *http.Request, jobID string) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } args := structs.JobSpecificRequest{ @@ -329,11 +329,11 @@ func (s *HTTPServer) jobLatestDeployment(resp http.ResponseWriter, req *http.Req func (s *HTTPServer) jobCRUD(resp http.ResponseWriter, req *http.Request, jobID string) (interface{}, error) { switch req.Method { - case "GET": + case http.MethodGet: return s.jobQuery(resp, req, jobID) - case "PUT", "POST": + case http.MethodPut, http.MethodPost: return s.jobUpdate(resp, req, jobID) - case "DELETE": + case http.MethodDelete: return s.jobDelete(resp, req, jobID) default: return nil, CodedError(405, ErrInvalidMethod) @@ -499,9 +499,9 @@ func (s *HTTPServer) jobDelete(resp http.ResponseWriter, req *http.Request, jobI func (s *HTTPServer) jobScale(resp http.ResponseWriter, req *http.Request, jobID string) (interface{}, error) { switch req.Method { - case "GET": + case http.MethodGet: return s.jobScaleStatus(resp, req, jobID) - case "PUT", "POST": + case http.MethodPut, http.MethodPost: return s.jobScaleAction(resp, req, jobID) default: return nil, CodedError(405, ErrInvalidMethod) diff --git a/command/agent/job_endpoint_test.go b/command/agent/job_endpoint_test.go index ad65cc9c46b..9b3dcd4f78c 100644 --- a/command/agent/job_endpoint_test.go +++ b/command/agent/job_endpoint_test.go @@ -41,7 +41,7 @@ func TestHTTP_JobsList(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/jobs", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/jobs", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -100,7 +100,7 @@ func TestHTTP_PrefixJobsList(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/jobs?prefix=aabb", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/jobs?prefix=aabb", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -150,7 +150,7 @@ func TestHTTP_JobsList_AllNamespaces_OSS(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/jobs?namespace=*", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/jobs?namespace=*", nil) require.NoError(t, err) respW := httptest.NewRecorder() @@ -183,7 +183,7 @@ func TestHTTP_JobsRegister(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/jobs", buf) + req, err := http.NewRequest(http.MethodPut, "/v1/jobs", buf) if err != nil { t.Fatalf("err: %v", err) } @@ -239,7 +239,7 @@ func TestHTTP_JobsRegister_IgnoresParentID(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/jobs", buf) + req, err := http.NewRequest(http.MethodPut, "/v1/jobs", buf) require.NoError(t, err) respW := httptest.NewRecorder() @@ -302,7 +302,7 @@ func TestHTTP_JobsRegister_ACL(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/jobs", buf) + req, err := http.NewRequest(http.MethodPut, "/v1/jobs", buf) if err != nil { t.Fatalf("err: %v", err) } @@ -334,7 +334,7 @@ func TestHTTP_JobsRegister_Defaulting(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/jobs", buf) + req, err := http.NewRequest(http.MethodPut, "/v1/jobs", buf) if err != nil { t.Fatalf("err: %v", err) } @@ -383,7 +383,7 @@ func TestHTTP_JobsParse(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { buf := encodeReq(api.JobsParseRequest{JobHCL: mock.HCL()}) - req, err := http.NewRequest("POST", "/v1/jobs/parse", buf) + req, err := http.NewRequest(http.MethodPost, "/v1/jobs/parse", buf) if err != nil { t.Fatalf("err: %v", err) } @@ -502,7 +502,7 @@ func TestHTTP_JobsParse_ACL(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { buf := encodeReq(api.JobsParseRequest{JobHCL: mock.HCL()}) - req, err := http.NewRequest("POST", "/v1/jobs/parse", buf) + req, err := http.NewRequest(http.MethodPost, "/v1/jobs/parse", buf) require.NoError(t, err) if tc.namespace != "" { @@ -551,7 +551,7 @@ func TestHTTP_JobQuery(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/job/"+job.ID, nil) + req, err := http.NewRequest(http.MethodGet, "/v1/job/"+job.ID, nil) if err != nil { t.Fatalf("err: %v", err) } @@ -600,7 +600,7 @@ func TestHTTP_JobQuery_Payload(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/job/"+job.ID, nil) + req, err := http.NewRequest(http.MethodGet, "/v1/job/"+job.ID, nil) if err != nil { t.Fatalf("err: %v", err) } @@ -653,7 +653,7 @@ func TestHTTP_jobUpdate_systemScaling(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/job/"+*job.ID, buf) + req, err := http.NewRequest(http.MethodPut, "/v1/job/"+*job.ID, buf) if err != nil { t.Fatalf("err: %v", err) } @@ -681,7 +681,7 @@ func TestHTTP_JobUpdate(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/job/"+*job.ID, buf) + req, err := http.NewRequest(http.MethodPut, "/v1/job/"+*job.ID, buf) if err != nil { t.Fatalf("err: %v", err) } @@ -769,7 +769,7 @@ func TestHTTP_JobUpdate_EvalPriority(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/job/"+*job.ID, buf) + req, err := http.NewRequest(http.MethodPut, "/v1/job/"+*job.ID, buf) assert.Nil(t, err) respW := httptest.NewRecorder() @@ -800,7 +800,7 @@ func TestHTTP_JobUpdate_EvalPriority(t *testing.T) { assert.NotNil(t, getResp.Job) // Check the evaluation that resulted from the job register. - evalInfoReq, err := http.NewRequest("GET", "/v1/evaluation/"+regResp.EvalID, nil) + evalInfoReq, err := http.NewRequest(http.MethodGet, "/v1/evaluation/"+regResp.EvalID, nil) assert.Nil(t, err) respW.Flush() @@ -884,7 +884,7 @@ func TestHTTP_JobUpdateRegion(t *testing.T) { // Make the HTTP request url := "/v1/job/" + *job.ID - req, err := http.NewRequest("PUT", url, buf) + req, err := http.NewRequest(http.MethodPut, url, buf) require.NoError(t, err) respW := httptest.NewRecorder() @@ -935,7 +935,7 @@ func TestHTTP_JobDelete(t *testing.T) { } // Make the HTTP request to do a soft delete - req, err := http.NewRequest("DELETE", "/v1/job/"+job.ID, nil) + req, err := http.NewRequest(http.MethodDelete, "/v1/job/"+job.ID, nil) if err != nil { t.Fatalf("err: %v", err) } @@ -978,7 +978,7 @@ func TestHTTP_JobDelete(t *testing.T) { } // Make the HTTP request to do a purge delete - req2, err := http.NewRequest("DELETE", "/v1/job/"+job.ID+"?purge=true", nil) + req2, err := http.NewRequest(http.MethodDelete, "/v1/job/"+job.ID+"?purge=true", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -1060,7 +1060,7 @@ func TestHTTP_JobDelete_EvalPriority(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - regReq, err := http.NewRequest("PUT", "/v1/job/"+*job.ID, buf) + regReq, err := http.NewRequest(http.MethodPut, "/v1/job/"+*job.ID, buf) assert.Nil(t, err) respW := httptest.NewRecorder() @@ -1086,7 +1086,7 @@ func TestHTTP_JobDelete_EvalPriority(t *testing.T) { assert.NotNil(t, getResp.Job) // Delete the job. - deleteReq, err := http.NewRequest("DELETE", "/v1/job/"+*job.ID+"?purge=true", nil) + deleteReq, err := http.NewRequest(http.MethodDelete, "/v1/job/"+*job.ID+"?purge=true", nil) assert.Nil(t, err) respW.Flush() @@ -1112,7 +1112,7 @@ func TestHTTP_JobDelete_EvalPriority(t *testing.T) { assert.NotEmpty(t, respW.Result().Header.Get("X-Nomad-Index")) // Check the evaluation that resulted from the job register. - evalInfoReq, err := http.NewRequest("GET", "/v1/evaluation/"+dereg.EvalID, nil) + evalInfoReq, err := http.NewRequest(http.MethodGet, "/v1/evaluation/"+dereg.EvalID, nil) assert.Nil(t, err) respW.Flush() @@ -1160,7 +1160,7 @@ func TestHTTP_Job_ScaleTaskGroup(t *testing.T) { buf := encodeReq(scaleReq) // Make the HTTP request to scale the job group - req, err := http.NewRequest("POST", "/v1/job/"+job.ID+"/scale", buf) + req, err := http.NewRequest(http.MethodPost, "/v1/job/"+job.ID+"/scale", buf) require.NoError(err) respW := httptest.NewRecorder() @@ -1212,7 +1212,7 @@ func TestHTTP_Job_ScaleStatus(t *testing.T) { } // Make the HTTP request to scale the job group - req, err := http.NewRequest("GET", "/v1/job/"+job.ID+"/scale", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/job/"+job.ID+"/scale", nil) require.NoError(err) respW := httptest.NewRecorder() @@ -1248,7 +1248,7 @@ func TestHTTP_JobForceEvaluate(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("POST", "/v1/job/"+job.ID+"/evaluate", nil) + req, err := http.NewRequest(http.MethodPost, "/v1/job/"+job.ID+"/evaluate", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -1299,7 +1299,7 @@ func TestHTTP_JobEvaluate_ForceReschedule(t *testing.T) { buf := encodeReq(jobEvalReq) // Make the HTTP request - req, err := http.NewRequest("POST", "/v1/job/"+job.ID+"/evaluate", buf) + req, err := http.NewRequest(http.MethodPost, "/v1/job/"+job.ID+"/evaluate", buf) if err != nil { t.Fatalf("err: %v", err) } @@ -1342,7 +1342,7 @@ func TestHTTP_JobEvaluations(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/job/"+job.ID+"/evaluations", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/job/"+job.ID+"/evaluations", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -1407,7 +1407,7 @@ func TestHTTP_JobAllocations(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/job/"+alloc1.Job.ID+"/allocations?all=true", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/job/"+alloc1.Job.ID+"/allocations?all=true", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -1465,7 +1465,7 @@ func TestHTTP_JobDeployments(t *testing.T) { assert.Nil(state.UpsertDeployment(1000, d), "UpsertDeployment") // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/job/"+j.ID+"/deployments", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/job/"+j.ID+"/deployments", nil) assert.Nil(err, "HTTP") respW := httptest.NewRecorder() @@ -1508,7 +1508,7 @@ func TestHTTP_JobDeployment(t *testing.T) { assert.Nil(state.UpsertDeployment(1000, d), "UpsertDeployment") // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/job/"+j.ID+"/deployment", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/job/"+j.ID+"/deployment", nil) assert.Nil(err, "HTTP") respW := httptest.NewRecorder() @@ -1561,7 +1561,7 @@ func TestHTTP_JobVersions(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/job/"+job.ID+"/versions?diffs=true", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/job/"+job.ID+"/versions?diffs=true", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -1623,7 +1623,7 @@ func TestHTTP_PeriodicForce(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("POST", "/v1/job/"+job.ID+"/periodic/force", nil) + req, err := http.NewRequest(http.MethodPost, "/v1/job/"+job.ID+"/periodic/force", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -1664,7 +1664,7 @@ func TestHTTP_JobPlan(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/job/"+*job.ID+"/plan", buf) + req, err := http.NewRequest(http.MethodPut, "/v1/job/"+*job.ID+"/plan", buf) if err != nil { t.Fatalf("err: %v", err) } @@ -1746,7 +1746,7 @@ func TestHTTP_JobPlanRegion(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/job/"+*job.ID+"/plan", buf) + req, err := http.NewRequest(http.MethodPut, "/v1/job/"+*job.ID+"/plan", buf) require.NoError(t, err) respW := httptest.NewRecorder() @@ -1794,7 +1794,7 @@ func TestHTTP_JobDispatch(t *testing.T) { buf := encodeReq(args2) // Make the HTTP request - req2, err := http.NewRequest("PUT", "/v1/job/"+job.ID+"/dispatch", buf) + req2, err := http.NewRequest(http.MethodPut, "/v1/job/"+job.ID+"/dispatch", buf) if err != nil { t.Fatalf("err: %v", err) } @@ -1852,7 +1852,7 @@ func TestHTTP_JobRevert(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/job/"+job.ID+"/revert", buf) + req, err := http.NewRequest(http.MethodPut, "/v1/job/"+job.ID+"/revert", buf) if err != nil { t.Fatalf("err: %v", err) } @@ -1910,7 +1910,7 @@ func TestHTTP_JobStable(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/job/"+job.ID+"/stable", buf) + req, err := http.NewRequest(http.MethodPut, "/v1/job/"+job.ID+"/stable", buf) if err != nil { t.Fatalf("err: %v", err) } @@ -2047,7 +2047,7 @@ func TestJobs_ParsingWriteRequest(t *testing.T) { Multiregion: tc.multiregion, } - req, _ := http.NewRequest("POST", "/", nil) + req, _ := http.NewRequest(http.MethodPost, "/", nil) if tc.queryToken != "" { req.Header.Set("X-Nomad-Token", tc.queryToken) } @@ -2533,7 +2533,7 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { Args: []string{"a", "b"}, Path: "/check", Protocol: "http", - Method: "POST", + Method: http.MethodPost, Body: "{\"check\":\"mem\"}", PortLabel: "foo", AddressMode: "driver", @@ -2943,7 +2943,7 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { Args: []string{"a", "b"}, Path: "/check", Protocol: "http", - Method: "POST", + Method: http.MethodPost, Body: "{\"check\":\"mem\"}", PortLabel: "foo", AddressMode: "driver", @@ -3556,7 +3556,7 @@ func TestHTTP_JobValidate_SystemMigrate(t *testing.T) { buf := encodeReq(args) // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/validate/job", buf) + req, err := http.NewRequest(http.MethodPut, "/v1/validate/job", buf) must.NoError(t, err) respW := httptest.NewRecorder() diff --git a/command/agent/metrics_endpoint.go b/command/agent/metrics_endpoint.go index 90686cb3e41..ec13a02591d 100644 --- a/command/agent/metrics_endpoint.go +++ b/command/agent/metrics_endpoint.go @@ -17,7 +17,7 @@ var ( // MetricsRequest returns metrics for the agent. Metrics are JSON by default // but Prometheus is an optional format. func (s *HTTPServer) MetricsRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } diff --git a/command/agent/metrics_endpoint_test.go b/command/agent/metrics_endpoint_test.go index 787f114b5f8..d19ed8f9edb 100644 --- a/command/agent/metrics_endpoint_test.go +++ b/command/agent/metrics_endpoint_test.go @@ -21,7 +21,7 @@ func TestHTTP_MetricsWithIllegalMethod(t *testing.T) { assert := assert.New(t) httpTest(t, nil, func(s *TestAgent) { - req, err := http.NewRequest("DELETE", "/v1/metrics", nil) + req, err := http.NewRequest(http.MethodDelete, "/v1/metrics", nil) assert.Nil(err) respW := httptest.NewRecorder() @@ -35,7 +35,7 @@ func TestHTTP_MetricsPrometheusDisabled(t *testing.T) { assert := assert.New(t) httpTest(t, func(c *Config) { c.Telemetry.PrometheusMetrics = false }, func(s *TestAgent) { - req, err := http.NewRequest("GET", "/v1/metrics?format=prometheus", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/metrics?format=prometheus", nil) assert.Nil(err) resp, err := s.Server.MetricsRequest(nil, req) @@ -49,7 +49,7 @@ func TestHTTP_MetricsPrometheusEnabled(t *testing.T) { assert := assert.New(t) httpTest(t, nil, func(s *TestAgent) { - req, err := http.NewRequest("GET", "/v1/metrics?format=prometheus", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/metrics?format=prometheus", nil) assert.Nil(err) respW := httptest.NewRecorder() @@ -71,14 +71,14 @@ func TestHTTP_Metrics(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { // make a separate HTTP request first, to ensure Nomad has written metrics // and prevent a race condition - req, err := http.NewRequest("GET", "/v1/agent/self", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/agent/self", nil) assert.Nil(err) respW := httptest.NewRecorder() s.Server.AgentSelfRequest(respW, req) // now make a metrics endpoint request, which should be already initialized // and written to - req, err = http.NewRequest("GET", "/v1/metrics", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/metrics", nil) assert.Nil(err) respW = httptest.NewRecorder() @@ -133,7 +133,7 @@ func TestHTTP_FreshClientAllocMetrics(t *testing.T) { var pending, running, terminal float32 = -1.0, -1.0, -1.0 testutil.WaitForResultRetries(100, func() (bool, error) { time.Sleep(100 * time.Millisecond) - req, err := http.NewRequest("GET", "/v1/metrics", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/metrics", nil) require.NoError(err) respW := httptest.NewRecorder() diff --git a/command/agent/namespace_endpoint.go b/command/agent/namespace_endpoint.go index ccea00bd2b4..ddfe1052b43 100644 --- a/command/agent/namespace_endpoint.go +++ b/command/agent/namespace_endpoint.go @@ -8,7 +8,7 @@ import ( ) func (s *HTTPServer) NamespacesRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } @@ -35,11 +35,11 @@ func (s *HTTPServer) NamespaceSpecificRequest(resp http.ResponseWriter, req *htt return nil, CodedError(400, "Missing Namespace Name") } switch req.Method { - case "GET": + case http.MethodGet: return s.namespaceQuery(resp, req, name) - case "PUT", "POST": + case http.MethodPut, http.MethodPost: return s.namespaceUpdate(resp, req, name) - case "DELETE": + case http.MethodDelete: return s.namespaceDelete(resp, req, name) default: return nil, CodedError(405, ErrInvalidMethod) @@ -47,7 +47,7 @@ func (s *HTTPServer) NamespaceSpecificRequest(resp http.ResponseWriter, req *htt } func (s *HTTPServer) NamespaceCreateRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "PUT" && req.Method != "POST" { + if req.Method != http.MethodPut && req.Method != http.MethodPost { return nil, CodedError(405, ErrInvalidMethod) } diff --git a/command/agent/namespace_endpoint_test.go b/command/agent/namespace_endpoint_test.go index b488fe16a81..9e2338c934a 100644 --- a/command/agent/namespace_endpoint_test.go +++ b/command/agent/namespace_endpoint_test.go @@ -26,7 +26,7 @@ func TestHTTP_NamespaceList(t *testing.T) { assert.Nil(s.Agent.RPC("Namespace.UpsertNamespaces", &args, &resp)) // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/namespaces", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/namespaces", nil) assert.Nil(err) respW := httptest.NewRecorder() @@ -57,7 +57,7 @@ func TestHTTP_NamespaceQuery(t *testing.T) { assert.Nil(s.Agent.RPC("Namespace.UpsertNamespaces", &args, &resp)) // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/namespace/"+ns1.Name, nil) + req, err := http.NewRequest(http.MethodGet, "/v1/namespace/"+ns1.Name, nil) assert.Nil(err) respW := httptest.NewRecorder() @@ -82,7 +82,7 @@ func TestHTTP_NamespaceCreate(t *testing.T) { // Make the HTTP request ns1 := mock.Namespace() buf := encodeReq(ns1) - req, err := http.NewRequest("PUT", "/v1/namespace", buf) + req, err := http.NewRequest(http.MethodPut, "/v1/namespace", buf) assert.Nil(err) respW := httptest.NewRecorder() @@ -113,7 +113,7 @@ func TestHTTP_NamespaceUpdate(t *testing.T) { // Make the HTTP request ns1 := mock.Namespace() buf := encodeReq(ns1) - req, err := http.NewRequest("PUT", "/v1/namespace/"+ns1.Name, buf) + req, err := http.NewRequest(http.MethodPut, "/v1/namespace/"+ns1.Name, buf) assert.Nil(err) respW := httptest.NewRecorder() @@ -150,7 +150,7 @@ func TestHTTP_NamespaceDelete(t *testing.T) { assert.Nil(s.Agent.RPC("Namespace.UpsertNamespaces", &args, &resp)) // Make the HTTP request - req, err := http.NewRequest("DELETE", "/v1/namespace/"+ns1.Name, nil) + req, err := http.NewRequest(http.MethodDelete, "/v1/namespace/"+ns1.Name, nil) assert.Nil(err) respW := httptest.NewRecorder() diff --git a/command/agent/node_endpoint.go b/command/agent/node_endpoint.go index 046227dbb23..9c72e618b69 100644 --- a/command/agent/node_endpoint.go +++ b/command/agent/node_endpoint.go @@ -9,7 +9,7 @@ import ( ) func (s *HTTPServer) NodesRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } @@ -76,7 +76,7 @@ func (s *HTTPServer) NodeSpecificRequest(resp http.ResponseWriter, req *http.Req func (s *HTTPServer) nodeForceEvaluate(resp http.ResponseWriter, req *http.Request, nodeID string) (interface{}, error) { - if req.Method != "PUT" && req.Method != "POST" { + if req.Method != http.MethodPut && req.Method != http.MethodPost { return nil, CodedError(405, ErrInvalidMethod) } args := structs.NodeEvaluateRequest{ @@ -94,7 +94,7 @@ func (s *HTTPServer) nodeForceEvaluate(resp http.ResponseWriter, req *http.Reque func (s *HTTPServer) nodeAllocations(resp http.ResponseWriter, req *http.Request, nodeID string) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } args := structs.NodeSpecificRequest{ @@ -121,7 +121,7 @@ func (s *HTTPServer) nodeAllocations(resp http.ResponseWriter, req *http.Request func (s *HTTPServer) nodeToggleDrain(resp http.ResponseWriter, req *http.Request, nodeID string) (interface{}, error) { - if req.Method != "PUT" && req.Method != "POST" { + if req.Method != http.MethodPut && req.Method != http.MethodPost { return nil, CodedError(405, ErrInvalidMethod) } @@ -157,7 +157,7 @@ func (s *HTTPServer) nodeToggleDrain(resp http.ResponseWriter, req *http.Request func (s *HTTPServer) nodeToggleEligibility(resp http.ResponseWriter, req *http.Request, nodeID string) (interface{}, error) { - if req.Method != "PUT" && req.Method != "POST" { + if req.Method != http.MethodPut && req.Method != http.MethodPost { return nil, CodedError(405, ErrInvalidMethod) } @@ -181,7 +181,7 @@ func (s *HTTPServer) nodeToggleEligibility(resp http.ResponseWriter, req *http.R func (s *HTTPServer) nodeQuery(resp http.ResponseWriter, req *http.Request, nodeID string) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } args := structs.NodeSpecificRequest{ @@ -204,7 +204,7 @@ func (s *HTTPServer) nodeQuery(resp http.ResponseWriter, req *http.Request, } func (s *HTTPServer) nodePurge(resp http.ResponseWriter, req *http.Request, nodeID string) (interface{}, error) { - if req.Method != "PUT" && req.Method != "POST" { + if req.Method != http.MethodPut && req.Method != http.MethodPost { return nil, CodedError(405, ErrInvalidMethod) } args := structs.NodeDeregisterRequest{ diff --git a/command/agent/node_endpoint_test.go b/command/agent/node_endpoint_test.go index 406879a93ad..4fb8a32c34b 100644 --- a/command/agent/node_endpoint_test.go +++ b/command/agent/node_endpoint_test.go @@ -31,7 +31,7 @@ func TestHTTP_NodesList(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/nodes", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/nodes", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -88,7 +88,7 @@ func TestHTTP_NodesPrefixList(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/nodes?prefix=12345678", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/nodes?prefix=12345678", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -146,7 +146,7 @@ func TestHTTP_NodesOSList(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/nodes?prefix=123456&os=true", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/nodes?prefix=123456&os=true", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -210,7 +210,7 @@ func TestHTTP_NodeForceEval(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("POST", "/v1/node/"+node.ID+"/evaluate", nil) + req, err := http.NewRequest(http.MethodPost, "/v1/node/"+node.ID+"/evaluate", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -270,7 +270,7 @@ func TestHTTP_NodeAllocations(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/node/"+node.ID+"/allocations", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/node/"+node.ID+"/allocations", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -331,7 +331,7 @@ func TestHTTP_NodeDrain(t *testing.T) { // Make the HTTP request buf := encodeReq(drainReq) - req, err := http.NewRequest("POST", "/v1/node/"+node.ID+"/drain", buf) + req, err := http.NewRequest(http.MethodPost, "/v1/node/"+node.ID+"/drain", buf) require.Nil(err) respW := httptest.NewRecorder() @@ -373,7 +373,7 @@ func TestHTTP_NodeDrain(t *testing.T) { "cancel_reason": "changed my mind", } buf = encodeReq(drainReq) - req, err = http.NewRequest("POST", "/v1/node/"+node.ID+"/drain", buf) + req, err = http.NewRequest(http.MethodPost, "/v1/node/"+node.ID+"/drain", buf) require.Nil(err) respW = httptest.NewRecorder() @@ -419,7 +419,7 @@ func TestHTTP_NodeEligible(t *testing.T) { // Make the HTTP request buf := encodeReq(eligibilityReq) - req, err := http.NewRequest("POST", "/v1/node/"+node.ID+"/eligibility", buf) + req, err := http.NewRequest(http.MethodPost, "/v1/node/"+node.ID+"/eligibility", buf) require.Nil(err) respW := httptest.NewRecorder() @@ -443,7 +443,7 @@ func TestHTTP_NodeEligible(t *testing.T) { // Make the HTTP request to set something invalid eligibilityReq.Eligibility = "foo" buf = encodeReq(eligibilityReq) - req, err = http.NewRequest("POST", "/v1/node/"+node.ID+"/eligibility", buf) + req, err = http.NewRequest(http.MethodPost, "/v1/node/"+node.ID+"/eligibility", buf) require.Nil(err) respW = httptest.NewRecorder() @@ -481,7 +481,7 @@ func TestHTTP_NodePurge(t *testing.T) { } // Make the HTTP request to purge it - req, err := http.NewRequest("POST", "/v1/node/"+node.ID+"/purge", nil) + req, err := http.NewRequest(http.MethodPost, "/v1/node/"+node.ID+"/purge", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -534,7 +534,7 @@ func TestHTTP_NodeQuery(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/node/"+node.ID, nil) + req, err := http.NewRequest(http.MethodGet, "/v1/node/"+node.ID, nil) if err != nil { t.Fatalf("err: %v", err) } diff --git a/command/agent/operator_endpoint.go b/command/agent/operator_endpoint.go index 4c8d278cd1d..d69047da79b 100644 --- a/command/agent/operator_endpoint.go +++ b/command/agent/operator_endpoint.go @@ -35,7 +35,7 @@ func (s *HTTPServer) OperatorRequest(resp http.ResponseWriter, req *http.Request // OperatorRaftConfiguration is used to inspect the current Raft configuration. // This supports the stale query mode in case the cluster doesn't have a leader. func (s *HTTPServer) OperatorRaftConfiguration(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { resp.WriteHeader(http.StatusMethodNotAllowed) return nil, nil } @@ -56,7 +56,7 @@ func (s *HTTPServer) OperatorRaftConfiguration(resp http.ResponseWriter, req *ht // OperatorRaftPeer supports actions on Raft peers. Currently we only support // removing peers by address. func (s *HTTPServer) OperatorRaftPeer(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "DELETE" { + if req.Method != http.MethodDelete { return nil, CodedError(404, ErrInvalidMethod) } @@ -99,7 +99,7 @@ func (s *HTTPServer) OperatorRaftPeer(resp http.ResponseWriter, req *http.Reques func (s *HTTPServer) OperatorAutopilotConfiguration(resp http.ResponseWriter, req *http.Request) (interface{}, error) { // Switch on the method switch req.Method { - case "GET": + case http.MethodGet: var args structs.GenericRequest if done := s.parse(resp, req, &args.Region, &args.QueryOptions); done { return nil, nil @@ -125,7 +125,7 @@ func (s *HTTPServer) OperatorAutopilotConfiguration(resp http.ResponseWriter, re return out, nil - case "PUT": + case http.MethodPut: var args structs.AutopilotSetConfigRequest s.parseWriteRequest(req, &args.WriteRequest) @@ -174,7 +174,7 @@ func (s *HTTPServer) OperatorAutopilotConfiguration(resp http.ResponseWriter, re // OperatorServerHealth is used to get the health of the servers in the given Region. func (s *HTTPServer) OperatorServerHealth(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(404, ErrInvalidMethod) } @@ -222,10 +222,10 @@ func (s *HTTPServer) OperatorServerHealth(resp http.ResponseWriter, req *http.Re func (s *HTTPServer) OperatorSchedulerConfiguration(resp http.ResponseWriter, req *http.Request) (interface{}, error) { // Switch on the method switch req.Method { - case "GET": + case http.MethodGet: return s.schedulerGetConfig(resp, req) - case "PUT", "POST": + case http.MethodPut, http.MethodPost: return s.schedulerUpdateConfig(resp, req) default: @@ -294,9 +294,9 @@ func (s *HTTPServer) schedulerUpdateConfig(resp http.ResponseWriter, req *http.R func (s *HTTPServer) SnapshotRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { switch req.Method { - case "GET": + case http.MethodGet: return s.snapshotSaveRequest(resp, req) - case "PUT", "POST": + case http.MethodPut, http.MethodPost: return s.snapshotRestoreRequest(resp, req) default: return nil, CodedError(405, ErrInvalidMethod) diff --git a/command/agent/operator_endpoint_oss.go b/command/agent/operator_endpoint_oss.go index 8467c907bea..900b6aee433 100644 --- a/command/agent/operator_endpoint_oss.go +++ b/command/agent/operator_endpoint_oss.go @@ -9,10 +9,10 @@ import ( func (s *HTTPServer) LicenseRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { switch req.Method { - case "GET": + case http.MethodGet: resp.WriteHeader(http.StatusNoContent) return nil, nil - case "PUT": + case http.MethodPut: return nil, CodedError(501, ErrEntOnly) default: return nil, CodedError(405, ErrInvalidMethod) diff --git a/command/agent/operator_endpoint_test.go b/command/agent/operator_endpoint_test.go index cbfed043530..187d2478062 100644 --- a/command/agent/operator_endpoint_test.go +++ b/command/agent/operator_endpoint_test.go @@ -29,7 +29,7 @@ func TestHTTP_OperatorRaftConfiguration(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { body := bytes.NewBuffer(nil) - req, err := http.NewRequest("GET", "/v1/operator/raft/configuration", body) + req, err := http.NewRequest(http.MethodGet, "/v1/operator/raft/configuration", body) if err != nil { t.Fatalf("err: %v", err) } @@ -59,7 +59,7 @@ func TestHTTP_OperatorRaftPeer(t *testing.T) { assert := assert.New(t) httpTest(t, nil, func(s *TestAgent) { body := bytes.NewBuffer(nil) - req, err := http.NewRequest("DELETE", "/v1/operator/raft/peer?address=nope", body) + req, err := http.NewRequest(http.MethodDelete, "/v1/operator/raft/peer?address=nope", body) assert.Nil(err) // If we get this error, it proves we sent the address all the @@ -74,7 +74,7 @@ func TestHTTP_OperatorRaftPeer(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { body := bytes.NewBuffer(nil) - req, err := http.NewRequest("DELETE", "/v1/operator/raft/peer?id=nope", body) + req, err := http.NewRequest(http.MethodDelete, "/v1/operator/raft/peer?id=nope", body) assert.Nil(err) // If we get this error, it proves we sent the address all the @@ -92,13 +92,13 @@ func TestOperator_AutopilotGetConfiguration(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { body := bytes.NewBuffer(nil) - req, _ := http.NewRequest("GET", "/v1/operator/autopilot/configuration", body) + req, _ := http.NewRequest(http.MethodGet, "/v1/operator/autopilot/configuration", body) resp := httptest.NewRecorder() obj, err := s.Server.OperatorAutopilotConfiguration(resp, req) if err != nil { t.Fatalf("err: %v", err) } - if resp.Code != 200 { + if resp.Code != http.StatusOK { t.Fatalf("bad code: %d", resp.Code) } out, ok := obj.(api.AutopilotConfiguration) @@ -115,7 +115,7 @@ func TestOperator_AutopilotSetConfiguration(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { body := bytes.NewBuffer([]byte(`{"CleanupDeadServers": false}`)) - req, _ := http.NewRequest("PUT", "/v1/operator/autopilot/configuration", body) + req, _ := http.NewRequest(http.MethodPut, "/v1/operator/autopilot/configuration", body) resp := httptest.NewRecorder() if _, err := s.Server.OperatorAutopilotConfiguration(resp, req); err != nil { t.Fatalf("err: %v", err) @@ -144,7 +144,7 @@ func TestOperator_AutopilotCASConfiguration(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { body := bytes.NewBuffer([]byte(`{"CleanupDeadServers": false}`)) - req, _ := http.NewRequest("PUT", "/v1/operator/autopilot/configuration", body) + req, _ := http.NewRequest(http.MethodPut, "/v1/operator/autopilot/configuration", body) resp := httptest.NewRecorder() if _, err := s.Server.OperatorAutopilotConfiguration(resp, req); err != nil { t.Fatalf("err: %v", err) @@ -171,7 +171,7 @@ func TestOperator_AutopilotCASConfiguration(t *testing.T) { // Create a CAS request, bad index { buf := bytes.NewBuffer([]byte(`{"CleanupDeadServers": true}`)) - req, _ := http.NewRequest("PUT", fmt.Sprintf("/v1/operator/autopilot/configuration?cas=%d", reply.ModifyIndex-1), buf) + req, _ := http.NewRequest(http.MethodPut, fmt.Sprintf("/v1/operator/autopilot/configuration?cas=%d", reply.ModifyIndex-1), buf) resp := httptest.NewRecorder() obj, err := s.Server.OperatorAutopilotConfiguration(resp, req) if err != nil { @@ -186,7 +186,7 @@ func TestOperator_AutopilotCASConfiguration(t *testing.T) { // Create a CAS request, good index { buf := bytes.NewBuffer([]byte(`{"CleanupDeadServers": true}`)) - req, _ := http.NewRequest("PUT", fmt.Sprintf("/v1/operator/autopilot/configuration?cas=%d", reply.ModifyIndex), buf) + req, _ := http.NewRequest(http.MethodPut, fmt.Sprintf("/v1/operator/autopilot/configuration?cas=%d", reply.ModifyIndex), buf) resp := httptest.NewRecorder() obj, err := s.Server.OperatorAutopilotConfiguration(resp, req) if err != nil { @@ -215,7 +215,7 @@ func TestOperator_ServerHealth(t *testing.T) { c.Server.RaftProtocol = 3 }, func(s *TestAgent) { body := bytes.NewBuffer(nil) - req, _ := http.NewRequest("GET", "/v1/operator/autopilot/health", body) + req, _ := http.NewRequest(http.MethodGet, "/v1/operator/autopilot/health", body) f := func() error { resp := httptest.NewRecorder() obj, err := s.Server.OperatorServerHealth(resp, req) @@ -256,7 +256,7 @@ func TestOperator_ServerHealth_Unhealthy(t *testing.T) { c.Autopilot.LastContactThreshold = -1 * time.Second }, func(s *TestAgent) { body := bytes.NewBuffer(nil) - req, _ := http.NewRequest("GET", "/v1/operator/autopilot/health", body) + req, _ := http.NewRequest(http.MethodGet, "/v1/operator/autopilot/health", body) f := func() error { resp := httptest.NewRecorder() obj, err := s.Server.OperatorServerHealth(resp, req) @@ -291,7 +291,7 @@ func TestOperator_SchedulerGetConfiguration(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { body := bytes.NewBuffer(nil) - req, _ := http.NewRequest("GET", "/v1/operator/scheduler/configuration", body) + req, _ := http.NewRequest(http.MethodGet, "/v1/operator/scheduler/configuration", body) resp := httptest.NewRecorder() obj, err := s.Server.OperatorSchedulerConfiguration(resp, req) require.Nil(t, err) @@ -321,7 +321,7 @@ func TestOperator_SchedulerSetConfiguration(t *testing.T) { "ServiceSchedulerEnabled": true } }`)) - req, _ := http.NewRequest("PUT", "/v1/operator/scheduler/configuration", body) + req, _ := http.NewRequest(http.MethodPut, "/v1/operator/scheduler/configuration", body) resp := httptest.NewRecorder() setResp, err := s.Server.OperatorSchedulerConfiguration(resp, req) require.Nil(t, err) @@ -357,7 +357,7 @@ func TestOperator_SchedulerCASConfiguration(t *testing.T) { "SysBatchSchedulerEnabled":true, "BatchSchedulerEnabled":true }}`)) - req, _ := http.NewRequest("PUT", "/v1/operator/scheduler/configuration", body) + req, _ := http.NewRequest(http.MethodPut, "/v1/operator/scheduler/configuration", body) resp := httptest.NewRecorder() setResp, err := s.Server.OperatorSchedulerConfiguration(resp, req) require.Nil(err) @@ -387,7 +387,7 @@ func TestOperator_SchedulerCASConfiguration(t *testing.T) { "SystemSchedulerEnabled": false, "BatchSchedulerEnabled":true }}`)) - req, _ := http.NewRequest("PUT", fmt.Sprintf("/v1/operator/scheduler/configuration?cas=%d", reply.QueryMeta.Index-1), buf) + req, _ := http.NewRequest(http.MethodPut, fmt.Sprintf("/v1/operator/scheduler/configuration?cas=%d", reply.QueryMeta.Index-1), buf) resp := httptest.NewRecorder() setResp, err := s.Server.OperatorSchedulerConfiguration(resp, req) require.Nil(err) @@ -404,7 +404,7 @@ func TestOperator_SchedulerCASConfiguration(t *testing.T) { "SystemSchedulerEnabled": false, "BatchSchedulerEnabled":false }}`)) - req, _ := http.NewRequest("PUT", fmt.Sprintf("/v1/operator/scheduler/configuration?cas=%d", reply.QueryMeta.Index), buf) + req, _ := http.NewRequest(http.MethodPut, fmt.Sprintf("/v1/operator/scheduler/configuration?cas=%d", reply.QueryMeta.Index), buf) resp := httptest.NewRecorder() setResp, err := s.Server.OperatorSchedulerConfiguration(resp, req) require.Nil(err) @@ -459,7 +459,7 @@ func TestOperator_SnapshotRequests(t *testing.T) { require.NoError(t, err) // now actually snapshot - req, _ := http.NewRequest("GET", "/v1/operator/snapshot", nil) + req, _ := http.NewRequest(http.MethodGet, "/v1/operator/snapshot", nil) resp := httptest.NewRecorder() _, err = s.Server.SnapshotRequest(resp, req) require.NoError(t, err) @@ -495,7 +495,7 @@ func TestOperator_SnapshotRequests(t *testing.T) { }, func(s *TestAgent) { jobExists := func() bool { // check job isn't present - req, _ := http.NewRequest("GET", "/v1/job/"+job.ID, nil) + req, _ := http.NewRequest(http.MethodGet, "/v1/job/"+job.ID, nil) resp := httptest.NewRecorder() j, _ := s.Server.jobCRUD(resp, req, job.ID) return j != nil @@ -509,7 +509,7 @@ func TestOperator_SnapshotRequests(t *testing.T) { require.NoError(t, err) defer f.Close() - req, _ := http.NewRequest("PUT", "/v1/operator/snapshot", f) + req, _ := http.NewRequest(http.MethodPut, "/v1/operator/snapshot", f) resp := httptest.NewRecorder() _, err = s.Server.SnapshotRequest(resp, req) require.NoError(t, err) diff --git a/command/agent/region_endpoint.go b/command/agent/region_endpoint.go index 538adefb4f7..074f10658e6 100644 --- a/command/agent/region_endpoint.go +++ b/command/agent/region_endpoint.go @@ -7,7 +7,7 @@ import ( ) func (s *HTTPServer) RegionListRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } diff --git a/command/agent/region_endpoint_test.go b/command/agent/region_endpoint_test.go index 30f84ed0074..9f923eb207e 100644 --- a/command/agent/region_endpoint_test.go +++ b/command/agent/region_endpoint_test.go @@ -12,7 +12,7 @@ func TestHTTP_RegionList(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/regions", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/regions", nil) if err != nil { t.Fatalf("err: %v", err) } diff --git a/command/agent/scaling_endpoint.go b/command/agent/scaling_endpoint.go index 96a1b853cda..f8488c20e24 100644 --- a/command/agent/scaling_endpoint.go +++ b/command/agent/scaling_endpoint.go @@ -10,7 +10,7 @@ import ( func (s *HTTPServer) ScalingPoliciesRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { switch req.Method { - case "GET": + case http.MethodGet: return s.scalingPoliciesListRequest(resp, req) default: return nil, CodedError(405, ErrInvalidMethod) @@ -49,7 +49,7 @@ func (s *HTTPServer) ScalingPolicySpecificRequest(resp http.ResponseWriter, req func (s *HTTPServer) scalingPolicyCRUD(resp http.ResponseWriter, req *http.Request, policyID string) (interface{}, error) { switch req.Method { - case "GET": + case http.MethodGet: return s.scalingPolicyQuery(resp, req, policyID) default: return nil, CodedError(405, ErrInvalidMethod) diff --git a/command/agent/scaling_endpoint_test.go b/command/agent/scaling_endpoint_test.go index fe7faa2e3fb..39c6b5d9f53 100644 --- a/command/agent/scaling_endpoint_test.go +++ b/command/agent/scaling_endpoint_test.go @@ -31,7 +31,7 @@ func TestHTTP_ScalingPoliciesList(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/scaling/policies", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/scaling/policies", nil) require.NoError(err) respW := httptest.NewRecorder() @@ -72,7 +72,7 @@ func TestHTTP_ScalingPoliciesList_Filter(t *testing.T) { } // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/scaling/policies?job="+job.ID, nil) + req, err := http.NewRequest(http.MethodGet, "/v1/scaling/policies?job="+job.ID, nil) require.NoError(err) respW := httptest.NewRecorder() @@ -85,7 +85,7 @@ func TestHTTP_ScalingPoliciesList_Filter(t *testing.T) { require.Len(l, 1) // Request again, with policy type filter - req, err = http.NewRequest("GET", "/v1/scaling/policies?type=cluster", nil) + req, err = http.NewRequest(http.MethodGet, "/v1/scaling/policies?type=cluster", nil) require.NoError(err) respW = httptest.NewRecorder() @@ -117,7 +117,7 @@ func TestHTTP_ScalingPolicyGet(t *testing.T) { require.NoError(err) // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/scaling/policy/"+p.ID, nil) + req, err := http.NewRequest(http.MethodGet, "/v1/scaling/policy/"+p.ID, nil) require.NoError(err) respW := httptest.NewRecorder() diff --git a/command/agent/search_endpoint_test.go b/command/agent/search_endpoint_test.go index 23c37b97007..6f4c26c31a1 100644 --- a/command/agent/search_endpoint_test.go +++ b/command/agent/search_endpoint_test.go @@ -30,7 +30,7 @@ func TestHTTP_PrefixSearchWithIllegalMethod(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { - req, err := http.NewRequest("DELETE", "/v1/search", nil) + req, err := http.NewRequest(http.MethodDelete, "/v1/search", nil) require.NoError(t, err) respW := httptest.NewRecorder() @@ -43,7 +43,7 @@ func TestHTTP_FuzzySearchWithIllegalMethod(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { - req, err := http.NewRequest("DELETE", "/v1/search/fuzzy", nil) + req, err := http.NewRequest(http.MethodDelete, "/v1/search/fuzzy", nil) require.NoError(t, err) respW := httptest.NewRecorder() @@ -73,7 +73,7 @@ func TestHTTP_PrefixSearch_POST(t *testing.T) { createJobForTest(testJob, s, t) data := structs.SearchRequest{Prefix: testJobPrefix, Context: structs.Jobs} - req, err := http.NewRequest("POST", "/v1/search", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -101,7 +101,7 @@ func TestHTTP_FuzzySearch_POST(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { createJobForTest(testJobID, s, t) data := structs.FuzzySearchRequest{Text: "fau", Context: structs.Namespaces} - req, err := http.NewRequest("POST", "/v1/search/fuzzy", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search/fuzzy", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -133,7 +133,7 @@ func TestHTTP_PrefixSearch_PUT(t *testing.T) { createJobForTest(testJob, s, t) data := structs.SearchRequest{Prefix: testJobPrefix, Context: structs.Jobs} - req, err := http.NewRequest("PUT", "/v1/search", encodeReq(data)) + req, err := http.NewRequest(http.MethodPut, "/v1/search", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -161,7 +161,7 @@ func TestHTTP_FuzzySearch_PUT(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { createJobForTest(testJobID, s, t) data := structs.FuzzySearchRequest{Text: "fau", Context: structs.Namespaces} - req, err := http.NewRequest("PUT", "/v1/search/fuzzy", encodeReq(data)) + req, err := http.NewRequest(http.MethodPut, "/v1/search/fuzzy", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -197,7 +197,7 @@ func TestHTTP_PrefixSearch_MultipleJobs(t *testing.T) { createJobForTest(testJobC, s, t) data := structs.SearchRequest{Prefix: testJobPrefix, Context: structs.Jobs} - req, err := http.NewRequest("POST", "/v1/search", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -229,7 +229,7 @@ func TestHTTP_FuzzySearch_MultipleJobs(t *testing.T) { job4ID := createCmdJobForTest("job4", "/sbin/ping", s, t).ID data := structs.FuzzySearchRequest{Text: "bin", Context: structs.Jobs} - req, err := http.NewRequest("POST", "/v1/search/fuzzy", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search/fuzzy", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -274,7 +274,7 @@ func TestHTTP_PrefixSearch_Evaluation(t *testing.T) { prefix := eval1.ID[:len(eval1.ID)-2] data := structs.SearchRequest{Prefix: prefix, Context: structs.Evals} - req, err := http.NewRequest("POST", "/v1/search", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -307,7 +307,7 @@ func TestHTTP_FuzzySearch_Evaluation(t *testing.T) { // fuzzy search does prefix search for evaluations prefix := eval1.ID[:len(eval1.ID)-2] data := structs.FuzzySearchRequest{Text: prefix, Context: structs.Evals} - req, err := http.NewRequest("POST", "/v1/search/fuzzy", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search/fuzzy", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -346,7 +346,7 @@ func TestHTTP_PrefixSearch_Allocations(t *testing.T) { prefix := alloc.ID[:len(alloc.ID)-2] data := structs.SearchRequest{Prefix: prefix, Context: structs.Allocs} - req, err := http.NewRequest("POST", "/v1/search", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -376,7 +376,7 @@ func TestHTTP_FuzzySearch_Allocations(t *testing.T) { require.NoError(t, err) data := structs.FuzzySearchRequest{Text: "-job", Context: structs.Allocs} - req, err := http.NewRequest("POST", "/v1/search/fuzzy", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search/fuzzy", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -407,7 +407,7 @@ func TestHTTP_PrefixSearch_Nodes(t *testing.T) { prefix := node.ID[:len(node.ID)-2] data := structs.SearchRequest{Prefix: prefix, Context: structs.Nodes} - req, err := http.NewRequest("POST", "/v1/search", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -437,7 +437,7 @@ func TestHTTP_FuzzySearch_Nodes(t *testing.T) { require.NoError(t, err) data := structs.FuzzySearchRequest{Text: "oo", Context: structs.Nodes} - req, err := http.NewRequest("POST", "/v1/search/fuzzy", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search/fuzzy", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -467,7 +467,7 @@ func TestHTTP_PrefixSearch_Deployments(t *testing.T) { prefix := deployment.ID[:len(deployment.ID)-2] data := structs.SearchRequest{Prefix: prefix, Context: structs.Deployments} - req, err := http.NewRequest("POST", "/v1/search", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -496,7 +496,7 @@ func TestHTTP_FuzzySearch_Deployments(t *testing.T) { // fuzzy search of deployments are prefix searches prefix := deployment.ID[:len(deployment.ID)-2] data := structs.FuzzySearchRequest{Text: prefix, Context: structs.Deployments} - req, err := http.NewRequest("POST", "/v1/search/fuzzy", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search/fuzzy", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -519,7 +519,7 @@ func TestHTTP_PrefixSearch_NoJob(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { data := structs.SearchRequest{Prefix: "12345", Context: structs.Jobs} - req, err := http.NewRequest("POST", "/v1/search", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -539,7 +539,7 @@ func TestHTTP_FuzzySearch_NoJob(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { data := structs.FuzzySearchRequest{Text: "12345", Context: structs.Jobs} - req, err := http.NewRequest("POST", "/v1/search/fuzzy", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search/fuzzy", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -569,7 +569,7 @@ func TestHTTP_PrefixSearch_AllContext(t *testing.T) { require.NoError(t, err) data := structs.SearchRequest{Prefix: testJobPrefix, Context: structs.All} - req, err := http.NewRequest("POST", "/v1/search", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -601,7 +601,7 @@ func TestHTTP_FuzzySearch_AllContext(t *testing.T) { require.NoError(t, err) data := structs.FuzzySearchRequest{Text: "aa", Context: structs.All} - req, err := http.NewRequest("POST", "/v1/search/fuzzy", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search/fuzzy", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -641,7 +641,7 @@ func TestHTTP_PrefixSearch_Variables(t *testing.T) { require.NoError(t, setResp.Error) data := structs.SearchRequest{Prefix: testPathPrefix, Context: structs.Variables} - req, err := http.NewRequest("POST", "/v1/search", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -674,7 +674,7 @@ func TestHTTP_FuzzySearch_Variables(t *testing.T) { require.NoError(t, setResp.Error) data := structs.FuzzySearchRequest{Text: testPathText, Context: structs.Variables} - req, err := http.NewRequest("POST", "/v1/search/", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search/", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -783,7 +783,7 @@ func TestHTTP_PrefixSearch_Variables_ACL(t *testing.T) { }, } - req, err := http.NewRequest("POST", "/v1/search", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search", encodeReq(data)) require.NoError(t, err) respW := httptest.NewRecorder() @@ -907,7 +907,7 @@ func TestHTTP_FuzzySearch_Variables_ACL(t *testing.T) { Namespace: tcNS(tC), }, } - req, err := http.NewRequest("POST", "/v1/search/fuzzy", encodeReq(data)) + req, err := http.NewRequest(http.MethodPost, "/v1/search/fuzzy", encodeReq(data)) require.NoError(t, err) setToken(req, tC.token) diff --git a/command/agent/stats_endpoint_test.go b/command/agent/stats_endpoint_test.go index 6778ef58da4..3b705a8e89b 100644 --- a/command/agent/stats_endpoint_test.go +++ b/command/agent/stats_endpoint_test.go @@ -23,7 +23,7 @@ func TestClientStatsRequest(t *testing.T) { // Local node, local resp { - req, err := http.NewRequest("GET", "/v1/client/stats/?since=foo", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/client/stats/?since=foo", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -40,7 +40,7 @@ func TestClientStatsRequest(t *testing.T) { srv := s.server s.server = nil - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/stats?node_id=%s", uuid.Generate()), nil) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/stats?node_id=%s", uuid.Generate()), nil) require.Nil(err) respW := httptest.NewRecorder() @@ -66,7 +66,7 @@ func TestClientStatsRequest(t *testing.T) { t.Fatalf("should have client: %v", err) }) - req, err := http.NewRequest("GET", fmt.Sprintf("/v1/client/stats?node_id=%s", c.NodeID()), nil) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/v1/client/stats?node_id=%s", c.NodeID()), nil) require.Nil(err) respW := httptest.NewRecorder() @@ -82,7 +82,7 @@ func TestClientStatsRequest_ACL(t *testing.T) { assert := assert.New(t) httpACLTest(t, nil, func(s *TestAgent) { state := s.Agent.server.State() - req, err := http.NewRequest("GET", "/v1/client/stats/", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/client/stats/", nil) assert.Nil(err) // Try request without a token and expect failure diff --git a/command/agent/status_endpoint.go b/command/agent/status_endpoint.go index 7e25cf84e24..125cc851798 100644 --- a/command/agent/status_endpoint.go +++ b/command/agent/status_endpoint.go @@ -7,7 +7,7 @@ import ( ) func (s *HTTPServer) StatusLeaderRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } @@ -24,7 +24,7 @@ func (s *HTTPServer) StatusLeaderRequest(resp http.ResponseWriter, req *http.Req } func (s *HTTPServer) StatusPeersRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, CodedError(405, ErrInvalidMethod) } diff --git a/command/agent/status_endpoint_test.go b/command/agent/status_endpoint_test.go index 9be35c4f27d..fa56c78ea40 100644 --- a/command/agent/status_endpoint_test.go +++ b/command/agent/status_endpoint_test.go @@ -12,7 +12,7 @@ func TestHTTP_StatusLeader(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/status/leader", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/status/leader", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -35,7 +35,7 @@ func TestHTTP_StatusPeers(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { // Make the HTTP request - req, err := http.NewRequest("GET", "/v1/status/peers", nil) + req, err := http.NewRequest(http.MethodGet, "/v1/status/peers", nil) if err != nil { t.Fatalf("err: %v", err) } diff --git a/command/agent/system_endpoint.go b/command/agent/system_endpoint.go index ef7a8122283..eebe3ded042 100644 --- a/command/agent/system_endpoint.go +++ b/command/agent/system_endpoint.go @@ -7,7 +7,7 @@ import ( ) func (s *HTTPServer) GarbageCollectRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "PUT" { + if req.Method != http.MethodPut { return nil, CodedError(405, ErrInvalidMethod) } @@ -24,7 +24,7 @@ func (s *HTTPServer) GarbageCollectRequest(resp http.ResponseWriter, req *http.R } func (s *HTTPServer) ReconcileJobSummaries(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - if req.Method != "PUT" { + if req.Method != http.MethodPut { return nil, CodedError(405, ErrInvalidMethod) } diff --git a/command/agent/system_endpoint_test.go b/command/agent/system_endpoint_test.go index 504b44f5451..8edf01678e8 100644 --- a/command/agent/system_endpoint_test.go +++ b/command/agent/system_endpoint_test.go @@ -12,7 +12,7 @@ func TestHTTP_SystemGarbageCollect(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/system/gc", nil) + req, err := http.NewRequest(http.MethodPut, "/v1/system/gc", nil) if err != nil { t.Fatalf("err: %v", err) } @@ -29,7 +29,7 @@ func TestHTTP_ReconcileJobSummaries(t *testing.T) { ci.Parallel(t) httpTest(t, nil, func(s *TestAgent) { // Make the HTTP request - req, err := http.NewRequest("PUT", "/v1/system/reconcile/summaries", nil) + req, err := http.NewRequest(http.MethodPut, "/v1/system/reconcile/summaries", nil) if err != nil { t.Fatalf("err: %v", err) } diff --git a/command/agent/testagent.go b/command/agent/testagent.go index c0d6836be54..f877e527a7e 100644 --- a/command/agent/testagent.go +++ b/command/agent/testagent.go @@ -200,7 +200,7 @@ RETRY: }) } else { testutil.WaitForResult(func() (bool, error) { - req, _ := http.NewRequest("GET", "/v1/agent/self", nil) + req, _ := http.NewRequest(http.MethodGet, "/v1/agent/self", nil) resp := httptest.NewRecorder() _, err := a.Server.AgentSelfRequest(resp, req) return err == nil && resp.Code == 200, err diff --git a/command/operator_debug.go b/command/operator_debug.go index eeb4321d834..4f8089744aa 100644 --- a/command/operator_debug.go +++ b/command/operator_debug.go @@ -1216,7 +1216,7 @@ func (c *OperatorDebugCommand) collectConsulAPI(client *http.Client, urlPath str func (c *OperatorDebugCommand) collectConsulAPIRequest(client *http.Client, urlPath string, dir string, file string) error { url := c.consul.addrVal + urlPath - req, err := http.NewRequest("GET", url, nil) + req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return fmt.Errorf("failed to create HTTP request for Consul API URL=%q: %w", url, err) } @@ -1250,7 +1250,7 @@ func (c *OperatorDebugCommand) collectVault(dir, vault string) error { } } - req, err := http.NewRequest("GET", vaultAddr+"/v1/sys/health", nil) + req, err := http.NewRequest(http.MethodGet, vaultAddr+"/v1/sys/health", nil) if err != nil { return fmt.Errorf("failed to create HTTP request for Vault API URL=%q: %w", vaultAddr, err) } diff --git a/command/operator_debug_test.go b/command/operator_debug_test.go index 7a3d2cc862c..158146d0e43 100644 --- a/command/operator_debug_test.go +++ b/command/operator_debug_test.go @@ -830,7 +830,7 @@ func TestDebug_RedirectError(t *testing.T) { } w.Header().Set("Location", "/ui/") - w.WriteHeader(307) + w.WriteHeader(http.StatusTemporaryRedirect) fmt.Fprintln(w, `Temporary Redirect.`) })) defer ts.Close() diff --git a/testutil/server.go b/testutil/server.go index ca0abdb929a..fa296279313 100644 --- a/testutil/server.go +++ b/testutil/server.go @@ -357,7 +357,7 @@ func (s *TestServer) url(path string) string { // requireOK checks the HTTP response code and ensures it is acceptable. func (s *TestServer) requireOK(resp *http.Response) error { - if resp.StatusCode != 200 { + if resp.StatusCode != http.StatusOK { return fmt.Errorf("Bad status code: %d", resp.StatusCode) } return nil @@ -365,7 +365,7 @@ func (s *TestServer) requireOK(resp *http.Response) error { // put performs a new HTTP PUT request. func (s *TestServer) put(path string, body io.Reader) *http.Response { - req, err := http.NewRequest("PUT", s.url(path), body) + req, err := http.NewRequest(http.MethodPut, s.url(path), body) if err != nil { s.t.Fatalf("err: %s", err) }