How to Escape the Html in Go
Created
Modified
Using EscapeString Function
The html.EscapeString()
function escapes special characters like "<" to become "<". It escapes only five such characters: <, >, &, ' and ".
The following example should cover whatever you are trying to do:
package main
import (
"fmt"
"html"
)
func main() {
s := "<script>alert(1);</script>"
s = html.EscapeString(s)
fmt.Println(s)
}
<script>alert(1);</script>
Using HTMLEscapeString Funcion
The template.HTMLEscapeString()
function returns the escaped HTML equivalent of the plain text data s. For example,
package main
import (
"fmt"
"text/template"
)
func main() {
s := "<script>alert(1);</script>"
s = template.HTMLEscapeString(s)
fmt.Println(s)
}
<script>alert(1);</script>