Skip to content

Commit

Permalink
api/server/httputils: ensure consistent status code
Browse files Browse the repository at this point in the history
Error code resolution is powered by string matching. Not the greatest
thing in the world and I hope no one is proud of this code, but it
works. However, because a map is used, the iteration order of the map is
random, such that if an error matches two of the snippets, it may return
a different error code depending on the seed of the hashmap. This change
converts it to use a slice instead.

Signed-off-by: Stephen J Day <[email protected]>
  • Loading branch information
stevvooe committed Nov 17, 2016
1 parent f7b27de commit 3484e02
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions api/server/httputils/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,20 +49,23 @@ func GetHTTPErrorStatusCode(err error) int {
// If we need to differentiate between different possible error types,
// we should create appropriate error types that implement the httpStatusError interface.
errStr := strings.ToLower(errMsg)
for keyword, status := range map[string]int{
"not found": http.StatusNotFound,
"no such": http.StatusNotFound,
"bad parameter": http.StatusBadRequest,
"no command": http.StatusBadRequest,
"conflict": http.StatusConflict,
"impossible": http.StatusNotAcceptable,
"wrong login/password": http.StatusUnauthorized,
"unauthorized": http.StatusUnauthorized,
"hasn't been activated": http.StatusForbidden,
"this node": http.StatusNotAcceptable,
for _, status := range []struct {
keyword string
code int
}{
{"not found", http.StatusNotFound},
{"no such", http.StatusNotFound},
{"bad parameter", http.StatusBadRequest},
{"no command", http.StatusBadRequest},
{"conflict", http.StatusConflict},
{"impossible", http.StatusNotAcceptable},
{"wrong login/password", http.StatusUnauthorized},
{"unauthorized", http.StatusUnauthorized},
{"hasn't been activated", http.StatusForbidden},
{"this node", http.StatusNotAcceptable},
} {
if strings.Contains(errStr, keyword) {
statusCode = status
if strings.Contains(errStr, status.keyword) {
statusCode = status.code
break
}
}
Expand Down

0 comments on commit 3484e02

Please sign in to comment.