Add urldecode and safeURL template functions
This PR adds two new template functions to address double-encoding issues when working with URLs in Alertmanager templates, as described in issue #4710.
Changes
-
urldecode: Decodes URL-encoded strings using
url.QueryUnescape. Useful for extracting and manipulating query parameters from URLs (e.g., extracting expr from Prometheus GeneratorURL for Grafana Explore links). -
safeURL: Marks a URL string as safe to prevent double-encoding by html/template. This provides an alias for
safeUrlwith capital URL naming for consistency.
Use Cases
These functions solve the problem where .GeneratorURL from Prometheus is already URL-encoded, but html/template escapes it again, resulting in double-encoded output (e.g., %2520 instead of %20).
Example Usage
{{ $expr := ( reReplaceAll ".*expr=([^&]+).*" "$1" (urldecode .GeneratorURL) ) }}
<a href="https://grafana.com/explore?expr={{ $expr }}">See in Grafana</a>
Or for trusted URLs:
<a href="{{ .GeneratorURL | safeURL }}">See in Prometheus</a>
Testing
- Added unit tests for both
urldecodeandsafeURLfunctions - Tests verify correct URL decoding and prevention of double-encoding
Fixes #4710