Browse Source

registry: use constants for http status codes

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
Sebastiaan van Stijn 5 years ago
parent
commit
63e62d13a0

+ 25 - 25
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")
 }

+ 2 - 2
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")
 	}

+ 2 - 2
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("")),

+ 18 - 18
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)