CodexBloom - Programming Q&A Platform

Using Go's built-in template package leads to incorrect HTML escaping in custom functions

👀 Views: 69 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
go html templates Go

I'm updating my dependencies and I'm wondering if anyone has experience with I'm running into a question when trying to use Go's `html/template` package with custom functions. I have a custom function that formats a string, but it appears that the output is not being escaped properly, which could lead to XSS vulnerabilities. For example, I'm trying to create a simple template that formats a date and returns it as a string. Here's my relevant code: ```go package main import ( "html/template" "os" "time" ) func formatDate(t time.Time) string { return t.Format("January 2, 2006") } func main() { funcMap := template.FuncMap{ "formatDate": formatDate, } tmpl, err := template.New("example").Funcs(funcMap).Parse(`{{ . | formatDate }}`) if err != nil { panic(err) } currentDate := time.Now() err = tmpl.Execute(os.Stdout, currentDate) if err != nil { panic(err) } } ``` When I execute this code, the output is as expected, but I noticed that if I pass a string containing HTML tags, it gets rendered incorrectly. For example, if I replace `currentDate` with a string like `<b>bold</b>`, the output is `<b>bold</b>`, which is not escaped. I was expecting the output to be `&lt;b&gt;bold&lt;/b&gt;`. I tried adding the `template.HTML` type in the function return, but it doesn't seem to resolve the escaping scenario. I also considered using `template.HTMLEscapeString`, but I'm unsure where to properly implement that. Is there a recommended way to ensure that my custom function outputs are correctly escaped in templates? I'm using Go version 1.19.1. Any insights or best practices would be greatly appreciated! What's the best practice here?