-
Notifications
You must be signed in to change notification settings - Fork 69
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Extract route name logic to a single middleware and use it everywhere #527
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
// SPDX-License-Identifier: AGPL-3.0-only | ||
|
||
package middleware | ||
|
||
import ( | ||
"context" | ||
"net/http" | ||
"regexp" | ||
"strings" | ||
|
||
"github.com/gorilla/mux" | ||
) | ||
|
||
// RouteInjector is a middleware that injects the route name for the current request into the request context. | ||
// | ||
// The route name can be retrieved by calling ExtractRouteName. | ||
type RouteInjector struct { | ||
RouteMatcher RouteMatcher | ||
} | ||
|
||
func (i RouteInjector) Wrap(handler http.Handler) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
routeName := getRouteName(i.RouteMatcher, r) | ||
handler.ServeHTTP(w, WithRouteName(r, routeName)) | ||
}) | ||
} | ||
|
||
// WithRouteName annotates r's context with the provided route name. | ||
// | ||
// The provided value must be suitable to use as a Prometheus label value. | ||
// | ||
// This method should generally only be used in tests: in production code, use RouteInjector instead. | ||
func WithRouteName(r *http.Request, routeName string) *http.Request { | ||
ctx := context.WithValue(r.Context(), contextKeyRouteName, routeName) | ||
return r.WithContext(ctx) | ||
} | ||
|
||
// ExtractRouteName returns the route name associated with this request that was previously injected by the | ||
// RouteInjector middleware or WithRouteName. | ||
// | ||
// This is the same route name used for trace and metric names, and is already suitable for use as a Prometheus label | ||
// value. | ||
func ExtractRouteName(ctx context.Context) string { | ||
routeName, ok := ctx.Value(contextKeyRouteName).(string) | ||
if !ok { | ||
return "" | ||
} | ||
|
||
return routeName | ||
} | ||
|
||
func getRouteName(routeMatcher RouteMatcher, r *http.Request) string { | ||
var routeMatch mux.RouteMatch | ||
if routeMatcher == nil || !routeMatcher.Match(r, &routeMatch) { | ||
return "" | ||
} | ||
|
||
if routeMatch.MatchErr == mux.ErrNotFound { | ||
return "notfound" | ||
} | ||
|
||
if routeMatch.Route == nil { | ||
return "" | ||
} | ||
|
||
if name := routeMatch.Route.GetName(); name != "" { | ||
return name | ||
} | ||
|
||
tmpl, err := routeMatch.Route.GetPathTemplate() | ||
if err == nil { | ||
return MakeLabelValue(tmpl) | ||
} | ||
|
||
return "" | ||
} | ||
|
||
var invalidChars = regexp.MustCompile(`[^a-zA-Z0-9]+`) | ||
|
||
// MakeLabelValue converts a Gorilla mux path to a string suitable for use in | ||
// a Prometheus label value. | ||
func MakeLabelValue(path string) string { | ||
// Convert non-alnums to underscores. | ||
result := invalidChars.ReplaceAllString(path, "_") | ||
|
||
// Trim leading and trailing underscores. | ||
result = strings.Trim(result, "_") | ||
|
||
// Make it all lowercase | ||
result = strings.ToLower(result) | ||
|
||
// Special case. | ||
if result == "" { | ||
result = "root" | ||
} | ||
return result | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
// SPDX-License-Identifier: AGPL-3.0-only | ||
// Provenance-includes-location: https://github.com/weaveworks/common/blob/main/middleware/instrument_test.go | ||
// Provenance-includes-license: Apache-2.0 | ||
// Provenance-includes-copyright: Weaveworks Ltd. | ||
|
||
package middleware | ||
|
||
import ( | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
|
||
"github.com/gorilla/mux" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestRouteInjector(t *testing.T) { | ||
testCases := map[string]string{ | ||
"/": "root", | ||
"/foo/bar/blah": "foo_bar_blah", | ||
"/templated/name-1/thing": "templated_name_thing", | ||
"/named": "my-named-route", | ||
"/does-not-exist": "notfound", | ||
} | ||
|
||
for url, expectedRouteName := range testCases { | ||
t.Run(url, func(t *testing.T) { | ||
actualRouteName := "" | ||
|
||
handler := func(_ http.ResponseWriter, r *http.Request) { | ||
actualRouteName = ExtractRouteName(r.Context()) | ||
} | ||
|
||
router := mux.NewRouter() | ||
router.HandleFunc("/", handler) | ||
router.HandleFunc("/foo/bar/blah", handler) | ||
router.HandleFunc("/templated/{name}/thing", handler) | ||
router.HandleFunc("/named", handler).Name("my-named-route") | ||
router.NotFoundHandler = http.HandlerFunc(handler) | ||
|
||
endpoint := RouteInjector{router}.Wrap(router) | ||
endpoint.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, url, nil)) | ||
|
||
require.Equal(t, expectedRouteName, actualRouteName) | ||
}) | ||
} | ||
|
||
} | ||
|
||
func TestMakeLabelValue(t *testing.T) { | ||
for input, want := range map[string]string{ | ||
"/": "root", // special case | ||
"//": "root", // unintended consequence of special case | ||
"a": "a", | ||
"/foo": "foo", | ||
"foo/": "foo", | ||
"/foo/": "foo", | ||
"/foo/bar": "foo_bar", | ||
"foo/bar/": "foo_bar", | ||
"/foo/bar/": "foo_bar", | ||
"/foo/{orgName}/Bar": "foo_orgname_bar", | ||
"/foo/{org_name}/Bar": "foo_org_name_bar", | ||
"/foo/{org__name}/Bar": "foo_org_name_bar", | ||
"/foo/{org___name}/_Bar": "foo_org_name_bar", | ||
"/foo.bar/baz.qux/": "foo_bar_baz_qux", | ||
} { | ||
if have := MakeLabelValue(input); want != have { | ||
t.Errorf("%q: want %q, have %q", input, want, have) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: move to route_injector.go?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wanted to keep all the
contextKey
values in one place, as otherwise there's a risk that we define twocontextKey
s with the same value (eg. twocontextKey
s with value3
).