Skip to content

Commit 3f692d7

Browse files
committed
Check RawPath before checking Path on Prometheus middleware
1 parent 1b66cfb commit 3f692d7

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

echoprometheus/prometheus.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,15 @@ func (conf MiddlewareConfig) ToMiddleware() (echo.MiddlewareFunc, error) {
249249
if url == "" {
250250
// as of Echo v4.10.1 path is empty for 404 cases (when router did not find any matching routes)
251251
// in this case we use actual path from request to have some distinction in Prometheus
252-
url = c.Request().URL.Path
252+
253+
// Referencing Go documentation (https://cs.opensource.google/go/go/+/refs/tags/go1.21.3:src/net/url/url.go;l=357-359):
254+
// We first check the RawPath, which is the original, escaped form. It's important to check RawPath first because
255+
// it preserves the original encoding of the URL. Using Path (decoded form) can sometimes result invalid UTF-8 characters.
256+
if c.Request().URL.RawPath != "" {
257+
url = c.Request().URL.RawPath
258+
} else {
259+
url = c.Request().URL.Path
260+
}
253261
}
254262

255263
status := c.Response().Status

echoprometheus/prometheus_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,3 +330,22 @@ func unregisterDefaults(subsystem string) {
330330
Help: "The HTTP request sizes in bytes.",
331331
})
332332
}
333+
334+
func TestToMiddleware_RawPath(t *testing.T) {
335+
middleware, err := MiddlewareConfig{}.ToMiddleware()
336+
assert.NoError(t, err)
337+
338+
next := echo.HandlerFunc(func(c echo.Context) error {
339+
return nil
340+
})
341+
342+
handler := middleware(next)
343+
344+
e := echo.New()
345+
346+
req := httptest.NewRequest(http.MethodGet, "/v1/%a1", http.NoBody)
347+
rec := httptest.NewRecorder()
348+
echoContext := e.NewContext(req, rec)
349+
350+
assert.NoError(t, handler(echoContext))
351+
}

0 commit comments

Comments
 (0)