diff options
author | Dave Henderson <dhenderson@gmail.com> | 2022-01-25 15:34:35 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-01-25 15:34:35 -0500 |
commit | 741b0502ee7cb0ecbd6dd0517c4f186729f52718 (patch) | |
tree | a8dbe6a5bbb0aa10dc9ab9c2f5111e017e559358 /internal | |
parent | 44e5e9e43f3583f04613bbbb1996e9b5a13a60ac (diff) | |
parent | 7ca5921a87c819f9848ccd7ec786aab0f896be72 (diff) |
Merge pull request #4545 from hairyhenderson/metrics-restrict-http-methods
metrics: Enforce smaller set of method labels
Diffstat (limited to 'internal')
-rw-r--r-- | internal/metrics/metrics.go | 39 | ||||
-rw-r--r-- | internal/metrics/metrics_test.go | 28 |
2 files changed, 67 insertions, 0 deletions
diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go new file mode 100644 index 0000000..7ae09b6 --- /dev/null +++ b/internal/metrics/metrics.go @@ -0,0 +1,39 @@ +package metrics + +import ( + "net/http" + "strconv" +) + +func SanitizeCode(s int) string { + switch s { + case 0, 200: + return "200" + default: + return strconv.Itoa(s) + } +} + +// Only support the list of "regular" HTTP methods, see +// https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods +var methodMap = map[string]string{ + "GET": http.MethodGet, "get": http.MethodGet, + "HEAD": http.MethodHead, "head": http.MethodHead, + "PUT": http.MethodPut, "put": http.MethodPut, + "POST": http.MethodPost, "post": http.MethodPost, + "DELETE": http.MethodDelete, "delete": http.MethodDelete, + "CONNECT": http.MethodConnect, "connect": http.MethodConnect, + "OPTIONS": http.MethodOptions, "options": http.MethodOptions, + "TRACE": http.MethodTrace, "trace": http.MethodTrace, + "PATCH": http.MethodPatch, "patch": http.MethodPatch, +} + +// SanitizeMethod sanitizes the method for use as a metric label. This helps +// prevent high cardinality on the method label. The name is always upper case. +func SanitizeMethod(m string) string { + if m, ok := methodMap[m]; ok { + return m + } + + return "OTHER" +} diff --git a/internal/metrics/metrics_test.go b/internal/metrics/metrics_test.go new file mode 100644 index 0000000..c3f5965 --- /dev/null +++ b/internal/metrics/metrics_test.go @@ -0,0 +1,28 @@ +package metrics + +import ( + "strings" + "testing" +) + +func TestSanitizeMethod(t *testing.T) { + tests := []struct { + method string + expected string + }{ + {method: "get", expected: "GET"}, + {method: "POST", expected: "POST"}, + {method: "OPTIONS", expected: "OPTIONS"}, + {method: "connect", expected: "CONNECT"}, + {method: "trace", expected: "TRACE"}, + {method: "UNKNOWN", expected: "OTHER"}, + {method: strings.Repeat("ohno", 9999), expected: "OTHER"}, + } + + for _, d := range tests { + actual := SanitizeMethod(d.method) + if actual != d.expected { + t.Errorf("Not same: expected %#v, but got %#v", d.expected, actual) + } + } +} |