From 5eadc4c0a8e5c51e72670591c4b7877e79c15e3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Pedersen?= Date: Thu, 12 Mar 2020 17:09:49 +0100 Subject: metrics: Fix --templateMetricsHints Also improve non-string comparisons. Fixes #7048 --- common/types/convert.go | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) (limited to 'common') diff --git a/common/types/convert.go b/common/types/convert.go index b55330757..24e01c273 100644 --- a/common/types/convert.go +++ b/common/types/convert.go @@ -13,7 +13,11 @@ package types -import "github.com/spf13/cast" +import ( + "html/template" + + "github.com/spf13/cast" +) // ToStringSlicePreserveString converts v to a string slice. // If v is a string, it will be wrapped in a string slice. @@ -26,3 +30,39 @@ func ToStringSlicePreserveString(v interface{}) []string { } return cast.ToStringSlice(v) } + +// TypeToString converts v to a string if it's a valid string type. +// Note that this will not try to convert numeric values etc., +// use ToString for that. +func TypeToString(v interface{}) (string, bool) { + switch s := v.(type) { + case string: + return s, true + case template.HTML: + return string(s), true + case template.CSS: + return string(s), true + case template.HTMLAttr: + return string(s), true + case template.JS: + return string(s), true + case template.JSStr: + return string(s), true + case template.URL: + return string(s), true + case template.Srcset: + return string(s), true + } + + return "", false +} + +// ToString converts v to a string. +func ToString(v interface{}) string { + if s, ok := TypeToString(v); ok { + return s + } + + return cast.ToString(v) + +} -- cgit v1.2.3