diff --git a/docs/configuration/template_reference.md b/docs/configuration/template_reference.md index ff664af06..0da7f7ad6 100644 --- a/docs/configuration/template_reference.md +++ b/docs/configuration/template_reference.md @@ -70,6 +70,7 @@ versions. | title | string | string | [strings.Title](https://golang.org/pkg/strings/#Title), capitalises first character of each word.| | toUpper | string | string | [strings.ToUpper](https://golang.org/pkg/strings/#ToUpper), converts all characters to upper case.| | toLower | string | string | [strings.ToLower](https://golang.org/pkg/strings/#ToLower), converts all characters to lower case.| +| stripPort | string | string | [net.SplitHostPort](https://pkg.go.dev/net#SplitHostPort), splits string into host and port, then returns only host.| | match | pattern, text | boolean | [regexp.MatchString](https://golang.org/pkg/regexp/#MatchString) Tests for a unanchored regexp match. | | reReplaceAll | pattern, replacement, text | string | [Regexp.ReplaceAllString](https://golang.org/pkg/regexp/#Regexp.ReplaceAllString) Regexp substitution, unanchored. | | graphLink | expr | string | Returns path to graph view in the [expression browser](https://prometheus.io/docs/visualization/browser/) for the expression. | diff --git a/template/template.go b/template/template.go index e79de5ee6..fa20c0a47 100644 --- a/template/template.go +++ b/template/template.go @@ -19,6 +19,7 @@ import ( "fmt" html_template "html/template" "math" + "net" "net/url" "regexp" "sort" @@ -184,6 +185,13 @@ func NewTemplateExpander( sort.Stable(sorter) return v }, + "stripPort": func(hostPort string) string { + host, _, err := net.SplitHostPort(hostPort) + if err != nil { + return hostPort + } + return host + }, "humanize": func(i interface{}) (string, error) { v, err := convertToFloat(i) if err != nil { diff --git a/template/template_test.go b/template/template_test.go index f3af79712..ab39502ab 100644 --- a/template/template_test.go +++ b/template/template_test.go @@ -161,6 +161,41 @@ func TestTemplateExpansion(t *testing.T) { }, output: "a:11: b:21: ", }, + { + // Simple hostname. + text: "{{ \"foo.example.com\" | stripPort }}", + output: "foo.example.com", + }, + { + // Hostname with port. + text: "{{ \"foo.example.com:12345\" | stripPort }}", + output: "foo.example.com", + }, + { + // Simple IPv4 address. + text: "{{ \"192.0.2.1\" | stripPort }}", + output: "192.0.2.1", + }, + { + // IPv4 address with port. + text: "{{ \"192.0.2.1:12345\" | stripPort }}", + output: "192.0.2.1", + }, + { + // Simple IPv6 address. + text: "{{ \"2001:0DB8::1\" | stripPort }}", + output: "2001:0DB8::1", + }, + { + // IPv6 address with port. + text: "{{ \"[2001:0DB8::1]:12345\" | stripPort }}", + output: "2001:0DB8::1", + }, + { + // Value can't be split into host and port. + text: "{{ \"[2001:0DB8::1]::12345\" | stripPort }}", + output: "[2001:0DB8::1]::12345", + }, { // Missing value is no value for nil options. text: "{{ .Foo }}",