Merge pull request #40081 from thaJeztah/http_constants

Use http constants for HTTP methods and status codes
This commit is contained in:
Justin Cormack 2019-10-17 11:30:26 -07:00 committed by GitHub
commit f681590a25
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
69 changed files with 183 additions and 183 deletions

View File

@ -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)

View File

@ -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 {

View File

@ -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()

View File

@ -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()

View File

@ -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)
@ -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,
}

View File

@ -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)
}

View File

@ -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{

View File

@ -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{

View File

@ -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{

View File

@ -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{

View File

@ -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()

View File

@ -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 ?

View File

@ -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
}

View File

@ -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()

View File

@ -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()

View File

@ -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()

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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()

View File

@ -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{

View File

@ -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")

View File

@ -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{

View File

@ -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
}

View File

@ -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,

View File

@ -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{

View File

@ -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{

View File

@ -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")

View File

@ -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{

View File

@ -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{

View File

@ -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{})
}

View File

@ -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)
}
}

View File

@ -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{

View File

@ -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{

View File

@ -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{

View File

@ -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{

View File

@ -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{

View File

@ -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")

View File

@ -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)
}

View File

@ -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{

View File

@ -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{

View File

@ -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")

View File

@ -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{

View File

@ -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{

View File

@ -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)
}

View File

@ -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)

View File

@ -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{

View File

@ -507,7 +507,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
}

View File

@ -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)

View File

@ -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.

View File

@ -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")
}

View File

@ -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)

View File

@ -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

View File

@ -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{

View File

@ -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")

View File

@ -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
}

View File

@ -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)
}

View File

@ -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))
}

View File

@ -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
}

View File

@ -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
}

View File

@ -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
}

View File

@ -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))
@ -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 == "DELETE" {
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
if r.Method == "POST" {
code = 201
} else if r.Method == "PUT" {
code = 204
code := http.StatusOK
if r.Method == http.MethodPost {
code = http.StatusCreated
} else if r.Method == http.MethodPut {
code = http.StatusNoContent
}
writeResponse(w, "", code)
}
@ -418,16 +418,16 @@ 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)
writeResponse(w, "", http.StatusNoContent)
return
}
writeResponse(w, "", 200)
writeResponse(w, "", http.StatusOK)
return
}
if r.Method == "DELETE" {
writeResponse(w, "", 204)
if r.Method == http.MethodDelete {
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")
}

View File

@ -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})

View File

@ -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")
}

View File

@ -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,14 +92,14 @@ 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{}
response := &http.Response{
Status: "500 Internal Server",
StatusCode: 500,
StatusCode: http.StatusInternalServerError,
ContentLength: 0,
Close: true,
Body: errorReaderCloser{},
@ -123,14 +123,14 @@ 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{}
response := &http.Response{
Status: "416 Requested Range Not Satisfiable",
StatusCode: 416,
StatusCode: http.StatusRequestedRangeNotSatisfiable,
ContentLength: 0,
Close: true,
Body: ioutil.NopCloser(strings.NewReader("")),
@ -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{}

View File

@ -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'
@ -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)
}
@ -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
}
@ -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
}
@ -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)
@ -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
}
@ -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)
@ -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
}
@ -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)
@ -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
}
@ -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)
@ -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
}
@ -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)
@ -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")
}
@ -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)

View File

@ -329,7 +329,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)
}
@ -684,7 +684,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
}

View File

@ -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")
}