From fb42972c057364a1dc99dfb528554e7a94415be7 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Fri, 1 Mar 2024 18:16:19 +0800 Subject: Rename Str2html to SanitizeHTML and clarify its behavior (#29516) Str2html was abused a lot. So use a proper name for it: SanitizeHTML And add some tests to show its behavior. --- modules/templates/helper.go | 24 ++++++++++++------------ modules/templates/helper_test.go | 5 +++++ 2 files changed, 17 insertions(+), 12 deletions(-) (limited to 'modules') diff --git a/modules/templates/helper.go b/modules/templates/helper.go index 0f39767586..1487fce69d 100644 --- a/modules/templates/helper.go +++ b/modules/templates/helper.go @@ -33,16 +33,16 @@ func NewFuncMap() template.FuncMap { // ----------------------------------------------------------------- // html/template related functions - "dict": dict, // it's lowercase because this name has been widely used. Our other functions should have uppercase names. - "Eval": Eval, - "SafeHTML": SafeHTML, - "HTMLFormat": HTMLFormat, - "HTMLEscape": HTMLEscape, - "QueryEscape": url.QueryEscape, - "JSEscape": JSEscapeSafe, - "Str2html": Str2html, // TODO: rename it to SanitizeHTML - "URLJoin": util.URLJoin, - "DotEscape": DotEscape, + "dict": dict, // it's lowercase because this name has been widely used. Our other functions should have uppercase names. + "Eval": Eval, + "SafeHTML": SafeHTML, + "HTMLFormat": HTMLFormat, + "HTMLEscape": HTMLEscape, + "QueryEscape": url.QueryEscape, + "JSEscape": JSEscapeSafe, + "SanitizeHTML": SanitizeHTML, + "URLJoin": util.URLJoin, + "DotEscape": DotEscape, "PathEscape": url.PathEscape, "PathEscapeSegments": util.PathEscapeSegments, @@ -207,8 +207,8 @@ func SafeHTML(s any) template.HTML { panic(fmt.Sprintf("unexpected type %T", s)) } -// Str2html sanitizes the input by pre-defined markdown rules -func Str2html(s any) template.HTML { +// SanitizeHTML sanitizes the input by pre-defined markdown rules +func SanitizeHTML(s any) template.HTML { switch v := s.(type) { case string: return template.HTML(markup.Sanitize(v)) diff --git a/modules/templates/helper_test.go b/modules/templates/helper_test.go index 8f5d633d4f..3365278ac2 100644 --- a/modules/templates/helper_test.go +++ b/modules/templates/helper_test.go @@ -61,3 +61,8 @@ func TestJSEscapeSafe(t *testing.T) { func TestHTMLFormat(t *testing.T) { assert.Equal(t, template.HTML("< < 1"), HTMLFormat("%s %s %d", "<", template.HTML("<"), 1)) } + +func TestSanitizeHTML(t *testing.T) { + assert.Equal(t, template.HTML(`link xss
inline
`), SanitizeHTML(`link xss
inline
`)) + assert.Equal(t, template.HTML(`link xss
inline
`), SanitizeHTML(template.HTML(`link xss
inline
`))) +} -- cgit v1.2.3