Browse code

api/server/httputils: ensure consistent status code

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 <stephen.day@docker.com>

Stephen J Day authored on 2016/11/17 11:58:55
Showing 1 changed files
... ...
@@ -49,20 +49,23 @@ func GetHTTPErrorStatusCode(err error) int {
49 49
 		// If we need to differentiate between different possible error types,
50 50
 		// we should create appropriate error types that implement the httpStatusError interface.
51 51
 		errStr := strings.ToLower(errMsg)
52
-		for keyword, status := range map[string]int{
53
-			"not found":             http.StatusNotFound,
54
-			"no such":               http.StatusNotFound,
55
-			"bad parameter":         http.StatusBadRequest,
56
-			"no command":            http.StatusBadRequest,
57
-			"conflict":              http.StatusConflict,
58
-			"impossible":            http.StatusNotAcceptable,
59
-			"wrong login/password":  http.StatusUnauthorized,
60
-			"unauthorized":          http.StatusUnauthorized,
61
-			"hasn't been activated": http.StatusForbidden,
62
-			"this node":             http.StatusNotAcceptable,
52
+		for _, status := range []struct {
53
+			keyword string
54
+			code    int
55
+		}{
56
+			{"not found", http.StatusNotFound},
57
+			{"no such", http.StatusNotFound},
58
+			{"bad parameter", http.StatusBadRequest},
59
+			{"no command", http.StatusBadRequest},
60
+			{"conflict", http.StatusConflict},
61
+			{"impossible", http.StatusNotAcceptable},
62
+			{"wrong login/password", http.StatusUnauthorized},
63
+			{"unauthorized", http.StatusUnauthorized},
64
+			{"hasn't been activated", http.StatusForbidden},
65
+			{"this node", http.StatusNotAcceptable},
63 66
 		} {
64
-			if strings.Contains(errStr, keyword) {
65
-				statusCode = status
67
+			if strings.Contains(errStr, status.keyword) {
68
+				statusCode = status.code
66 69
 				break
67 70
 			}
68 71
 		}