Indicate HTTP status code by library const (#703)

This commit is contained in:
xiekeyang
2018-05-24 19:10:45 +08:00
committed by Ta-Ching Chen
parent 8984e4916e
commit 940b9adabd
10 changed files with 49 additions and 49 deletions
+1 -1
View File
@@ -30,7 +30,7 @@ func (api *API) StorageServiceProxy(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
msg := fmt.Sprintf("Error parsing url %v: %v", u, err) msg := fmt.Sprintf("Error parsing url %v: %v", u, err)
log.Println(msg) log.Println(msg)
http.Error(w, msg, 500) http.Error(w, msg, http.StatusInternalServerError)
return return
} }
director := func(req *http.Request) { director := func(req *http.Request) {
+1 -1
View File
@@ -13,7 +13,7 @@ func (api *API) WorkflowApiserverProxy(w http.ResponseWriter, r *http.Request) {
ssUrl, err := url.Parse(u) ssUrl, err := url.Parse(u)
if err != nil { if err != nil {
msg := fmt.Sprintf("Error parsing url %v: %v", u, err) msg := fmt.Sprintf("Error parsing url %v: %v", u, err)
http.Error(w, msg, 500) http.Error(w, msg, http.StatusInternalServerError)
return return
} }
+1 -1
View File
@@ -46,7 +46,7 @@ type (
func (bs *BinaryServer) SpecializeHandler(w http.ResponseWriter, r *http.Request) { func (bs *BinaryServer) SpecializeHandler(w http.ResponseWriter, r *http.Request) {
if specialized { if specialized {
w.WriteHeader(400) w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Not a generic container")) w.Write([]byte("Not a generic container"))
return return
} }
+11 -11
View File
@@ -221,13 +221,13 @@ func (fetcher *Fetcher) Fetch(req FetchRequest) (int, error) {
if len(req.Filename) == 0 { if len(req.Filename) == 0 {
e := fmt.Sprintf("Fetch request received for an empty file name, request: %v", req) e := fmt.Sprintf("Fetch request received for an empty file name, request: %v", req)
log.Printf(e) log.Printf(e)
return 400, errors.New(e) return http.StatusBadRequest, errors.New(e)
} }
// verify first if the file already exists. // verify first if the file already exists.
if _, err := os.Stat(filepath.Join(fetcher.sharedVolumePath, req.Filename)); err == nil { 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) 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" tmpFile := req.Filename + ".tmp"
@@ -239,7 +239,7 @@ func (fetcher *Fetcher) Fetch(req FetchRequest) (int, error) {
if err != nil { if err != nil {
e := fmt.Sprintf("Failed to download url %v: %v", req.Url, err) e := fmt.Sprintf("Failed to download url %v: %v", req.Url, err)
log.Printf(e) log.Printf(e)
return 400, errors.New(e) return http.StatusBadRequest, errors.New(e)
} }
} else { } else {
// get pkg // get pkg
@@ -247,7 +247,7 @@ func (fetcher *Fetcher) Fetch(req FetchRequest) (int, error) {
if err != nil { if err != nil {
e := fmt.Sprintf("Failed to get package: %v", err) e := fmt.Sprintf("Failed to get package: %v", err)
log.Printf(e) log.Printf(e)
return 500, errors.New(e) return http.StatusInternalServerError, errors.New(e)
} }
var archive *fission.Archive 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 { 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) 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) log.Printf(e)
return 500, errors.New(e) return http.StatusInternalServerError, errors.New(e)
} }
archive = &pkg.Spec.Deployment archive = &pkg.Spec.Deployment
} }
@@ -272,7 +272,7 @@ func (fetcher *Fetcher) Fetch(req FetchRequest) (int, error) {
if err != nil { if err != nil {
e := fmt.Sprintf("Failed to write file %v: %v", tmpPath, err) e := fmt.Sprintf("Failed to write file %v: %v", tmpPath, err)
log.Printf(e) log.Printf(e)
return 500, errors.New(e) return http.StatusInternalServerError, errors.New(e)
} }
} else { } else {
// download and verify // download and verify
@@ -280,14 +280,14 @@ func (fetcher *Fetcher) Fetch(req FetchRequest) (int, error) {
if err != nil { if err != nil {
e := fmt.Sprintf("Failed to download url %v: %v", req.Url, err) e := fmt.Sprintf("Failed to download url %v: %v", req.Url, err)
log.Printf(e) log.Printf(e)
return 400, errors.New(e) return http.StatusBadRequest, errors.New(e)
} }
err = verifyChecksum(tmpPath, &archive.Checksum) err = verifyChecksum(tmpPath, &archive.Checksum)
if err != nil { if err != nil {
e := fmt.Sprintf("Failed to verify checksum: %v", err) e := fmt.Sprintf("Failed to verify checksum: %v", err)
log.Printf(e) 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) err := fetcher.unarchive(tmpPath, tmpUnarchivePath)
if err != nil { if err != nil {
log.Println(err.Error()) log.Println(err.Error())
return 500, err return http.StatusInternalServerError, err
} }
tmpPath = tmpUnarchivePath tmpPath = tmpUnarchivePath
} }
@@ -308,11 +308,11 @@ func (fetcher *Fetcher) Fetch(req FetchRequest) (int, error) {
err := fetcher.rename(tmpPath, filepath.Join(fetcher.sharedVolumePath, req.Filename)) err := fetcher.rename(tmpPath, filepath.Join(fetcher.sharedVolumePath, req.Filename))
if err != nil { if err != nil {
log.Println(err.Error()) log.Println(err.Error())
return 500, err return http.StatusInternalServerError, err
} }
log.Printf("Successfully placed at %v", filepath.Join(fetcher.sharedVolumePath, req.Filename)) 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 // FetchSecretsAndCfgMaps fetches secrets and configmaps specified by user
+11 -11
View File
@@ -32,19 +32,19 @@ func MakeError(code int, msg string) Error {
} }
func MakeErrorFromHTTP(resp *http.Response) error { func MakeErrorFromHTTP(resp *http.Response) error {
if resp.StatusCode == 200 { if resp.StatusCode == http.StatusOK {
return nil return nil
} }
var errCode int var errCode int
switch resp.StatusCode { switch resp.StatusCode {
case 400: case http.StatusBadRequest:
errCode = ErrorInvalidArgument errCode = ErrorInvalidArgument
case 403: case http.StatusForbidden:
errCode = ErrorNotAuthorized errCode = ErrorNotAuthorized
case 404: case http.StatusNotFound:
errCode = ErrorNotFound errCode = ErrorNotFound
case 409: case http.StatusConflict:
errCode = ErrorNameExists errCode = ErrorNameExists
default: default:
errCode = ErrorInternal errCode = ErrorInternal
@@ -64,15 +64,15 @@ func (err Error) HTTPStatus() int {
var code int var code int
switch err.Code { switch err.Code {
case ErrorInvalidArgument: case ErrorInvalidArgument:
code = 400 code = http.StatusBadRequest
case ErrorNotAuthorized: case ErrorNotAuthorized:
code = 403 code = http.StatusForbidden
case ErrorNotFound: case ErrorNotFound:
code = 404 code = http.StatusNotFound
case ErrorNameExists: case ErrorNameExists:
code = 409 code = http.StatusConflict
default: default:
code = 500 code = http.StatusInternalServerError
} }
return code return code
} }
@@ -85,7 +85,7 @@ func GetHTTPError(err error) (int, string) {
code = fe.HTTPStatus() code = fe.HTTPStatus()
msg = fe.Message msg = fe.Message
} else { } else {
code = 500 code = http.StatusInternalServerError
msg = err.Error() msg = err.Error()
} }
return code, msg return code, msg
+4 -4
View File
@@ -34,7 +34,7 @@ import (
func (executor *Executor) getServiceForFunctionApi(w http.ResponseWriter, r *http.Request) { func (executor *Executor) getServiceForFunctionApi(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body) body, err := ioutil.ReadAll(r.Body)
if err != nil { if err != nil {
http.Error(w, "Failed to read request", 500) http.Error(w, "Failed to read request", http.StatusInternalServerError)
return return
} }
@@ -42,7 +42,7 @@ func (executor *Executor) getServiceForFunctionApi(w http.ResponseWriter, r *htt
m := metav1.ObjectMeta{} m := metav1.ObjectMeta{}
err = json.Unmarshal(body, &m) err = json.Unmarshal(body, &m)
if err != nil { if err != nil {
http.Error(w, "Failed to parse request", 400) http.Error(w, "Failed to parse request", http.StatusBadRequest)
return return
} }
@@ -97,7 +97,7 @@ func (executor *Executor) getServiceForFunction(m *metav1.ObjectMeta) (string, e
func (executor *Executor) tapService(w http.ResponseWriter, r *http.Request) { func (executor *Executor) tapService(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body) body, err := ioutil.ReadAll(r.Body)
if err != nil { if err != nil {
http.Error(w, "Failed to read request", 500) http.Error(w, "Failed to read request", http.StatusInternalServerError)
return return
} }
svcName := string(body) svcName := string(body)
@@ -106,7 +106,7 @@ func (executor *Executor) tapService(w http.ResponseWriter, r *http.Request) {
err = executor.fsCache.TouchByAddress(svcHost) err = executor.fsCache.TouchByAddress(svcHost)
if err != nil { if err != nil {
log.Printf("funcSvc tap error: %v", err) log.Printf("funcSvc tap error: %v", err)
http.Error(w, "Not found", 404) http.Error(w, "Not found", http.StatusNotFound)
return return
} }
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
+1 -1
View File
@@ -101,7 +101,7 @@ func migrateDeleteTPR(c *cli.Context) error {
checkErr(err, "delete tpr resources") checkErr(err, "delete tpr resources")
defer resp.Body.Close() 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) msg := fmt.Sprintf("Server %v isn't support deleteTpr method. Use --server to point at a 0.4.0+ Fission server.", server)
fatal(msg) fatal(msg)
} }
+1 -1
View File
@@ -249,7 +249,7 @@ func upgradeDumpState(c *cli.Context) error {
// check v1 // check v1
resp, err := http.Get(u + "/environments") resp, err := http.Get(u + "/environments")
checkErr(err, "reach fission server") 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) 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) fatal(msg)
} }
+6 -6
View File
@@ -171,7 +171,7 @@ func TestAzureStorageQueuePoisonMessage(t *testing.T) {
mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "", ContentType, FunctionName, MessageBody)), mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "", ContentType, FunctionName, MessageBody)),
).Return( ).Return(
&http.Response{ &http.Response{
StatusCode: 500, StatusCode: http.StatusInternalServerError,
Body: ioutil.NopCloser(strings.NewReader("server error")), Body: ioutil.NopCloser(strings.NewReader("server error")),
}, },
nil, nil,
@@ -181,7 +181,7 @@ func TestAzureStorageQueuePoisonMessage(t *testing.T) {
mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "1", ContentType, FunctionName, MessageBody)), mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "1", ContentType, FunctionName, MessageBody)),
).Return( ).Return(
&http.Response{ &http.Response{
StatusCode: 404, StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(strings.NewReader("not found")), Body: ioutil.NopCloser(strings.NewReader("not found")),
}, },
nil, nil,
@@ -191,7 +191,7 @@ func TestAzureStorageQueuePoisonMessage(t *testing.T) {
mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "2", ContentType, FunctionName, MessageBody)), mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "2", ContentType, FunctionName, MessageBody)),
).Return( ).Return(
&http.Response{ &http.Response{
StatusCode: 400, StatusCode: http.StatusBadRequest,
Body: ioutil.NopCloser(strings.NewReader("bad request")), Body: ioutil.NopCloser(strings.NewReader("bad request")),
}, },
nil, nil,
@@ -201,7 +201,7 @@ func TestAzureStorageQueuePoisonMessage(t *testing.T) {
mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "3", ContentType, FunctionName, MessageBody)), mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "3", ContentType, FunctionName, MessageBody)),
).Return( ).Return(
&http.Response{ &http.Response{
StatusCode: 403, StatusCode: http.StatusForbidden,
Body: ioutil.NopCloser(strings.NewReader("not authorized")), Body: ioutil.NopCloser(strings.NewReader("not authorized")),
}, },
nil, nil,
@@ -338,7 +338,7 @@ func runAzureStorageQueueTest(t *testing.T, count int, output bool) {
responseTopic = OutputQueueName 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 := new(azureHTTPClientMock)
httpClient.bodyHandler = func(res *http.Response) { httpClient.bodyHandler = func(res *http.Response) {
res.Body = ioutil.NopCloser(strings.NewReader(FunctionResponse)) res.Body = ioutil.NopCloser(strings.NewReader(FunctionResponse))
@@ -346,7 +346,7 @@ func runAzureStorageQueueTest(t *testing.T, count int, output bool) {
httpClient.On( httpClient.On(
"Do", "Do",
mock.MatchedBy(httpRequestMatcher(t, QueueName, responseTopic, "", ContentType, FunctionName, MessageBody)), 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 // Mock a queue message with "input" as the message body
message := new(azureMessageMock) message := new(azureMessageMock)
+12 -12
View File
@@ -48,7 +48,7 @@ func (ss *StorageService) uploadHandler(w http.ResponseWriter, r *http.Request)
r.ParseMultipartForm(0) r.ParseMultipartForm(0)
file, handler, err := r.FormFile("uploadfile") file, handler, err := r.FormFile("uploadfile")
if err != nil { if err != nil {
http.Error(w, "missing upload file", 400) http.Error(w, "missing upload file", http.StatusBadRequest)
return return
} }
defer file.Close() defer file.Close()
@@ -61,14 +61,14 @@ func (ss *StorageService) uploadHandler(w http.ResponseWriter, r *http.Request)
fileSizeS, ok := r.Header["X-File-Size"] fileSizeS, ok := r.Header["X-File-Size"]
if !ok { if !ok {
log.Error("Missing X-File-Size") 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 return
} }
fileSize, err := strconv.Atoi(fileSizeS[0]) fileSize, err := strconv.Atoi(fileSizeS[0])
if err != nil { if err != nil {
log.WithError(err).Errorf("Error parsing x-file-size: '%v'", fileSizeS) 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 return
} }
@@ -81,7 +81,7 @@ func (ss *StorageService) uploadHandler(w http.ResponseWriter, r *http.Request)
id, err := ss.storageClient.putFile(file, int64(fileSize)) id, err := ss.storageClient.putFile(file, int64(fileSize))
if err != nil { if err != nil {
log.WithError(err).Error("Error saving uploaded file") 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 return
} }
@@ -91,7 +91,7 @@ func (ss *StorageService) uploadHandler(w http.ResponseWriter, r *http.Request)
} }
resp, err := json.Marshal(ur) resp, err := json.Marshal(ur)
if err != nil { if err != nil {
http.Error(w, "Error marshaling response", 500) http.Error(w, "Error marshaling response", http.StatusInternalServerError)
return return
} }
w.Write(resp) w.Write(resp)
@@ -110,14 +110,14 @@ func (ss *StorageService) deleteHandler(w http.ResponseWriter, r *http.Request)
// get id from request // get id from request
fileId, err := ss.getIdFromRequest(r) fileId, err := ss.getIdFromRequest(r)
if err != nil { if err != nil {
http.Error(w, err.Error(), 400) http.Error(w, err.Error(), http.StatusBadRequest)
return return
} }
err = ss.storageClient.removeFileByID(fileId) err = ss.storageClient.removeFileByID(fileId)
if err != nil { if err != nil {
msg := fmt.Sprintf("Error deleting item: %v", err) msg := fmt.Sprintf("Error deleting item: %v", err)
http.Error(w, msg, 500) http.Error(w, msg, http.StatusInternalServerError)
return return
} }
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
@@ -127,7 +127,7 @@ func (ss *StorageService) downloadHandler(w http.ResponseWriter, r *http.Request
// get id from request // get id from request
fileId, err := ss.getIdFromRequest(r) fileId, err := ss.getIdFromRequest(r)
if err != nil { if err != nil {
http.Error(w, err.Error(), 400) http.Error(w, err.Error(), http.StatusBadRequest)
return return
} }
@@ -137,13 +137,13 @@ func (ss *StorageService) downloadHandler(w http.ResponseWriter, r *http.Request
if err != nil { if err != nil {
log.WithError(err).Errorf("Error getting item id '%v'", fileId) log.WithError(err).Errorf("Error getting item id '%v'", fileId)
if err == ErrNotFound { 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 { } else if err == ErrRetrievingItem {
http.Error(w, "Error retrieving item", 400) http.Error(w, "Error retrieving item", http.StatusBadRequest)
} else if err == ErrOpeningItem { } else if err == ErrOpeningItem {
http.Error(w, "Error opening item", 400) http.Error(w, "Error opening item", http.StatusBadRequest)
} else if err == ErrWritingFileIntoResponse { } else if err == ErrWritingFileIntoResponse {
http.Error(w, "Error writing response", 500) http.Error(w, "Error writing response", http.StatusInternalServerError)
} }
return return
} }