I have managed to output text using the following line:
fmt.Fprintf(w, "<p>some text</p>")
But this will literally output the HTML tags. How do you output it so it can safely be included in HTML like you would with echo
in PHP?
I have managed to output text using the following line:
fmt.Fprintf(w, "<p>some text</p>")
But this will literally output the HTML tags. How do you output it so it can safely be included in HTML like you would with echo
in PHP?
fmt.Fprintf()
has no knowledge of HTML syntax: it outputs raw data without escaping it (it may do some formatting but that is not escaping).
You don't use it correctly though: its second parameter is a format string, so you should call it rather like this:
fmt.Fprintf(w, "%s", "<p>some text</p>")
Else if your text contains some format-specific special characters, you will not get the expected result.
What you want is to escape HTML code so it can be safely included in HTML documents/pages. For that you get excellent support from the html/template
package which provides you a powerful template engine where automatic escaping functionality being just one feature.
Here's a simple example how to achieve what you want:
w := os.Stdout
text := "<p>some text</p>"
fmt.Fprintf(w, "%s
", text)
tt := `{{.}}`
t := template.Must(template.New("test").Parse(tt))
t.Execute(w, text)
Output (try it on the Go Playground):
<p>some text</p>
<p>some text</p>
Also note that if you only want to escape some HTML code, there is a template.HTMLEscaper()
function for that:
fmt.Println(template.HTMLEscaper(text))
Output:
<p>some text</p>