Skip to content

Commit

Permalink
Indicate HTTP status code by library const (#703)
Browse files Browse the repository at this point in the history
  • Loading branch information
xiekeyang authored and life1347 committed May 24, 2018
1 parent 8984e49 commit 940b9ad
Show file tree
Hide file tree
Showing 10 changed files with 49 additions and 49 deletions.
2 changes: 1 addition & 1 deletion controller/storagesvc.go
Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion controller/workflowApiProxy.go
Expand Up @@ -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
}

Expand Down
2 changes: 1 addition & 1 deletion environments/binary/server.go
Expand Up @@ -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
}
Expand Down
22 changes: 11 additions & 11 deletions environments/fetcher/fetcher.go
Expand Up @@ -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"
Expand All @@ -239,15 +239,15 @@ 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
pkg, err := fetcher.fissionClient.Packages(req.Package.Namespace).Get(req.Package.Name)
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
Expand All @@ -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
}
Expand All @@ -272,22 +272,22 @@ 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
err = downloadUrl(archive.URL, tmpPath)
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)
}
}
}
Expand All @@ -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
}
Expand All @@ -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
Expand Down
22 changes: 11 additions & 11 deletions error.go
Expand Up @@ -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
Expand All @@ -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
}
Expand All @@ -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
Expand Down
8 changes: 4 additions & 4 deletions executor/api.go
Expand Up @@ -34,15 +34,15 @@ 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
}

// get function metadata
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
}

Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion fission/migrate.go
Expand Up @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion fission/upgrade.go
Expand Up @@ -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)
}
Expand Down
12 changes: 6 additions & 6 deletions mqtrigger/messageQueue/asq_test.go
Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -338,15 +338,15 @@ 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))
}
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)
Expand Down
24 changes: 12 additions & 12 deletions storagesvc/storagesvc.go
Expand Up @@ -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()
Expand All @@ -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
}

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

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

Expand All @@ -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
}
Expand Down

0 comments on commit 940b9ad

Please sign in to comment.