liveBook · Manning

HTML escaping

As explained in Learn Go with Pocket-Sized Projects

HTML escaping transforms characters with special meaning in HTML into safe representations that are treated as text rather than markup or code.

HTML escaping converts characters with special meaning, such as &, <, and >, into representations rendered as text instead of markup or executable code. Go’s html/template applies this protection automatically when rendering HTML. section 11.1.2

Protecting a rendered value

A template value such as "</html>" should remain text rather than terminate the page; escaping also helps prevent malicious JavaScript from executing. Use html/template for HTML output instead of text/template. section 11.1.2

Listing 11.10 index.html: Outputting a variable
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Learn Go</title>
</head>
<body>
<h1>Habits</h1>
<p>You have {{.}} habits to follow.</p> #1
</body>
</html>

See how a dynamic value is inserted into an HTML document through the {{.}} template action. section 11.1.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains automatic escaping and injection prevention, but does not detail escaping algorithms or context-specific rules.
Examples
Demonstrates rendering a variable and protecting values such as "</html>" or malicious JavaScript.
What it assumes
Assumes template-based rendering and distinguishes HTML templates from general text templates.
What you can do after
Apply it via Go’s html/template library when generating HTML containing dynamic or untrusted values.
How it connects
Connects HTML escaping with templates, text/template, HTML, XML, and code injection.

Also explained in

Compare how 3 books explain HTML escaping →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.