📌  相关文章
📜  escape html golang - Go 编程语言(1)

📅  最后修改于: 2023-12-03 15:00:37.523000             🧑  作者: Mango

Escape HTML in Go

HTML is a markup language used to display content in web browsers. However, HTML can also be used to inject malicious scripts that can be used to steal data, compromise user security or damage systems.

To prevent such attacks, it is important to escape HTML in input data. Escaping HTML means replacing special characters with their corresponding HTML entities. In Go, this can be achieved using the 'html' package.

html.EscapeString()

html.EscapeString() is a function that escapes special characters in a given string, such as the '<', '>', '&' and '"' symbols. This function returns a new string with escaped HTML entities.

import "html"

func main() {
    data := "<script>alert('hello');</script>"
    escapedData := html.EscapeString(data)
    fmt.Println(escapedData)
}

Output:

&lt;script&gt;alert('hello');&lt;/script&gt;
Safe HTML

Sometimes, it is desirable to allow certain HTML tags in input data, such as links or text formatting tags. In this case, the 'html/template' package can be used to allow only specific HTML tags.

template.HTMLEscaper() is a function that escapes special characters in a given string, much like html.EscapeString(). However, template.HTMLEscaper() also allows certain HTML tags to remain unescaped.

import "html/template"

func main() {
    data := "<a href='https://example.com'>link</a>"
    t := template.New("example")
    t = t.Funcs(template.FuncMap{"safe": func(s string) template.HTML { return template.HTML(s) }})
    t, _ = t.Parse("{{. | safe}}")
    t.Execute(os.Stdout, template.HTML(data))
}

Output:

<a href='https://example.com'>link</a>

In the above example, the 'safe' function is defined to allow HTML tags to remain unescaped. The func(s string) template.HTML signature of the safe function is defined to return an HTML type. This type indicates to the template engine that the output should not be escaped.

Conclusion

Escaping HTML is an important security measure to protect web applications from attacks such as Cross-Site Scripting (XSS). Go provides a simple way to escape HTML using the 'html' package. To allow certain HTML tags, the 'html/template' package can be used instead.