From 940b9adabd24d23034bdd89186ca3f582b913057 Mon Sep 17 00:00:00 2001 From: xiekeyang Date: Thu, 24 May 2018 19:10:45 +0800 Subject: [PATCH] Indicate HTTP status code by library const (#703) --- controller/storagesvc.go | 2 +- controller/workflowApiProxy.go | 2 +- environments/binary/server.go | 2 +- environments/fetcher/fetcher.go | 22 +++++++++++----------- error.go | 22 +++++++++++----------- executor/api.go | 8 ++++---- fission/migrate.go | 2 +- fission/upgrade.go | 2 +- mqtrigger/messageQueue/asq_test.go | 12 ++++++------ storagesvc/storagesvc.go | 24 ++++++++++++------------ 10 files changed, 49 insertions(+), 49 deletions(-) diff --git a/controller/storagesvc.go b/controller/storagesvc.go index faab0d8e..1b854d3f 100644 --- a/controller/storagesvc.go +++ b/controller/storagesvc.go @@ -30,7 +30,7 @@ func (api *API) StorageServiceProxy(w http.ResponseWriter, r *http.Request) { if err != nil { msg := fmt.Sprintf("Error parsing url %v: %v", u, err) log.Println(msg) - http.Error(w, msg, 500) + http.Error(w, msg, http.StatusInternalServerError) return } director := func(req *http.Request) { diff --git a/controller/workflowApiProxy.go b/controller/workflowApiProxy.go index 7ebd2d8b..ba8fbbdd 100644 --- a/controller/workflowApiProxy.go +++ b/controller/workflowApiProxy.go @@ -13,7 +13,7 @@ func (api *API) WorkflowApiserverProxy(w http.ResponseWriter, r *http.Request) { ssUrl, err := url.Parse(u) if err != nil { msg := fmt.Sprintf("Error parsing url %v: %v", u, err) - http.Error(w, msg, 500) + http.Error(w, msg, http.StatusInternalServerError) return } diff --git a/environments/binary/server.go b/environments/binary/server.go index 28ae70fa..2ea99a04 100644 --- a/environments/binary/server.go +++ b/environments/binary/server.go @@ -46,7 +46,7 @@ type ( func (bs *BinaryServer) SpecializeHandler(w http.ResponseWriter, r *http.Request) { if specialized { - w.WriteHeader(400) + w.WriteHeader(http.StatusBadRequest) w.Write([]byte("Not a generic container")) return } diff --git a/environments/fetcher/fetcher.go b/environments/fetcher/fetcher.go index 157da92c..56289f31 100644 --- a/environments/fetcher/fetcher.go +++ b/environments/fetcher/fetcher.go @@ -221,13 +221,13 @@ func (fetcher *Fetcher) Fetch(req FetchRequest) (int, error) { if len(req.Filename) == 0 { e := fmt.Sprintf("Fetch request received for an empty file name, request: %v", req) log.Printf(e) - return 400, errors.New(e) + return http.StatusBadRequest, errors.New(e) } // verify first if the file already exists. if _, err := os.Stat(filepath.Join(fetcher.sharedVolumePath, req.Filename)); err == nil { log.Printf("Requested file: %s already exists at %s. Skipping fetch", req.Filename, fetcher.sharedVolumePath) - return 200, nil + return http.StatusOK, nil } tmpFile := req.Filename + ".tmp" @@ -239,7 +239,7 @@ func (fetcher *Fetcher) Fetch(req FetchRequest) (int, error) { if err != nil { e := fmt.Sprintf("Failed to download url %v: %v", req.Url, err) log.Printf(e) - return 400, errors.New(e) + return http.StatusBadRequest, errors.New(e) } } else { // get pkg @@ -247,7 +247,7 @@ func (fetcher *Fetcher) Fetch(req FetchRequest) (int, error) { if err != nil { e := fmt.Sprintf("Failed to get package: %v", err) log.Printf(e) - return 500, errors.New(e) + return http.StatusInternalServerError, errors.New(e) } var archive *fission.Archive @@ -261,7 +261,7 @@ func (fetcher *Fetcher) Fetch(req FetchRequest) (int, error) { if pkg.Status.BuildStatus != fission.BuildStatusSucceeded && pkg.Status.BuildStatus != fission.BuildStatusNone { e := fmt.Sprintf("Build status for the function's pkg : %s.%s is : %s, can't fetch deployment", pkg.Metadata.Name, pkg.Metadata.Namespace, pkg.Status.BuildStatus) log.Printf(e) - return 500, errors.New(e) + return http.StatusInternalServerError, errors.New(e) } archive = &pkg.Spec.Deployment } @@ -272,7 +272,7 @@ func (fetcher *Fetcher) Fetch(req FetchRequest) (int, error) { if err != nil { e := fmt.Sprintf("Failed to write file %v: %v", tmpPath, err) log.Printf(e) - return 500, errors.New(e) + return http.StatusInternalServerError, errors.New(e) } } else { // download and verify @@ -280,14 +280,14 @@ func (fetcher *Fetcher) Fetch(req FetchRequest) (int, error) { if err != nil { e := fmt.Sprintf("Failed to download url %v: %v", req.Url, err) log.Printf(e) - return 400, errors.New(e) + return http.StatusBadRequest, errors.New(e) } err = verifyChecksum(tmpPath, &archive.Checksum) if err != nil { e := fmt.Sprintf("Failed to verify checksum: %v", err) log.Printf(e) - return 400, errors.New(e) + return http.StatusBadRequest, errors.New(e) } } } @@ -299,7 +299,7 @@ func (fetcher *Fetcher) Fetch(req FetchRequest) (int, error) { err := fetcher.unarchive(tmpPath, tmpUnarchivePath) if err != nil { log.Println(err.Error()) - return 500, err + return http.StatusInternalServerError, err } tmpPath = tmpUnarchivePath } @@ -308,11 +308,11 @@ func (fetcher *Fetcher) Fetch(req FetchRequest) (int, error) { err := fetcher.rename(tmpPath, filepath.Join(fetcher.sharedVolumePath, req.Filename)) if err != nil { log.Println(err.Error()) - return 500, err + return http.StatusInternalServerError, err } log.Printf("Successfully placed at %v", filepath.Join(fetcher.sharedVolumePath, req.Filename)) - return 200, nil + return http.StatusOK, nil } // FetchSecretsAndCfgMaps fetches secrets and configmaps specified by user diff --git a/error.go b/error.go index ad40090e..0d11c4d1 100644 --- a/error.go +++ b/error.go @@ -32,19 +32,19 @@ func MakeError(code int, msg string) Error { } func MakeErrorFromHTTP(resp *http.Response) error { - if resp.StatusCode == 200 { + if resp.StatusCode == http.StatusOK { return nil } var errCode int switch resp.StatusCode { - case 400: + case http.StatusBadRequest: errCode = ErrorInvalidArgument - case 403: + case http.StatusForbidden: errCode = ErrorNotAuthorized - case 404: + case http.StatusNotFound: errCode = ErrorNotFound - case 409: + case http.StatusConflict: errCode = ErrorNameExists default: errCode = ErrorInternal @@ -64,15 +64,15 @@ func (err Error) HTTPStatus() int { var code int switch err.Code { case ErrorInvalidArgument: - code = 400 + code = http.StatusBadRequest case ErrorNotAuthorized: - code = 403 + code = http.StatusForbidden case ErrorNotFound: - code = 404 + code = http.StatusNotFound case ErrorNameExists: - code = 409 + code = http.StatusConflict default: - code = 500 + code = http.StatusInternalServerError } return code } @@ -85,7 +85,7 @@ func GetHTTPError(err error) (int, string) { code = fe.HTTPStatus() msg = fe.Message } else { - code = 500 + code = http.StatusInternalServerError msg = err.Error() } return code, msg diff --git a/executor/api.go b/executor/api.go index 7e91d3a4..8e10a6f5 100644 --- a/executor/api.go +++ b/executor/api.go @@ -34,7 +34,7 @@ import ( func (executor *Executor) getServiceForFunctionApi(w http.ResponseWriter, r *http.Request) { body, err := ioutil.ReadAll(r.Body) if err != nil { - http.Error(w, "Failed to read request", 500) + http.Error(w, "Failed to read request", http.StatusInternalServerError) return } @@ -42,7 +42,7 @@ func (executor *Executor) getServiceForFunctionApi(w http.ResponseWriter, r *htt m := metav1.ObjectMeta{} err = json.Unmarshal(body, &m) if err != nil { - http.Error(w, "Failed to parse request", 400) + http.Error(w, "Failed to parse request", http.StatusBadRequest) return } @@ -97,7 +97,7 @@ func (executor *Executor) getServiceForFunction(m *metav1.ObjectMeta) (string, e func (executor *Executor) tapService(w http.ResponseWriter, r *http.Request) { body, err := ioutil.ReadAll(r.Body) if err != nil { - http.Error(w, "Failed to read request", 500) + http.Error(w, "Failed to read request", http.StatusInternalServerError) return } svcName := string(body) @@ -106,7 +106,7 @@ func (executor *Executor) tapService(w http.ResponseWriter, r *http.Request) { err = executor.fsCache.TouchByAddress(svcHost) if err != nil { log.Printf("funcSvc tap error: %v", err) - http.Error(w, "Not found", 404) + http.Error(w, "Not found", http.StatusNotFound) return } w.WriteHeader(http.StatusOK) diff --git a/fission/migrate.go b/fission/migrate.go index 6b0e4234..d3ea8e94 100644 --- a/fission/migrate.go +++ b/fission/migrate.go @@ -101,7 +101,7 @@ func migrateDeleteTPR(c *cli.Context) error { checkErr(err, "delete tpr resources") defer resp.Body.Close() - if resp.StatusCode == 404 { + if resp.StatusCode == http.StatusNotFound { msg := fmt.Sprintf("Server %v isn't support deleteTpr method. Use --server to point at a 0.4.0+ Fission server.", server) fatal(msg) } diff --git a/fission/upgrade.go b/fission/upgrade.go index 4262f2e8..cfdcc7e0 100644 --- a/fission/upgrade.go +++ b/fission/upgrade.go @@ -249,7 +249,7 @@ func upgradeDumpState(c *cli.Context) error { // check v1 resp, err := http.Get(u + "/environments") checkErr(err, "reach fission server") - if resp.StatusCode == 404 { + if resp.StatusCode == http.StatusNotFound { msg := fmt.Sprintf("Server %v isn't a v1 Fission server. Use --server to point at a pre-0.2.x Fission server.", u) fatal(msg) } diff --git a/mqtrigger/messageQueue/asq_test.go b/mqtrigger/messageQueue/asq_test.go index f2312556..131bef9e 100644 --- a/mqtrigger/messageQueue/asq_test.go +++ b/mqtrigger/messageQueue/asq_test.go @@ -171,7 +171,7 @@ func TestAzureStorageQueuePoisonMessage(t *testing.T) { mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "", ContentType, FunctionName, MessageBody)), ).Return( &http.Response{ - StatusCode: 500, + StatusCode: http.StatusInternalServerError, Body: ioutil.NopCloser(strings.NewReader("server error")), }, nil, @@ -181,7 +181,7 @@ func TestAzureStorageQueuePoisonMessage(t *testing.T) { mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "1", ContentType, FunctionName, MessageBody)), ).Return( &http.Response{ - StatusCode: 404, + StatusCode: http.StatusNotFound, Body: ioutil.NopCloser(strings.NewReader("not found")), }, nil, @@ -191,7 +191,7 @@ func TestAzureStorageQueuePoisonMessage(t *testing.T) { mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "2", ContentType, FunctionName, MessageBody)), ).Return( &http.Response{ - StatusCode: 400, + StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(strings.NewReader("bad request")), }, nil, @@ -201,7 +201,7 @@ func TestAzureStorageQueuePoisonMessage(t *testing.T) { mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "3", ContentType, FunctionName, MessageBody)), ).Return( &http.Response{ - StatusCode: 403, + StatusCode: http.StatusForbidden, Body: ioutil.NopCloser(strings.NewReader("not authorized")), }, nil, @@ -338,7 +338,7 @@ func runAzureStorageQueueTest(t *testing.T, count int, output bool) { responseTopic = OutputQueueName } - // Mock a HTTP client that returns 200 with "output" for the body + // Mock a HTTP client that returns http.StatusOK with "output" for the body httpClient := new(azureHTTPClientMock) httpClient.bodyHandler = func(res *http.Response) { res.Body = ioutil.NopCloser(strings.NewReader(FunctionResponse)) @@ -346,7 +346,7 @@ func runAzureStorageQueueTest(t *testing.T, count int, output bool) { httpClient.On( "Do", mock.MatchedBy(httpRequestMatcher(t, QueueName, responseTopic, "", ContentType, FunctionName, MessageBody)), - ).Return(&http.Response{StatusCode: 200}, nil).Times(count) + ).Return(&http.Response{StatusCode: http.StatusOK}, nil).Times(count) // Mock a queue message with "input" as the message body message := new(azureMessageMock) diff --git a/storagesvc/storagesvc.go b/storagesvc/storagesvc.go index 6d166f9f..fb16af63 100644 --- a/storagesvc/storagesvc.go +++ b/storagesvc/storagesvc.go @@ -48,7 +48,7 @@ func (ss *StorageService) uploadHandler(w http.ResponseWriter, r *http.Request) r.ParseMultipartForm(0) file, handler, err := r.FormFile("uploadfile") if err != nil { - http.Error(w, "missing upload file", 400) + http.Error(w, "missing upload file", http.StatusBadRequest) return } defer file.Close() @@ -61,14 +61,14 @@ func (ss *StorageService) uploadHandler(w http.ResponseWriter, r *http.Request) fileSizeS, ok := r.Header["X-File-Size"] if !ok { log.Error("Missing X-File-Size") - http.Error(w, "missing X-File-Size header", 400) + http.Error(w, "missing X-File-Size header", http.StatusBadRequest) return } fileSize, err := strconv.Atoi(fileSizeS[0]) if err != nil { log.WithError(err).Errorf("Error parsing x-file-size: '%v'", fileSizeS) - http.Error(w, "missing or bad X-File-Size header", 400) + http.Error(w, "missing or bad X-File-Size header", http.StatusBadRequest) return } @@ -81,7 +81,7 @@ func (ss *StorageService) uploadHandler(w http.ResponseWriter, r *http.Request) id, err := ss.storageClient.putFile(file, int64(fileSize)) if err != nil { log.WithError(err).Error("Error saving uploaded file") - http.Error(w, "Error saving uploaded file", 500) + http.Error(w, "Error saving uploaded file", http.StatusInternalServerError) return } @@ -91,7 +91,7 @@ func (ss *StorageService) uploadHandler(w http.ResponseWriter, r *http.Request) } resp, err := json.Marshal(ur) if err != nil { - http.Error(w, "Error marshaling response", 500) + http.Error(w, "Error marshaling response", http.StatusInternalServerError) return } w.Write(resp) @@ -110,14 +110,14 @@ func (ss *StorageService) deleteHandler(w http.ResponseWriter, r *http.Request) // get id from request fileId, err := ss.getIdFromRequest(r) if err != nil { - http.Error(w, err.Error(), 400) + http.Error(w, err.Error(), http.StatusBadRequest) return } err = ss.storageClient.removeFileByID(fileId) if err != nil { msg := fmt.Sprintf("Error deleting item: %v", err) - http.Error(w, msg, 500) + http.Error(w, msg, http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) @@ -127,7 +127,7 @@ func (ss *StorageService) downloadHandler(w http.ResponseWriter, r *http.Request // get id from request fileId, err := ss.getIdFromRequest(r) if err != nil { - http.Error(w, err.Error(), 400) + http.Error(w, err.Error(), http.StatusBadRequest) return } @@ -137,13 +137,13 @@ func (ss *StorageService) downloadHandler(w http.ResponseWriter, r *http.Request if err != nil { log.WithError(err).Errorf("Error getting item id '%v'", fileId) if err == ErrNotFound { - http.Error(w, "Error retrieving item: not found", 404) + http.Error(w, "Error retrieving item: not found", http.StatusNotFound) } else if err == ErrRetrievingItem { - http.Error(w, "Error retrieving item", 400) + http.Error(w, "Error retrieving item", http.StatusBadRequest) } else if err == ErrOpeningItem { - http.Error(w, "Error opening item", 400) + http.Error(w, "Error opening item", http.StatusBadRequest) } else if err == ErrWritingFileIntoResponse { - http.Error(w, "Error writing response", 500) + http.Error(w, "Error writing response", http.StatusInternalServerError) } return }