From 9ed58987ceb2427b66f3b9128088620dfde64471 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sat, 12 Oct 2019 20:42:02 +0200 Subject: [PATCH 01/13] integration: use constants for http methods Signed-off-by: Sebastiaan van Stijn --- integration/plugin/authz/authz_plugin_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/integration/plugin/authz/authz_plugin_test.go b/integration/plugin/authz/authz_plugin_test.go index 211bf9f6cc..af8acaa428 100644 --- a/integration/plugin/authz/authz_plugin_test.go +++ b/integration/plugin/authz/authz_plugin_test.go @@ -178,7 +178,7 @@ func TestAuthZPluginAPIDenyResponse(t *testing.T) { conn, err := net.DialTimeout(daemonURL.Scheme, daemonURL.Path, time.Second*10) assert.NilError(t, err) c := httputil.NewClientConn(conn, nil) - req, err := http.NewRequest("GET", "/version", nil) + req, err := http.NewRequest(http.MethodGet, "/version", nil) assert.NilError(t, err) resp, err := c.Do(req) @@ -477,7 +477,7 @@ func TestAuthZPluginHeader(t *testing.T) { conn, err := net.DialTimeout(daemonURL.Scheme, daemonURL.Path, time.Second*10) assert.NilError(t, err) client := httputil.NewClientConn(conn, nil) - req, err := http.NewRequest("GET", "/version", nil) + req, err := http.NewRequest(http.MethodGet, "/version", nil) assert.NilError(t, err) resp, err := client.Do(req) assert.NilError(t, err) From 23b6b5a9ae0e16bdcf37d0ec9a5a8bee9cb38f97 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sat, 12 Oct 2019 20:42:19 +0200 Subject: [PATCH 02/13] integration-cli: use constants for http methods Signed-off-by: Sebastiaan van Stijn --- integration-cli/docker_api_attach_test.go | 12 ++++++------ integration-cli/docker_api_exec_resize_test.go | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/integration-cli/docker_api_attach_test.go b/integration-cli/docker_api_attach_test.go index e7c751c2e6..5f0acfd6a9 100644 --- a/integration-cli/docker_api_attach_test.go +++ b/integration-cli/docker_api_attach_test.go @@ -142,12 +142,12 @@ func (s *DockerSuite) TestPostContainersAttach(c *testing.T) { cid, _ := dockerCmd(c, "run", "-di", "busybox", "cat") cid = strings.TrimSpace(cid) // Attach to the container's stdout stream. - conn, br, err := sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) + conn, br, err := sockRequestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) assert.NilError(c, err) // Check if the data from stdout can be received. expectSuccess(conn, br, "stdout", false) // Attach to the container's stderr stream. - conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) + conn, br, err = sockRequestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) assert.NilError(c, err) // Since the container only emits stdout, attaching to stderr should return nothing. expectTimeout(conn, br, "stdout") @@ -155,10 +155,10 @@ func (s *DockerSuite) TestPostContainersAttach(c *testing.T) { // Test the similar functions of the stderr stream. cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "cat >&2") cid = strings.TrimSpace(cid) - conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) + conn, br, err = sockRequestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) assert.NilError(c, err) expectSuccess(conn, br, "stderr", false) - conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) + conn, br, err = sockRequestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) assert.NilError(c, err) expectTimeout(conn, br, "stderr") @@ -166,12 +166,12 @@ func (s *DockerSuite) TestPostContainersAttach(c *testing.T) { cid, _ = dockerCmd(c, "run", "-dit", "busybox", "/bin/sh", "-c", "cat >&2") cid = strings.TrimSpace(cid) // Attach to stdout only. - conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) + conn, br, err = sockRequestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) assert.NilError(c, err) expectSuccess(conn, br, "stdout", true) // Attach without stdout stream. - conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) + conn, br, err = sockRequestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) assert.NilError(c, err) // Nothing should be received because both the stdout and stderr of the container will be // sent to the client as stdout when tty is enabled. diff --git a/integration-cli/docker_api_exec_resize_test.go b/integration-cli/docker_api_exec_resize_test.go index 8a64dfe307..89de25a261 100644 --- a/integration-cli/docker_api_exec_resize_test.go +++ b/integration-cli/docker_api_exec_resize_test.go @@ -65,7 +65,7 @@ func (s *DockerSuite) TestExecResizeImmediatelyAfterExecStart(c *testing.T) { } payload := bytes.NewBufferString(`{"Tty":true}`) - conn, _, err := sockRequestHijack("POST", fmt.Sprintf("/exec/%s/start", execID), payload, "application/json", request.DaemonHost()) + conn, _, err := sockRequestHijack(http.MethodPost, fmt.Sprintf("/exec/%s/start", execID), payload, "application/json", request.DaemonHost()) if err != nil { return errors.Wrap(err, "failed to start the exec") } From a617809fe7cd59b8825cfad80af772d7b3595024 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sat, 12 Oct 2019 20:43:17 +0200 Subject: [PATCH 03/13] testutil: use constants for http methods Signed-off-by: Sebastiaan van Stijn --- testutil/daemon/daemon.go | 4 ++-- testutil/request/request.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/testutil/daemon/daemon.go b/testutil/daemon/daemon.go index d6a7a07276..cd172cae15 100644 --- a/testutil/daemon/daemon.go +++ b/testutil/daemon/daemon.go @@ -328,7 +328,7 @@ func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error { Transport: clientConfig.transport, } - req, err := http.NewRequest("GET", "/_ping", nil) + req, err := http.NewRequest(http.MethodGet, "/_ping", nil) if err != nil { return errors.Wrapf(err, "[%s] could not create new request", d.id) } @@ -683,7 +683,7 @@ func (d *Daemon) queryRootDir() (string, error) { Transport: clientConfig.transport, } - req, err := http.NewRequest("GET", "/info", nil) + req, err := http.NewRequest(http.MethodGet, "/info", nil) if err != nil { return "", err } diff --git a/testutil/request/request.go b/testutil/request/request.go index f41219a06f..bc9fc1ee19 100644 --- a/testutil/request/request.go +++ b/testutil/request/request.go @@ -115,7 +115,7 @@ func newRequest(endpoint string, opts *Options) (*http.Request, error) { if err != nil { return nil, errors.Wrapf(err, "failed parsing url %q", opts.host) } - req, err := http.NewRequest("GET", endpoint, nil) + req, err := http.NewRequest(http.MethodGet, endpoint, nil) if err != nil { return nil, errors.Wrap(err, "failed to create request") } From 93100adb69de2338982b5c2419c4dcef61ea2ca0 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sat, 12 Oct 2019 20:40:19 +0200 Subject: [PATCH 04/13] api/server: use constants for http methods Signed-off-by: Sebastiaan van Stijn --- api/server/httputils/form_test.go | 12 ++++++------ api/server/middleware/debug.go | 2 +- api/server/middleware/version_test.go | 4 ++-- api/server/server_test.go | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/api/server/httputils/form_test.go b/api/server/httputils/form_test.go index e7e2daea20..2721b23e39 100644 --- a/api/server/httputils/form_test.go +++ b/api/server/httputils/form_test.go @@ -23,7 +23,7 @@ func TestBoolValue(t *testing.T) { for c, e := range cases { v := url.Values{} v.Set("test", c) - r, _ := http.NewRequest("POST", "", nil) + r, _ := http.NewRequest(http.MethodPost, "", nil) r.Form = v a := BoolValue(r, "test") @@ -34,14 +34,14 @@ func TestBoolValue(t *testing.T) { } func TestBoolValueOrDefault(t *testing.T) { - r, _ := http.NewRequest("GET", "", nil) + r, _ := http.NewRequest(http.MethodGet, "", nil) if !BoolValueOrDefault(r, "queryparam", true) { t.Fatal("Expected to get true default value, got false") } v := url.Values{} v.Set("param", "") - r, _ = http.NewRequest("GET", "", nil) + r, _ = http.NewRequest(http.MethodGet, "", nil) r.Form = v if BoolValueOrDefault(r, "param", true) { t.Fatal("Expected not to get true") @@ -59,7 +59,7 @@ func TestInt64ValueOrZero(t *testing.T) { for c, e := range cases { v := url.Values{} v.Set("test", c) - r, _ := http.NewRequest("POST", "", nil) + r, _ := http.NewRequest(http.MethodPost, "", nil) r.Form = v a := Int64ValueOrZero(r, "test") @@ -79,7 +79,7 @@ func TestInt64ValueOrDefault(t *testing.T) { for c, e := range cases { v := url.Values{} v.Set("test", c) - r, _ := http.NewRequest("POST", "", nil) + r, _ := http.NewRequest(http.MethodPost, "", nil) r.Form = v a, err := Int64ValueOrDefault(r, "test", -1) @@ -95,7 +95,7 @@ func TestInt64ValueOrDefault(t *testing.T) { func TestInt64ValueOrDefaultWithError(t *testing.T) { v := url.Values{} v.Set("test", "invalid") - r, _ := http.NewRequest("POST", "", nil) + r, _ := http.NewRequest(http.MethodPost, "", nil) r.Form = v _, err := Int64ValueOrDefault(r, "test", -1) diff --git a/api/server/middleware/debug.go b/api/server/middleware/debug.go index a02c1bc7de..1ec62602db 100644 --- a/api/server/middleware/debug.go +++ b/api/server/middleware/debug.go @@ -18,7 +18,7 @@ func DebugRequestMiddleware(handler func(ctx context.Context, w http.ResponseWri return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { logrus.Debugf("Calling %s %s", r.Method, r.RequestURI) - if r.Method != "POST" { + if r.Method != http.MethodPost { return handler(ctx, w, r, vars) } if err := httputils.CheckForJSON(r); err != nil { diff --git a/api/server/middleware/version_test.go b/api/server/middleware/version_test.go index edbc0bcaa5..e00441d8c4 100644 --- a/api/server/middleware/version_test.go +++ b/api/server/middleware/version_test.go @@ -25,7 +25,7 @@ func TestVersionMiddlewareVersion(t *testing.T) { m := NewVersionMiddleware(defaultVersion, defaultVersion, minVersion) h := m.WrapHandler(handler) - req, _ := http.NewRequest("GET", "/containers/json", nil) + req, _ := http.NewRequest(http.MethodGet, "/containers/json", nil) resp := httptest.NewRecorder() ctx := context.Background() @@ -76,7 +76,7 @@ func TestVersionMiddlewareWithErrorsReturnsHeaders(t *testing.T) { m := NewVersionMiddleware(defaultVersion, defaultVersion, minVersion) h := m.WrapHandler(handler) - req, _ := http.NewRequest("GET", "/containers/json", nil) + req, _ := http.NewRequest(http.MethodGet, "/containers/json", nil) resp := httptest.NewRecorder() ctx := context.Background() diff --git a/api/server/server_test.go b/api/server/server_test.go index e0fac30ab7..a3e8124a88 100644 --- a/api/server/server_test.go +++ b/api/server/server_test.go @@ -22,7 +22,7 @@ func TestMiddlewares(t *testing.T) { srv.UseMiddleware(middleware.NewVersionMiddleware("0.1omega2", api.DefaultVersion, api.MinVersion)) - req, _ := http.NewRequest("GET", "/containers/json", nil) + req, _ := http.NewRequest(http.MethodGet, "/containers/json", nil) resp := httptest.NewRecorder() ctx := context.Background() From dabc7cdb56a1d5ae392e945a12f8357738950f2d Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sat, 12 Oct 2019 20:41:14 +0200 Subject: [PATCH 05/13] client: use constants for http methods Signed-off-by: Sebastiaan van Stijn --- client/checkpoint_create_test.go | 2 +- client/checkpoint_delete_test.go | 2 +- client/config_create_test.go | 2 +- client/config_remove_test.go | 2 +- client/config_update_test.go | 2 +- client/container_copy_test.go | 6 +++--- client/container_exec_test.go | 2 +- client/hijack.go | 4 ++-- client/image_remove_test.go | 2 +- client/image_tag_test.go | 2 +- client/network_connect_test.go | 4 ++-- client/network_create_test.go | 2 +- client/network_disconnect_test.go | 2 +- client/network_inspect_test.go | 2 +- client/network_list_test.go | 2 +- client/network_remove_test.go | 2 +- client/node_remove_test.go | 2 +- client/node_update_test.go | 2 +- client/ping.go | 4 ++-- client/ping_test.go | 4 ++-- client/plugin_disable_test.go | 2 +- client/plugin_enable_test.go | 2 +- client/plugin_push_test.go | 2 +- client/plugin_remove_test.go | 2 +- client/plugin_set_test.go | 2 +- client/request.go | 14 +++++++------- client/request_test.go | 2 +- client/secret_create_test.go | 2 +- client/secret_remove_test.go | 2 +- client/secret_update_test.go | 2 +- client/service_create_test.go | 2 +- client/service_remove_test.go | 2 +- client/service_update_test.go | 2 +- client/swarm_get_unlock_key_test.go | 2 +- client/swarm_init_test.go | 2 +- client/swarm_join_test.go | 2 +- client/swarm_leave_test.go | 2 +- client/swarm_unlock_test.go | 2 +- client/swarm_update_test.go | 2 +- client/volume_create_test.go | 2 +- client/volume_inspect_test.go | 2 +- client/volume_remove_test.go | 2 +- 42 files changed, 54 insertions(+), 54 deletions(-) diff --git a/client/checkpoint_create_test.go b/client/checkpoint_create_test.go index 6b37034550..83ed92cb10 100644 --- a/client/checkpoint_create_test.go +++ b/client/checkpoint_create_test.go @@ -42,7 +42,7 @@ func TestCheckpointCreate(t *testing.T) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } diff --git a/client/checkpoint_delete_test.go b/client/checkpoint_delete_test.go index 3ebdd2ce02..71daa31123 100644 --- a/client/checkpoint_delete_test.go +++ b/client/checkpoint_delete_test.go @@ -38,7 +38,7 @@ func TestCheckpointDelete(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "DELETE" { + if req.Method != http.MethodDelete { return nil, fmt.Errorf("expected DELETE method, got %s", req.Method) } return &http.Response{ diff --git a/client/config_create_test.go b/client/config_create_test.go index 98898e0c7f..f891cee8d2 100644 --- a/client/config_create_test.go +++ b/client/config_create_test.go @@ -48,7 +48,7 @@ func TestConfigCreate(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } b, err := json.Marshal(types.ConfigCreateResponse{ diff --git a/client/config_remove_test.go b/client/config_remove_test.go index 3912d1bede..48930ddc25 100644 --- a/client/config_remove_test.go +++ b/client/config_remove_test.go @@ -47,7 +47,7 @@ func TestConfigRemove(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "DELETE" { + if req.Method != http.MethodDelete { return nil, fmt.Errorf("expected DELETE method, got %s", req.Method) } return &http.Response{ diff --git a/client/config_update_test.go b/client/config_update_test.go index 2ad5eb8f68..d43e717e5a 100644 --- a/client/config_update_test.go +++ b/client/config_update_test.go @@ -48,7 +48,7 @@ func TestConfigUpdate(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } return &http.Response{ diff --git a/client/container_copy_test.go b/client/container_copy_test.go index b0a4ad825c..6154914387 100644 --- a/client/container_copy_test.go +++ b/client/container_copy_test.go @@ -61,7 +61,7 @@ func TestContainerStatPath(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "HEAD" { + if req.Method != http.MethodHead { return nil, fmt.Errorf("expected HEAD method, got %s", req.Method) } query := req.URL.Query() @@ -140,7 +140,7 @@ func TestCopyToContainer(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "PUT" { + if req.Method != http.MethodPut { return nil, fmt.Errorf("expected PUT method, got %s", req.Method) } query := req.URL.Query() @@ -235,7 +235,7 @@ func TestCopyFromContainer(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, fmt.Errorf("expected GET method, got %s", req.Method) } query := req.URL.Query() diff --git a/client/container_exec_test.go b/client/container_exec_test.go index c1cee4ed0f..80f514371c 100644 --- a/client/container_exec_test.go +++ b/client/container_exec_test.go @@ -34,7 +34,7 @@ func TestContainerExecCreate(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } // FIXME validate the content is the given ExecConfig ? diff --git a/client/hijack.go b/client/hijack.go index e77084af64..6f8205501f 100644 --- a/client/hijack.go +++ b/client/hijack.go @@ -24,7 +24,7 @@ func (cli *Client) postHijacked(ctx context.Context, path string, query url.Valu } apiPath := cli.getAPIPath(ctx, path, query) - req, err := http.NewRequest("POST", apiPath, bodyEncoded) + req, err := http.NewRequest(http.MethodPost, apiPath, bodyEncoded) if err != nil { return types.HijackedResponse{}, err } @@ -40,7 +40,7 @@ func (cli *Client) postHijacked(ctx context.Context, path string, query url.Valu // DialHijack returns a hijacked connection with negotiated protocol proto. func (cli *Client) DialHijack(ctx context.Context, url, proto string, meta map[string][]string) (net.Conn, error) { - req, err := http.NewRequest("POST", url, nil) + req, err := http.NewRequest(http.MethodPost, url, nil) if err != nil { return nil, err } diff --git a/client/image_remove_test.go b/client/image_remove_test.go index acc6bc9177..b3b02ebddb 100644 --- a/client/image_remove_test.go +++ b/client/image_remove_test.go @@ -63,7 +63,7 @@ func TestImageRemove(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "DELETE" { + if req.Method != http.MethodDelete { return nil, fmt.Errorf("expected DELETE method, got %s", req.Method) } query := req.URL.Query() diff --git a/client/image_tag_test.go b/client/image_tag_test.go index 0298495101..0ed6355335 100644 --- a/client/image_tag_test.go +++ b/client/image_tag_test.go @@ -123,7 +123,7 @@ func TestImageTag(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } query := req.URL.Query() diff --git a/client/network_connect_test.go b/client/network_connect_test.go index ef509b7929..032d8291be 100644 --- a/client/network_connect_test.go +++ b/client/network_connect_test.go @@ -38,7 +38,7 @@ func TestNetworkConnectEmptyNilEndpointSettings(t *testing.T) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } @@ -77,7 +77,7 @@ func TestNetworkConnect(t *testing.T) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } diff --git a/client/network_create_test.go b/client/network_create_test.go index 313f53f907..0fccd085ae 100644 --- a/client/network_create_test.go +++ b/client/network_create_test.go @@ -37,7 +37,7 @@ func TestNetworkCreate(t *testing.T) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } diff --git a/client/network_disconnect_test.go b/client/network_disconnect_test.go index 7ec85f9387..3814e4dbbe 100644 --- a/client/network_disconnect_test.go +++ b/client/network_disconnect_test.go @@ -37,7 +37,7 @@ func TestNetworkDisconnect(t *testing.T) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } diff --git a/client/network_inspect_test.go b/client/network_inspect_test.go index 699bccba67..e804d8dc22 100644 --- a/client/network_inspect_test.go +++ b/client/network_inspect_test.go @@ -55,7 +55,7 @@ func TestNetworkInspect(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, fmt.Errorf("expected GET method, got %s", req.Method) } diff --git a/client/network_list_test.go b/client/network_list_test.go index 90ae33405d..3e3d094fe8 100644 --- a/client/network_list_test.go +++ b/client/network_list_test.go @@ -77,7 +77,7 @@ func TestNetworkList(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, fmt.Errorf("expected GET method, got %s", req.Method) } query := req.URL.Query() diff --git a/client/network_remove_test.go b/client/network_remove_test.go index f70c8ac16e..df2c3b4479 100644 --- a/client/network_remove_test.go +++ b/client/network_remove_test.go @@ -34,7 +34,7 @@ func TestNetworkRemove(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "DELETE" { + if req.Method != http.MethodDelete { return nil, fmt.Errorf("expected DELETE method, got %s", req.Method) } return &http.Response{ diff --git a/client/node_remove_test.go b/client/node_remove_test.go index 5870ba1da3..5570773607 100644 --- a/client/node_remove_test.go +++ b/client/node_remove_test.go @@ -49,7 +49,7 @@ func TestNodeRemove(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "DELETE" { + if req.Method != http.MethodDelete { return nil, fmt.Errorf("expected DELETE method, got %s", req.Method) } force := req.URL.Query().Get("force") diff --git a/client/node_update_test.go b/client/node_update_test.go index 072297d682..d51df959a5 100644 --- a/client/node_update_test.go +++ b/client/node_update_test.go @@ -35,7 +35,7 @@ func TestNodeUpdate(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } return &http.Response{ diff --git a/client/ping.go b/client/ping.go index 90f39ec14f..1cfc48a25d 100644 --- a/client/ping.go +++ b/client/ping.go @@ -19,7 +19,7 @@ func (cli *Client) Ping(ctx context.Context) (types.Ping, error) { // Using cli.buildRequest() + cli.doRequest() instead of cli.sendRequest() // because ping requests are used during API version negotiation, so we want // to hit the non-versioned /_ping endpoint, not /v1.xx/_ping - req, err := cli.buildRequest("HEAD", path.Join(cli.basePath, "/_ping"), nil, nil) + req, err := cli.buildRequest(http.MethodHead, path.Join(cli.basePath, "/_ping"), nil, nil) if err != nil { return ping, err } @@ -35,7 +35,7 @@ func (cli *Client) Ping(ctx context.Context) (types.Ping, error) { return ping, err } - req, err = cli.buildRequest("GET", path.Join(cli.basePath, "/_ping"), nil, nil) + req, err = cli.buildRequest(http.MethodGet, path.Join(cli.basePath, "/_ping"), nil, nil) if err != nil { return ping, err } diff --git a/client/ping_test.go b/client/ping_test.go index 5b6a33cb1f..e14933a401 100644 --- a/client/ping_test.go +++ b/client/ping_test.go @@ -90,11 +90,11 @@ func TestPingHeadFallback(t *testing.T) { }{ { status: http.StatusOK, - expected: "HEAD", + expected: http.MethodHead, }, { status: http.StatusInternalServerError, - expected: "HEAD", + expected: http.MethodHead, }, { status: http.StatusNotFound, diff --git a/client/plugin_disable_test.go b/client/plugin_disable_test.go index 2e9c0396cc..1b1fe1ba33 100644 --- a/client/plugin_disable_test.go +++ b/client/plugin_disable_test.go @@ -35,7 +35,7 @@ func TestPluginDisable(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } return &http.Response{ diff --git a/client/plugin_enable_test.go b/client/plugin_enable_test.go index 1c3c988d3f..cd1945d751 100644 --- a/client/plugin_enable_test.go +++ b/client/plugin_enable_test.go @@ -35,7 +35,7 @@ func TestPluginEnable(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } return &http.Response{ diff --git a/client/plugin_push_test.go b/client/plugin_push_test.go index 779d8f8e90..b9292e4785 100644 --- a/client/plugin_push_test.go +++ b/client/plugin_push_test.go @@ -34,7 +34,7 @@ func TestPluginPush(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } auth := req.Header.Get("X-Registry-Auth") diff --git a/client/plugin_remove_test.go b/client/plugin_remove_test.go index 46d1b96fa9..249c5cd7b3 100644 --- a/client/plugin_remove_test.go +++ b/client/plugin_remove_test.go @@ -35,7 +35,7 @@ func TestPluginRemove(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "DELETE" { + if req.Method != http.MethodDelete { return nil, fmt.Errorf("expected DELETE method, got %s", req.Method) } return &http.Response{ diff --git a/client/plugin_set_test.go b/client/plugin_set_test.go index eee467c26b..ad8cdb7db5 100644 --- a/client/plugin_set_test.go +++ b/client/plugin_set_test.go @@ -34,7 +34,7 @@ func TestPluginSet(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } return &http.Response{ diff --git a/client/request.go b/client/request.go index 144c416369..ee15a46ed0 100644 --- a/client/request.go +++ b/client/request.go @@ -29,12 +29,12 @@ type serverResponse struct { // head sends an http request to the docker API using the method HEAD. func (cli *Client) head(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, "HEAD", path, query, nil, headers) + return cli.sendRequest(ctx, http.MethodHead, path, query, nil, headers) } // get sends an http request to the docker API using the method GET with a specific Go context. func (cli *Client) get(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, "GET", path, query, nil, headers) + return cli.sendRequest(ctx, http.MethodGet, path, query, nil, headers) } // post sends an http request to the docker API using the method POST with a specific Go context. @@ -43,21 +43,21 @@ func (cli *Client) post(ctx context.Context, path string, query url.Values, obj if err != nil { return serverResponse{}, err } - return cli.sendRequest(ctx, "POST", path, query, body, headers) + return cli.sendRequest(ctx, http.MethodPost, path, query, body, headers) } func (cli *Client) postRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, "POST", path, query, body, headers) + return cli.sendRequest(ctx, http.MethodPost, path, query, body, headers) } // putRaw sends an http request to the docker API using the method PUT. func (cli *Client) putRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, "PUT", path, query, body, headers) + return cli.sendRequest(ctx, http.MethodPut, path, query, body, headers) } // delete sends an http request to the docker API using the method DELETE. func (cli *Client) delete(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, "DELETE", path, query, nil, headers) + return cli.sendRequest(ctx, http.MethodDelete, path, query, nil, headers) } type headers map[string][]string @@ -79,7 +79,7 @@ func encodeBody(obj interface{}, headers headers) (io.Reader, headers, error) { } func (cli *Client) buildRequest(method, path string, body io.Reader, headers headers) (*http.Request, error) { - expectedPayload := (method == "POST" || method == "PUT") + expectedPayload := (method == http.MethodPost || method == http.MethodPut) if expectedPayload && body == nil { body = bytes.NewReader([]byte{}) } diff --git a/client/request_test.go b/client/request_test.go index de563d2c50..8656ddef68 100644 --- a/client/request_test.go +++ b/client/request_test.go @@ -73,7 +73,7 @@ func TestSetHostHeader(t *testing.T) { basePath: hostURL.Path, } - _, err = client.sendRequest(context.Background(), "GET", testURL, nil, nil, nil) + _, err = client.sendRequest(context.Background(), http.MethodGet, testURL, nil, nil, nil) assert.NilError(t, err) } } diff --git a/client/secret_create_test.go b/client/secret_create_test.go index 23c2449b55..09b4653036 100644 --- a/client/secret_create_test.go +++ b/client/secret_create_test.go @@ -48,7 +48,7 @@ func TestSecretCreate(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } b, err := json.Marshal(types.SecretCreateResponse{ diff --git a/client/secret_remove_test.go b/client/secret_remove_test.go index c69db4096d..3c0d7d27e7 100644 --- a/client/secret_remove_test.go +++ b/client/secret_remove_test.go @@ -47,7 +47,7 @@ func TestSecretRemove(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "DELETE" { + if req.Method != http.MethodDelete { return nil, fmt.Errorf("expected DELETE method, got %s", req.Method) } return &http.Response{ diff --git a/client/secret_update_test.go b/client/secret_update_test.go index c52ae2b8b8..6d6a759ce3 100644 --- a/client/secret_update_test.go +++ b/client/secret_update_test.go @@ -48,7 +48,7 @@ func TestSecretUpdate(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } return &http.Response{ diff --git a/client/service_create_test.go b/client/service_create_test.go index ef792a38e2..4b80d92722 100644 --- a/client/service_create_test.go +++ b/client/service_create_test.go @@ -40,7 +40,7 @@ func TestServiceCreate(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } b, err := json.Marshal(types.ServiceCreateResponse{ diff --git a/client/service_remove_test.go b/client/service_remove_test.go index d2379a1366..f358a7b10c 100644 --- a/client/service_remove_test.go +++ b/client/service_remove_test.go @@ -40,7 +40,7 @@ func TestServiceRemove(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "DELETE" { + if req.Method != http.MethodDelete { return nil, fmt.Errorf("expected DELETE method, got %s", req.Method) } return &http.Response{ diff --git a/client/service_update_test.go b/client/service_update_test.go index 9b5d1616f0..bc6c6f7766 100644 --- a/client/service_update_test.go +++ b/client/service_update_test.go @@ -58,7 +58,7 @@ func TestServiceUpdate(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } version := req.URL.Query().Get("version") diff --git a/client/swarm_get_unlock_key_test.go b/client/swarm_get_unlock_key_test.go index a1e460c1dc..730df7b744 100644 --- a/client/swarm_get_unlock_key_test.go +++ b/client/swarm_get_unlock_key_test.go @@ -33,7 +33,7 @@ func TestSwarmGetUnlockKey(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, fmt.Errorf("expected GET method, got %s", req.Method) } diff --git a/client/swarm_init_test.go b/client/swarm_init_test.go index 78b8245461..a1acc69ff2 100644 --- a/client/swarm_init_test.go +++ b/client/swarm_init_test.go @@ -35,7 +35,7 @@ func TestSwarmInit(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } return &http.Response{ diff --git a/client/swarm_join_test.go b/client/swarm_join_test.go index 215483830b..9cd516c477 100644 --- a/client/swarm_join_test.go +++ b/client/swarm_join_test.go @@ -35,7 +35,7 @@ func TestSwarmJoin(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } return &http.Response{ diff --git a/client/swarm_leave_test.go b/client/swarm_leave_test.go index b5484b3382..36e4fe4003 100644 --- a/client/swarm_leave_test.go +++ b/client/swarm_leave_test.go @@ -48,7 +48,7 @@ func TestSwarmLeave(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } force := req.URL.Query().Get("force") diff --git a/client/swarm_unlock_test.go b/client/swarm_unlock_test.go index dbcc870e2d..b01eb07e18 100644 --- a/client/swarm_unlock_test.go +++ b/client/swarm_unlock_test.go @@ -35,7 +35,7 @@ func TestSwarmUnlock(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } return &http.Response{ diff --git a/client/swarm_update_test.go b/client/swarm_update_test.go index 3acad9da8a..98059f1738 100644 --- a/client/swarm_update_test.go +++ b/client/swarm_update_test.go @@ -35,7 +35,7 @@ func TestSwarmUpdate(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } return &http.Response{ diff --git a/client/volume_create_test.go b/client/volume_create_test.go index 173fe104e1..f4078c2f00 100644 --- a/client/volume_create_test.go +++ b/client/volume_create_test.go @@ -38,7 +38,7 @@ func TestVolumeCreate(t *testing.T) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, fmt.Errorf("expected POST method, got %s", req.Method) } diff --git a/client/volume_inspect_test.go b/client/volume_inspect_test.go index 04f00129b7..804411cf2d 100644 --- a/client/volume_inspect_test.go +++ b/client/volume_inspect_test.go @@ -59,7 +59,7 @@ func TestVolumeInspect(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, fmt.Errorf("expected GET method, got %s", req.Method) } content, err := json.Marshal(expected) diff --git a/client/volume_remove_test.go b/client/volume_remove_test.go index 762e046c11..73d5a2ddfd 100644 --- a/client/volume_remove_test.go +++ b/client/volume_remove_test.go @@ -34,7 +34,7 @@ func TestVolumeRemove(t *testing.T) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } - if req.Method != "DELETE" { + if req.Method != http.MethodDelete { return nil, fmt.Errorf("expected DELETE method, got %s", req.Method) } return &http.Response{ From d1817b61351667aadb6d8b5afea3518d5908cdc1 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sun, 13 Oct 2019 17:25:39 +0200 Subject: [PATCH 06/13] client: use constants for http status codes Signed-off-by: Sebastiaan van Stijn --- client/hijack_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/hijack_test.go b/client/hijack_test.go index 255f818501..69e5b41e2b 100644 --- a/client/hijack_test.go +++ b/client/hijack_test.go @@ -25,13 +25,13 @@ func TestTLSCloseWriter(t *testing.T) { defer close(chErr) if err := httputils.ParseForm(req); err != nil { chErr <- errors.Wrap(err, "error parsing form") - http.Error(w, err.Error(), 500) + http.Error(w, err.Error(), http.StatusInternalServerError) return } r, rw, err := httputils.HijackConnection(w) if err != nil { chErr <- errors.Wrap(err, "error hijacking connection") - http.Error(w, err.Error(), 500) + http.Error(w, err.Error(), http.StatusInternalServerError) return } defer r.Close() From 441b031bdaf542f2050cf7ef20822d0f1edd71ae Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sat, 12 Oct 2019 20:42:44 +0200 Subject: [PATCH 07/13] registry: use constants for http methods Signed-off-by: Sebastiaan van Stijn --- registry/auth.go | 6 ++-- registry/endpoint_v1.go | 2 +- registry/registry_mock_test.go | 32 +++++++++---------- registry/registry_test.go | 12 +++---- .../resumable/resumablerequestreader_test.go | 18 +++++------ registry/session.go | 16 +++++----- 6 files changed, 43 insertions(+), 43 deletions(-) diff --git a/registry/auth.go b/registry/auth.go index 3f58fc6cff..bae093ec97 100644 --- a/registry/auth.go +++ b/registry/auth.go @@ -33,7 +33,7 @@ func loginV1(authConfig *types.AuthConfig, apiEndpoint APIEndpoint, userAgent st return "", "", errdefs.System(errors.New("server Error: Server Address not set")) } - req, err := http.NewRequest("GET", serverAddress+"users/", nil) + req, err := http.NewRequest(http.MethodGet, serverAddress+"users/", nil) if err != nil { return "", "", err } @@ -140,7 +140,7 @@ func loginV2(authConfig *types.AuthConfig, endpoint APIEndpoint, userAgent strin } endpointStr := strings.TrimRight(endpoint.URL.String(), "/") + "/v2/" - req, err := http.NewRequest("GET", endpointStr, nil) + req, err := http.NewRequest(http.MethodGet, endpointStr, nil) if err != nil { if !foundV2 { err = fallbackError{err: err} @@ -262,7 +262,7 @@ func PingV2Registry(endpoint *url.URL, transport http.RoundTripper) (challenge.M Timeout: 15 * time.Second, } endpointStr := strings.TrimRight(endpoint.String(), "/") + "/v2/" - req, err := http.NewRequest("GET", endpointStr, nil) + req, err := http.NewRequest(http.MethodGet, endpointStr, nil) if err != nil { return nil, false, err } diff --git a/registry/endpoint_v1.go b/registry/endpoint_v1.go index 2fc2ea0e74..db342d1412 100644 --- a/registry/endpoint_v1.go +++ b/registry/endpoint_v1.go @@ -149,7 +149,7 @@ func (e *V1Endpoint) Ping() (PingResult, error) { return PingResult{Standalone: false}, nil } - req, err := http.NewRequest("GET", e.Path("_ping"), nil) + req, err := http.NewRequest(http.MethodGet, e.Path("_ping"), nil) if err != nil { return PingResult{Standalone: false}, err } diff --git a/registry/registry_mock_test.go b/registry/registry_mock_test.go index bf17eb9fc7..e2bbf676b3 100644 --- a/registry/registry_mock_test.go +++ b/registry/registry_mock_test.go @@ -97,19 +97,19 @@ func init() { r := mux.NewRouter() // /v1/ - r.HandleFunc("/v1/_ping", handlerGetPing).Methods("GET") - r.HandleFunc("/v1/images/{image_id:[^/]+}/{action:json|layer|ancestry}", handlerGetImage).Methods("GET") - r.HandleFunc("/v1/images/{image_id:[^/]+}/{action:json|layer|checksum}", handlerPutImage).Methods("PUT") - r.HandleFunc("/v1/repositories/{repository:.+}/tags", handlerGetDeleteTags).Methods("GET", "DELETE") - r.HandleFunc("/v1/repositories/{repository:.+}/tags/{tag:.+}", handlerGetTag).Methods("GET") - r.HandleFunc("/v1/repositories/{repository:.+}/tags/{tag:.+}", handlerPutTag).Methods("PUT") - r.HandleFunc("/v1/users{null:.*}", handlerUsers).Methods("GET", "POST", "PUT") - r.HandleFunc("/v1/repositories/{repository:.+}{action:/images|/}", handlerImages).Methods("GET", "PUT", "DELETE") - r.HandleFunc("/v1/repositories/{repository:.+}/auth", handlerAuth).Methods("PUT") - r.HandleFunc("/v1/search", handlerSearch).Methods("GET") + r.HandleFunc("/v1/_ping", handlerGetPing).Methods(http.MethodGet) + r.HandleFunc("/v1/images/{image_id:[^/]+}/{action:json|layer|ancestry}", handlerGetImage).Methods(http.MethodGet) + r.HandleFunc("/v1/images/{image_id:[^/]+}/{action:json|layer|checksum}", handlerPutImage).Methods(http.MethodPut) + r.HandleFunc("/v1/repositories/{repository:.+}/tags", handlerGetDeleteTags).Methods(http.MethodGet, http.MethodDelete) + r.HandleFunc("/v1/repositories/{repository:.+}/tags/{tag:.+}", handlerGetTag).Methods(http.MethodGet) + r.HandleFunc("/v1/repositories/{repository:.+}/tags/{tag:.+}", handlerPutTag).Methods(http.MethodPut) + r.HandleFunc("/v1/users{null:.*}", handlerUsers).Methods(http.MethodGet, http.MethodPost, http.MethodPut) + r.HandleFunc("/v1/repositories/{repository:.+}{action:/images|/}", handlerImages).Methods(http.MethodGet, http.MethodPut, http.MethodDelete) + r.HandleFunc("/v1/repositories/{repository:.+}/auth", handlerAuth).Methods(http.MethodPut) + r.HandleFunc("/v1/search", handlerSearch).Methods(http.MethodGet) // /v2/ - r.HandleFunc("/v2/version", handlerGetPing).Methods("GET") + r.HandleFunc("/v2/version", handlerGetPing).Methods(http.MethodGet) testHTTPServer = httptest.NewServer(handlerAccessLog(r)) testHTTPSServer = httptest.NewTLSServer(handlerAccessLog(r)) @@ -350,7 +350,7 @@ func handlerGetDeleteTags(w http.ResponseWriter, r *http.Request) { apiError(w, "Repository not found", 404) return } - if r.Method == "DELETE" { + if r.Method == http.MethodDelete { delete(testRepositories, repositoryName.String()) writeResponse(w, true, 200) return @@ -406,9 +406,9 @@ func handlerPutTag(w http.ResponseWriter, r *http.Request) { func handlerUsers(w http.ResponseWriter, r *http.Request) { code := 200 - if r.Method == "POST" { + if r.Method == http.MethodPost { code = 201 - } else if r.Method == "PUT" { + } else if r.Method == http.MethodPut { code = 204 } writeResponse(w, "", code) @@ -418,7 +418,7 @@ func handlerImages(w http.ResponseWriter, r *http.Request) { u, _ := url.Parse(testHTTPServer.URL) w.Header().Add("X-Docker-Endpoints", fmt.Sprintf("%s , %s ", u.Host, "test.example.com")) w.Header().Add("X-Docker-Token", fmt.Sprintf("FAKE-SESSION-%d", time.Now().UnixNano())) - if r.Method == "PUT" { + if r.Method == http.MethodPut { if strings.HasSuffix(r.URL.Path, "images") { writeResponse(w, "", 204) return @@ -426,7 +426,7 @@ func handlerImages(w http.ResponseWriter, r *http.Request) { writeResponse(w, "", 200) return } - if r.Method == "DELETE" { + if r.Method == http.MethodDelete { writeResponse(w, "", 204) return } diff --git a/registry/registry_test.go b/registry/registry_test.go index b7459471b3..51ca083e80 100644 --- a/registry/registry_test.go +++ b/registry/registry_test.go @@ -761,12 +761,12 @@ func TestSearchRepositories(t *testing.T) { func TestTrustedLocation(t *testing.T) { for _, url := range []string{"http://example.com", "https://example.com:7777", "http://docker.io", "http://test.docker.com", "https://fakedocker.com"} { - req, _ := http.NewRequest("GET", url, nil) + req, _ := http.NewRequest(http.MethodGet, url, nil) assert.Check(t, !trustedLocation(req)) } for _, url := range []string{"https://docker.io", "https://test.docker.com:80"} { - req, _ := http.NewRequest("GET", url, nil) + req, _ := http.NewRequest(http.MethodGet, url, nil) assert.Check(t, trustedLocation(req)) } } @@ -777,10 +777,10 @@ func TestAddRequiredHeadersToRedirectedRequests(t *testing.T) { {"https://foo.docker.io:7777", "http://bar.docker.com"}, {"https://foo.docker.io", "https://example.com"}, } { - reqFrom, _ := http.NewRequest("GET", urls[0], nil) + reqFrom, _ := http.NewRequest(http.MethodGet, urls[0], nil) reqFrom.Header.Add("Content-Type", "application/json") reqFrom.Header.Add("Authorization", "super_secret") - reqTo, _ := http.NewRequest("GET", urls[1], nil) + reqTo, _ := http.NewRequest(http.MethodGet, urls[1], nil) addRequiredHeadersToRedirectedRequests(reqTo, []*http.Request{reqFrom}) @@ -801,10 +801,10 @@ func TestAddRequiredHeadersToRedirectedRequests(t *testing.T) { {"https://docker.io", "https://docker.com"}, {"https://foo.docker.io:7777", "https://bar.docker.com"}, } { - reqFrom, _ := http.NewRequest("GET", urls[0], nil) + reqFrom, _ := http.NewRequest(http.MethodGet, urls[0], nil) reqFrom.Header.Add("Content-Type", "application/json") reqFrom.Header.Add("Authorization", "super_secret") - reqTo, _ := http.NewRequest("GET", urls[1], nil) + reqTo, _ := http.NewRequest(http.MethodGet, urls[1], nil) addRequiredHeadersToRedirectedRequests(reqTo, []*http.Request{reqFrom}) diff --git a/registry/resumable/resumablerequestreader_test.go b/registry/resumable/resumablerequestreader_test.go index c72c210e77..e67316401a 100644 --- a/registry/resumable/resumablerequestreader_test.go +++ b/registry/resumable/resumablerequestreader_test.go @@ -23,7 +23,7 @@ func TestResumableRequestHeaderSimpleErrors(t *testing.T) { client := &http.Client{} var req *http.Request - req, err := http.NewRequest("GET", ts.URL, nil) + req, err := http.NewRequest(http.MethodGet, ts.URL, nil) assert.NilError(t, err) resreq := &requestReader{} @@ -44,7 +44,7 @@ func TestResumableRequestHeaderNotTooMuchFailures(t *testing.T) { client := &http.Client{} var badReq *http.Request - badReq, err := http.NewRequest("GET", "I'm not an url", nil) + badReq, err := http.NewRequest(http.MethodGet, "I'm not an url", nil) assert.NilError(t, err) resreq := &requestReader{ @@ -64,7 +64,7 @@ func TestResumableRequestHeaderTooMuchFailures(t *testing.T) { client := &http.Client{} var badReq *http.Request - badReq, err := http.NewRequest("GET", "I'm not an url", nil) + badReq, err := http.NewRequest(http.MethodGet, "I'm not an url", nil) assert.NilError(t, err) resreq := &requestReader{ @@ -92,7 +92,7 @@ func (errorReaderCloser) Read(p []byte) (n int, err error) { // If an unknown error is encountered, return 0, nil and log it func TestResumableRequestReaderWithReadError(t *testing.T) { var req *http.Request - req, err := http.NewRequest("GET", "", nil) + req, err := http.NewRequest(http.MethodGet, "", nil) assert.NilError(t, err) client := &http.Client{} @@ -123,7 +123,7 @@ func TestResumableRequestReaderWithReadError(t *testing.T) { func TestResumableRequestReaderWithEOFWith416Response(t *testing.T) { var req *http.Request - req, err := http.NewRequest("GET", "", nil) + req, err := http.NewRequest(http.MethodGet, "", nil) assert.NilError(t, err) client := &http.Client{} @@ -159,7 +159,7 @@ func TestResumableRequestReaderWithServerDoesntSupportByteRanges(t *testing.T) { defer ts.Close() var req *http.Request - req, err := http.NewRequest("GET", ts.URL, nil) + req, err := http.NewRequest(http.MethodGet, ts.URL, nil) assert.NilError(t, err) client := &http.Client{} @@ -185,7 +185,7 @@ func TestResumableRequestReaderWithZeroTotalSize(t *testing.T) { defer ts.Close() var req *http.Request - req, err := http.NewRequest("GET", ts.URL, nil) + req, err := http.NewRequest(http.MethodGet, ts.URL, nil) assert.NilError(t, err) client := &http.Client{} @@ -210,7 +210,7 @@ func TestResumableRequestReader(t *testing.T) { defer ts.Close() var req *http.Request - req, err := http.NewRequest("GET", ts.URL, nil) + req, err := http.NewRequest(http.MethodGet, ts.URL, nil) assert.NilError(t, err) client := &http.Client{} @@ -236,7 +236,7 @@ func TestResumableRequestReaderWithInitialResponse(t *testing.T) { defer ts.Close() var req *http.Request - req, err := http.NewRequest("GET", ts.URL, nil) + req, err := http.NewRequest(http.MethodGet, ts.URL, nil) assert.NilError(t, err) client := &http.Client{} diff --git a/registry/session.go b/registry/session.go index 59f5ad50ff..03be62bd61 100644 --- a/registry/session.go +++ b/registry/session.go @@ -289,7 +289,7 @@ func (r *Session) GetRemoteImageLayer(imgID, registry string, imgSize int64) (io imageURL = fmt.Sprintf("%simages/%s/layer", registry, imgID) ) - req, err := http.NewRequest("GET", imageURL, nil) + req, err := http.NewRequest(http.MethodGet, imageURL, nil) if err != nil { return nil, fmt.Errorf("Error while getting from the server: %v", err) } @@ -423,7 +423,7 @@ func (r *Session) GetRepositoryData(name reference.Named) (*RepositoryData, erro logrus.Debugf("[registry] Calling GET %s", repositoryTarget) - req, err := http.NewRequest("GET", repositoryTarget, nil) + req, err := http.NewRequest(http.MethodGet, repositoryTarget, nil) if err != nil { return nil, err } @@ -490,7 +490,7 @@ func (r *Session) PushImageChecksumRegistry(imgData *ImgData, registry string) e logrus.Debugf("[registry] Calling PUT %s", u) - req, err := http.NewRequest("PUT", u, nil) + req, err := http.NewRequest(http.MethodPut, u, nil) if err != nil { return err } @@ -528,7 +528,7 @@ func (r *Session) PushImageJSONRegistry(imgData *ImgData, jsonRaw []byte, regist logrus.Debugf("[registry] Calling PUT %s", u) - req, err := http.NewRequest("PUT", u, bytes.NewReader(jsonRaw)) + req, err := http.NewRequest(http.MethodPut, u, bytes.NewReader(jsonRaw)) if err != nil { return err } @@ -573,7 +573,7 @@ func (r *Session) PushImageLayerRegistry(imgID string, layer io.Reader, registry h.Write([]byte{'\n'}) checksumLayer := io.TeeReader(tarsumLayer, h) - req, err := http.NewRequest("PUT", u, checksumLayer) + req, err := http.NewRequest(http.MethodPut, u, checksumLayer) if err != nil { return "", "", err } @@ -610,7 +610,7 @@ func (r *Session) PushRegistryTag(remote reference.Named, revision, tag, registr revision = "\"" + revision + "\"" path := fmt.Sprintf("repositories/%s/tags/%s", reference.Path(remote), tag) - req, err := http.NewRequest("PUT", registry+path, strings.NewReader(revision)) + req, err := http.NewRequest(http.MethodPut, registry+path, strings.NewReader(revision)) if err != nil { return err } @@ -714,7 +714,7 @@ func (r *Session) PushImageJSONIndex(remote reference.Named, imgList []*ImgData, } func (r *Session) putImageRequest(u string, headers map[string][]string, body []byte) (*http.Response, error) { - req, err := http.NewRequest("PUT", u, bytes.NewReader(body)) + req, err := http.NewRequest(http.MethodPut, u, bytes.NewReader(body)) if err != nil { return nil, err } @@ -741,7 +741,7 @@ func (r *Session) SearchRepositories(term string, limit int) (*registrytypes.Sea logrus.Debugf("Index server: %s", r.indexEndpoint) u := r.indexEndpoint.String() + "search?q=" + url.QueryEscape(term) + "&n=" + url.QueryEscape(fmt.Sprintf("%d", limit)) - req, err := http.NewRequest("GET", u, nil) + req, err := http.NewRequest(http.MethodGet, u, nil) if err != nil { return nil, errors.Wrap(errdefs.InvalidParameter(err), "Error building request") } From 63e62d13a05da7ac3f24c8af703b9babd41eb558 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sun, 13 Oct 2019 17:25:25 +0200 Subject: [PATCH 08/13] registry: use constants for http status codes Signed-off-by: Sebastiaan van Stijn --- registry/registry_mock_test.go | 50 +++++++++---------- registry/resumable/resumablerequestreader.go | 4 +- .../resumable/resumablerequestreader_test.go | 4 +- registry/session.go | 36 ++++++------- 4 files changed, 47 insertions(+), 47 deletions(-) diff --git a/registry/registry_mock_test.go b/registry/registry_mock_test.go index e2bbf676b3..033e7d1663 100644 --- a/registry/registry_mock_test.go +++ b/registry/registry_mock_test.go @@ -281,12 +281,12 @@ func requiresAuth(w http.ResponseWriter, r *http.Request) bool { return true } w.Header().Add("WWW-Authenticate", "token") - apiError(w, "Wrong auth", 401) + apiError(w, "Wrong auth", http.StatusUnauthorized) return false } func handlerGetPing(w http.ResponseWriter, r *http.Request) { - writeResponse(w, true, 200) + writeResponse(w, true, http.StatusOK) } func handlerGetImage(w http.ResponseWriter, r *http.Request) { @@ -323,17 +323,17 @@ func handlerPutImage(w http.ResponseWriter, r *http.Request) { } if checksum := r.Header.Get("X-Docker-Checksum"); checksum != "" { if checksum != layer["checksum_simple"] && checksum != layer["checksum_tarsum"] { - apiError(w, "Wrong checksum", 400) + apiError(w, "Wrong checksum", http.StatusBadRequest) return } } body, err := ioutil.ReadAll(r.Body) if err != nil { - apiError(w, fmt.Sprintf("Error: %s", err), 500) + apiError(w, fmt.Sprintf("Error: %s", err), http.StatusInternalServerError) return } layer[action] = string(body) - writeResponse(w, true, 200) + writeResponse(w, true, http.StatusOK) } func handlerGetDeleteTags(w http.ResponseWriter, r *http.Request) { @@ -342,20 +342,20 @@ func handlerGetDeleteTags(w http.ResponseWriter, r *http.Request) { } repositoryName, err := reference.WithName(mux.Vars(r)["repository"]) if err != nil { - apiError(w, "Could not parse repository", 400) + apiError(w, "Could not parse repository", http.StatusBadRequest) return } tags, exists := testRepositories[repositoryName.String()] if !exists { - apiError(w, "Repository not found", 404) + apiError(w, "Repository not found", http.StatusNotFound) return } if r.Method == http.MethodDelete { delete(testRepositories, repositoryName.String()) - writeResponse(w, true, 200) + writeResponse(w, true, http.StatusOK) return } - writeResponse(w, tags, 200) + writeResponse(w, tags, http.StatusOK) } func handlerGetTag(w http.ResponseWriter, r *http.Request) { @@ -365,21 +365,21 @@ func handlerGetTag(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) repositoryName, err := reference.WithName(vars["repository"]) if err != nil { - apiError(w, "Could not parse repository", 400) + apiError(w, "Could not parse repository", http.StatusBadRequest) return } tagName := vars["tag"] tags, exists := testRepositories[repositoryName.String()] if !exists { - apiError(w, "Repository not found", 404) + apiError(w, "Repository not found", http.StatusNotFound) return } tag, exists := tags[tagName] if !exists { - apiError(w, "Tag not found", 404) + apiError(w, "Tag not found", http.StatusNotFound) return } - writeResponse(w, tag, 200) + writeResponse(w, tag, http.StatusOK) } func handlerPutTag(w http.ResponseWriter, r *http.Request) { @@ -389,7 +389,7 @@ func handlerPutTag(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) repositoryName, err := reference.WithName(vars["repository"]) if err != nil { - apiError(w, "Could not parse repository", 400) + apiError(w, "Could not parse repository", http.StatusBadRequest) return } tagName := vars["tag"] @@ -401,15 +401,15 @@ func handlerPutTag(w http.ResponseWriter, r *http.Request) { tagValue := "" readJSON(r, tagValue) tags[tagName] = tagValue - writeResponse(w, true, 200) + writeResponse(w, true, http.StatusOK) } func handlerUsers(w http.ResponseWriter, r *http.Request) { - code := 200 + code := http.StatusOK if r.Method == http.MethodPost { - code = 201 + code = http.StatusCreated } else if r.Method == http.MethodPut { - code = 204 + code = http.StatusNoContent } writeResponse(w, "", code) } @@ -420,14 +420,14 @@ func handlerImages(w http.ResponseWriter, r *http.Request) { w.Header().Add("X-Docker-Token", fmt.Sprintf("FAKE-SESSION-%d", time.Now().UnixNano())) if r.Method == http.MethodPut { if strings.HasSuffix(r.URL.Path, "images") { - writeResponse(w, "", 204) + writeResponse(w, "", http.StatusNoContent) return } - writeResponse(w, "", 200) + writeResponse(w, "", http.StatusOK) return } if r.Method == http.MethodDelete { - writeResponse(w, "", 204) + writeResponse(w, "", http.StatusNoContent) return } var images []map[string]string @@ -438,11 +438,11 @@ func handlerImages(w http.ResponseWriter, r *http.Request) { image["Tag"] = "latest" images = append(images, image) } - writeResponse(w, images, 200) + writeResponse(w, images, http.StatusOK) } func handlerAuth(w http.ResponseWriter, r *http.Request) { - writeResponse(w, "OK", 200) + writeResponse(w, "OK", http.StatusOK) } func handlerSearch(w http.ResponseWriter, r *http.Request) { @@ -451,7 +451,7 @@ func handlerSearch(w http.ResponseWriter, r *http.Request) { NumResults: 1, Results: []registrytypes.SearchResult{{Name: "fakeimage", StarCount: 42}}, } - writeResponse(w, result, 200) + writeResponse(w, result, http.StatusOK) } func TestPing(t *testing.T) { @@ -459,7 +459,7 @@ func TestPing(t *testing.T) { if err != nil { t.Fatal(err) } - assertEqual(t, res.StatusCode, 200, "") + assertEqual(t, res.StatusCode, http.StatusOK, "") assertEqual(t, res.Header.Get("X-Docker-Registry-Config"), "mock", "This is not a Mocked Registry") } diff --git a/registry/resumable/resumablerequestreader.go b/registry/resumable/resumablerequestreader.go index 8e97a1a4d1..3649f36ede 100644 --- a/registry/resumable/resumablerequestreader.go +++ b/registry/resumable/resumablerequestreader.go @@ -56,10 +56,10 @@ func (r *requestReader) Read(p []byte) (n int, err error) { r.cleanUpResponse() return 0, err } - if r.currentResponse.StatusCode == 416 && r.lastRange == r.totalSize && r.currentResponse.ContentLength == 0 { + if r.currentResponse.StatusCode == http.StatusRequestedRangeNotSatisfiable && r.lastRange == r.totalSize && r.currentResponse.ContentLength == 0 { r.cleanUpResponse() return 0, io.EOF - } else if r.currentResponse.StatusCode != 206 && r.lastRange != 0 && isFreshRequest { + } else if r.currentResponse.StatusCode != http.StatusPartialContent && r.lastRange != 0 && isFreshRequest { r.cleanUpResponse() return 0, fmt.Errorf("the server doesn't support byte ranges") } diff --git a/registry/resumable/resumablerequestreader_test.go b/registry/resumable/resumablerequestreader_test.go index e67316401a..b2c3cad25b 100644 --- a/registry/resumable/resumablerequestreader_test.go +++ b/registry/resumable/resumablerequestreader_test.go @@ -99,7 +99,7 @@ func TestResumableRequestReaderWithReadError(t *testing.T) { response := &http.Response{ Status: "500 Internal Server", - StatusCode: 500, + StatusCode: http.StatusInternalServerError, ContentLength: 0, Close: true, Body: errorReaderCloser{}, @@ -130,7 +130,7 @@ func TestResumableRequestReaderWithEOFWith416Response(t *testing.T) { response := &http.Response{ Status: "416 Requested Range Not Satisfiable", - StatusCode: 416, + StatusCode: http.StatusRequestedRangeNotSatisfiable, ContentLength: 0, Close: true, Body: ioutil.NopCloser(strings.NewReader("")), diff --git a/registry/session.go b/registry/session.go index 03be62bd61..f11a8847ba 100644 --- a/registry/session.go +++ b/registry/session.go @@ -225,8 +225,8 @@ func (r *Session) GetRemoteHistory(imgID, registry string) ([]string, error) { return nil, err } defer res.Body.Close() - if res.StatusCode != 200 { - if res.StatusCode == 401 { + if res.StatusCode != http.StatusOK { + if res.StatusCode == http.StatusUnauthorized { return nil, errcode.ErrorCodeUnauthorized.WithArgs() } return nil, newJSONError(fmt.Sprintf("Server error: %d trying to fetch remote history for %s", res.StatusCode, imgID), res) @@ -248,7 +248,7 @@ func (r *Session) LookupRemoteImage(imgID, registry string) error { return err } res.Body.Close() - if res.StatusCode != 200 { + if res.StatusCode != http.StatusOK { return newJSONError(fmt.Sprintf("HTTP code %d", res.StatusCode), res) } return nil @@ -261,7 +261,7 @@ func (r *Session) GetRemoteImageJSON(imgID, registry string) ([]byte, int64, err return nil, -1, fmt.Errorf("Failed to download json: %s", err) } defer res.Body.Close() - if res.StatusCode != 200 { + if res.StatusCode != http.StatusOK { return nil, -1, newJSONError(fmt.Sprintf("HTTP code %d", res.StatusCode), res) } // if the size header is not present, then set it to '-1' @@ -308,7 +308,7 @@ func (r *Session) GetRemoteImageLayer(imgID, registry string, imgSize int64) (io statusCode, imgID) } - if res.StatusCode != 200 { + if res.StatusCode != http.StatusOK { res.Body.Close() return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)", res.StatusCode, imgID) @@ -347,7 +347,7 @@ func (r *Session) GetRemoteTag(registries []string, repositoryRef reference.Name if res.StatusCode == 404 { return "", ErrRepoNotFound } - if res.StatusCode != 200 { + if res.StatusCode != http.StatusOK { continue } @@ -385,7 +385,7 @@ func (r *Session) GetRemoteTags(registries []string, repositoryRef reference.Nam if res.StatusCode == 404 { return nil, ErrRepoNotFound } - if res.StatusCode != 200 { + if res.StatusCode != http.StatusOK { continue } @@ -441,14 +441,14 @@ func (r *Session) GetRepositoryData(name reference.Named) (*RepositoryData, erro return nil, fmt.Errorf("Error while pulling image: %v", err) } defer res.Body.Close() - if res.StatusCode == 401 { + if res.StatusCode == http.StatusUnauthorized { return nil, errcode.ErrorCodeUnauthorized.WithArgs() } // TODO: Right now we're ignoring checksums in the response body. // In the future, we need to use them to check image validity. if res.StatusCode == 404 { return nil, newJSONError(fmt.Sprintf("HTTP code: %d", res.StatusCode), res) - } else if res.StatusCode != 200 { + } else if res.StatusCode != http.StatusOK { errBody, err := ioutil.ReadAll(res.Body) if err != nil { logrus.Debugf("Error reading response body: %s", err) @@ -505,7 +505,7 @@ func (r *Session) PushImageChecksumRegistry(imgData *ImgData, registry string) e if len(res.Cookies()) > 0 { r.client.Jar.SetCookies(req.URL, res.Cookies()) } - if res.StatusCode != 200 { + if res.StatusCode != http.StatusOK { errBody, err := ioutil.ReadAll(res.Body) if err != nil { return fmt.Errorf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err) @@ -539,10 +539,10 @@ func (r *Session) PushImageJSONRegistry(imgData *ImgData, jsonRaw []byte, regist return fmt.Errorf("Failed to upload metadata: %s", err) } defer res.Body.Close() - if res.StatusCode == 401 && strings.HasPrefix(registry, "http://") { + if res.StatusCode == http.StatusUnauthorized && strings.HasPrefix(registry, "http://") { return newJSONError("HTTP code 401, Docker will not send auth headers over HTTP.", res) } - if res.StatusCode != 200 { + if res.StatusCode != http.StatusOK { errBody, err := ioutil.ReadAll(res.Body) if err != nil { return newJSONError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res) @@ -591,7 +591,7 @@ func (r *Session) PushImageLayerRegistry(imgID string, layer io.Reader, registry } defer res.Body.Close() - if res.StatusCode != 200 { + if res.StatusCode != http.StatusOK { errBody, err := ioutil.ReadAll(res.Body) if err != nil { return "", "", newJSONError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res) @@ -621,7 +621,7 @@ func (r *Session) PushRegistryTag(remote reference.Named, revision, tag, registr return err } res.Body.Close() - if res.StatusCode != 200 && res.StatusCode != 201 { + if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated { return newJSONError(fmt.Sprintf("Internal server error: %d trying to push tag %s on %s", res.StatusCode, tag, reference.Path(remote)), res) } return nil @@ -675,13 +675,13 @@ func (r *Session) PushImageJSONIndex(remote reference.Named, imgList []*ImgData, } defer res.Body.Close() - if res.StatusCode == 401 { + if res.StatusCode == http.StatusUnauthorized { return nil, errcode.ErrorCodeUnauthorized.WithArgs() } var tokens, endpoints []string if !validate { - if res.StatusCode != 200 && res.StatusCode != 201 { + if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated { errBody, err := ioutil.ReadAll(res.Body) if err != nil { logrus.Debugf("Error reading response body: %s", err) @@ -699,7 +699,7 @@ func (r *Session) PushImageJSONIndex(remote reference.Named, imgList []*ImgData, return nil, err } } else { - if res.StatusCode != 204 { + if res.StatusCode != http.StatusNoContent { errBody, err := ioutil.ReadAll(res.Body) if err != nil { logrus.Debugf("Error reading response body: %s", err) @@ -752,7 +752,7 @@ func (r *Session) SearchRepositories(term string, limit int) (*registrytypes.Sea return nil, errdefs.System(err) } defer res.Body.Close() - if res.StatusCode != 200 { + if res.StatusCode != http.StatusOK { return nil, newJSONError(fmt.Sprintf("Unexpected status code %d", res.StatusCode), res) } result := new(registrytypes.SearchResults) From 3b8487521676f6065f6734c080ba9457a43c9090 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sat, 12 Oct 2019 20:40:56 +0200 Subject: [PATCH 09/13] builder-next: use constants for http methods Signed-off-by: Sebastiaan van Stijn --- builder/builder-next/reqbodyhandler.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/builder/builder-next/reqbodyhandler.go b/builder/builder-next/reqbodyhandler.go index b07503de13..1017a5e7aa 100644 --- a/builder/builder-next/reqbodyhandler.go +++ b/builder/builder-next/reqbodyhandler.go @@ -42,7 +42,7 @@ func (h *reqBodyHandler) newRequest(rc io.ReadCloser) (string, func()) { func (h *reqBodyHandler) RoundTrip(req *http.Request) (*http.Response, error) { host := req.URL.Host if strings.HasPrefix(host, urlPrefix) { - if req.Method != "GET" { + if req.Method != http.MethodGet { return nil, errors.Errorf("invalid request") } id := strings.TrimPrefix(host, urlPrefix) From 984d5bc30cfacd63872f8c1c4d366c8211a112bd Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sun, 13 Oct 2019 17:26:23 +0200 Subject: [PATCH 10/13] builder-next: use constants for http status codes Signed-off-by: Sebastiaan van Stijn --- builder/builder-next/reqbodyhandler.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/builder/builder-next/reqbodyhandler.go b/builder/builder-next/reqbodyhandler.go index 1017a5e7aa..9159218295 100644 --- a/builder/builder-next/reqbodyhandler.go +++ b/builder/builder-next/reqbodyhandler.go @@ -57,7 +57,7 @@ func (h *reqBodyHandler) RoundTrip(req *http.Request) (*http.Response, error) { resp := &http.Response{ Status: "200 OK", - StatusCode: 200, + StatusCode: http.StatusOK, Body: rc, ContentLength: -1, } From 9c590ed5c5eece661f8198b2bcb8f96d9f82fea9 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sat, 12 Oct 2019 20:41:39 +0200 Subject: [PATCH 11/13] daemon/logger/splunk: use constants for http methods Signed-off-by: Sebastiaan van Stijn --- daemon/logger/splunk/splunk.go | 2 +- daemon/logger/splunk/splunk_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/daemon/logger/splunk/splunk.go b/daemon/logger/splunk/splunk.go index 331bbfa5ce..64f55ffd6b 100644 --- a/daemon/logger/splunk/splunk.go +++ b/daemon/logger/splunk/splunk.go @@ -495,7 +495,7 @@ func (l *splunkLogger) tryPostMessages(ctx context.Context, messages []*splunkMe return err } } - req, err := http.NewRequest("POST", l.url, bytes.NewBuffer(buffer.Bytes())) + req, err := http.NewRequest(http.MethodPost, l.url, bytes.NewBuffer(buffer.Bytes())) if err != nil { return err } diff --git a/daemon/logger/splunk/splunk_test.go b/daemon/logger/splunk/splunk_test.go index db1e905a73..fa9b6cb6bf 100644 --- a/daemon/logger/splunk/splunk_test.go +++ b/daemon/logger/splunk/splunk_test.go @@ -105,7 +105,7 @@ func TestNewWithProxy(t *testing.T) { proxyFunc := splunkLogger.transport.Proxy assert.Assert(t, proxyFunc != nil) - req, err := http.NewRequest("GET", splunkURL, nil) + req, err := http.NewRequest(http.MethodGet, splunkURL, nil) assert.NilError(t, err) proxyURL, err := proxyFunc(req) From 5ba167ce8a1c34fbb6c49f246012d197455fecfa Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sat, 12 Oct 2019 20:43:46 +0200 Subject: [PATCH 12/13] pkg/authorization: use constants for http methods Signed-off-by: Sebastiaan van Stijn --- pkg/authorization/api_test.go | 2 +- pkg/authorization/authz_unix_test.go | 4 ++-- pkg/authorization/middleware_unix_test.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pkg/authorization/api_test.go b/pkg/authorization/api_test.go index 9d51e9e66e..617fd69a17 100644 --- a/pkg/authorization/api_test.go +++ b/pkg/authorization/api_test.go @@ -46,7 +46,7 @@ func TestPeerCertificateMarshalJSON(t *testing.T) { var certs = []*x509.Certificate{cert} addr := "www.authz.com/auth" - req, err := http.NewRequest("GET", addr, nil) + req, err := http.NewRequest(http.MethodGet, addr, nil) assert.NilError(t, err) req.RequestURI = addr diff --git a/pkg/authorization/authz_unix_test.go b/pkg/authorization/authz_unix_test.go index c38b5e1566..584ef89104 100644 --- a/pkg/authorization/authz_unix_test.go +++ b/pkg/authorization/authz_unix_test.go @@ -38,7 +38,7 @@ func TestAuthZRequestPluginError(t *testing.T) { User: "user", RequestBody: []byte("sample body"), RequestURI: "www.authz.com/auth", - RequestMethod: "GET", + RequestMethod: http.MethodGet, RequestHeaders: map[string]string{"header": "value"}, } server.replayResponse = Response{ @@ -69,7 +69,7 @@ func TestAuthZRequestPlugin(t *testing.T) { User: "user", RequestBody: []byte("sample body"), RequestURI: "www.authz.com/auth", - RequestMethod: "GET", + RequestMethod: http.MethodGet, RequestHeaders: map[string]string{"header": "value"}, } server.replayResponse = Response{ diff --git a/pkg/authorization/middleware_unix_test.go b/pkg/authorization/middleware_unix_test.go index 450e7fbbb7..b399d2b805 100644 --- a/pkg/authorization/middleware_unix_test.go +++ b/pkg/authorization/middleware_unix_test.go @@ -34,7 +34,7 @@ func TestMiddlewareWrapHandler(t *testing.T) { assert.Assert(t, mdHandler != nil) addr := "www.example.com/auth" - req, _ := http.NewRequest("GET", addr, nil) + req, _ := http.NewRequest(http.MethodGet, addr, nil) req.RequestURI = addr req.Header.Add("header", "value") From aa655a4d73693741cd3f8bc44566eb34585b3303 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sat, 12 Oct 2019 20:44:07 +0200 Subject: [PATCH 13/13] pkg/plugins: use constants for http methods Signed-off-by: Sebastiaan van Stijn --- pkg/plugins/client_test.go | 8 ++++---- pkg/plugins/plugin_test.go | 2 +- pkg/plugins/transport/http_test.go | 2 +- pkg/plugins/transport/transport.go | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pkg/plugins/client_test.go b/pkg/plugins/client_test.go index 12f67db570..2540ec3561 100644 --- a/pkg/plugins/client_test.go +++ b/pkg/plugins/client_test.go @@ -70,7 +70,7 @@ func TestEchoInputOutput(t *testing.T) { m := Manifest{[]string{"VolumeDriver", "NetworkDriver"}} mux.HandleFunc("/Test.Echo", func(w http.ResponseWriter, r *http.Request) { - if r.Method != "POST" { + if r.Method != http.MethodPost { t.Fatalf("Expected POST, got %s\n", r.Method) } @@ -185,7 +185,7 @@ func TestClientStream(t *testing.T) { var output Manifest mux.HandleFunc("/Test.Echo", func(w http.ResponseWriter, r *http.Request) { - if r.Method != "POST" { + if r.Method != http.MethodPost { t.Fatalf("Expected POST, got %s", r.Method) } @@ -218,7 +218,7 @@ func TestClientSendFile(t *testing.T) { t.Fatal(err) } mux.HandleFunc("/Test.Echo", func(w http.ResponseWriter, r *http.Request) { - if r.Method != "POST" { + if r.Method != http.MethodPost { t.Fatalf("Expected POST, got %s\n", r.Method) } @@ -263,7 +263,7 @@ type testRequestWrapper struct { } func (w *testRequestWrapper) NewRequest(path string, data io.Reader) (*http.Request, error) { - req, err := http.NewRequest("POST", path, data) + req, err := http.NewRequest(http.MethodPost, path, data) if err != nil { return nil, err } diff --git a/pkg/plugins/plugin_test.go b/pkg/plugins/plugin_test.go index ce98078f87..12c35ccbb2 100644 --- a/pkg/plugins/plugin_test.go +++ b/pkg/plugins/plugin_test.go @@ -95,7 +95,7 @@ func TestPluginWithNoManifest(t *testing.T) { } mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) { - if r.Method != "POST" { + if r.Method != http.MethodPost { t.Fatalf("Expected POST, got %s\n", r.Method) } diff --git a/pkg/plugins/transport/http_test.go b/pkg/plugins/transport/http_test.go index 78ab23724b..2573306cf8 100644 --- a/pkg/plugins/transport/http_test.go +++ b/pkg/plugins/transport/http_test.go @@ -17,5 +17,5 @@ func TestHTTPTransport(t *testing.T) { if err != nil { t.Fatal(err) } - assert.Check(t, is.Equal("POST", request.Method)) + assert.Check(t, is.Equal(http.MethodPost, request.Method)) } diff --git a/pkg/plugins/transport/transport.go b/pkg/plugins/transport/transport.go index 9cb13335a8..6c66cad662 100644 --- a/pkg/plugins/transport/transport.go +++ b/pkg/plugins/transport/transport.go @@ -27,7 +27,7 @@ func newHTTPRequest(path string, data io.Reader) (*http.Request, error) { if !strings.HasPrefix(path, "/") { path = "/" + path } - req, err := http.NewRequest("POST", path, data) + req, err := http.NewRequest(http.MethodPost, path, data) if err != nil { return nil, err }