How do you escape raw HTML in Go? -
i have managed output text using following line:
fmt.fprintf(w, "<p>some text</p>")
but literally output html tags. how output can safely included in html echo
in php?
fmt.fprintf()
has no knowledge of html syntax: outputs raw data without escaping (it may formatting not escaping).
you don't use correctly though: second parameter format string, should call rather this:
fmt.fprintf(w, "%s", "<p>some text</p>")
else if text contains format-specific special characters, not expected result.
what want escape html code can safely included in html documents/pages. excellent support html/template
package provides powerful template engine automatic escaping functionality being 1 feature.
here's simple example how achieve want:
w := os.stdout text := "<p>some text</p>" fmt.fprintf(w, "%s\n", text) tt := `{{.}}` t := template.must(template.new("test").parse(tt)) t.execute(w, text)
output (try on go playground):
<p>some text</p> <p>some text</p>
also note if want escape html code, there template.htmlescaper()
function that:
fmt.println(template.htmlescaper(text))
output:
<p>some text</p>
Comments
Post a Comment