1
0
Fork 0
upl/helpers.go

61 lines
1.8 KiB
Go
Raw Normal View History

2021-05-22 13:12:14 +08:00
package main
import (
"errors"
"net/http"
)
var errNotFound = errors.New("not found")
var errBadRequest = errors.New("bad request")
2021-05-22 22:24:28 +08:00
var errInternalServerError = errors.New("internal server error")
var errUnauthorized = errors.New("unauthorized")
var errForbidden = errors.New("forbidden")
2021-07-03 20:25:08 +08:00
var errConflict = errors.New("conflict")
2021-05-22 13:12:14 +08:00
2021-05-23 00:46:15 +08:00
func errorResponseStatus(w http.ResponseWriter, req *http.Request, err error) {
2021-05-22 13:12:14 +08:00
errorStatus := http.StatusInternalServerError
if errors.Is(err, errNotFound) {
errorStatus = http.StatusNotFound
} else if errors.Is(err, errBadRequest) {
errorStatus = http.StatusBadRequest
2021-05-22 22:24:28 +08:00
} else if errors.Is(err, errInternalServerError) {
errorStatus = http.StatusInternalServerError
} else if errors.Is(err, errUnauthorized) {
errorStatus = http.StatusUnauthorized
} else if errors.Is(err, errForbidden) {
errorStatus = http.StatusForbidden
2021-07-03 20:25:08 +08:00
} else if errors.Is(err, errConflict) {
errorStatus = http.StatusConflict
2021-05-22 13:12:14 +08:00
}
w.WriteHeader(errorStatus)
}
2021-05-23 00:46:15 +08:00
// errorResponse prints the error message in the response body.
//
// Do not use this function when the error message might contain sensitive
// information.
2021-05-23 00:46:15 +08:00
func errorResponse(w http.ResponseWriter, req *http.Request, err error) {
errorResponseStatus(w, req, err)
w.Write([]byte(err.Error()))
}
// responseToError converts a HTTP status code to an error
func responseToError(resp *http.Response) error {
if resp.StatusCode == http.StatusNotFound {
return errNotFound
} else if resp.StatusCode == http.StatusBadRequest {
return errBadRequest
} else if resp.StatusCode == http.StatusInternalServerError {
return errInternalServerError
} else if resp.StatusCode == http.StatusUnauthorized {
return errUnauthorized
} else if resp.StatusCode == http.StatusForbidden {
return errForbidden
2021-07-03 20:25:08 +08:00
} else if resp.StatusCode == http.StatusConflict {
return errConflict
}
return nil
}