Escape Strings Before They Reach HTML

Neutralize user-controlled text before it reaches HTML: EscapeString turns angle brackets and quotes into entities, and UnescapeString restores them.

GoSecurity Boundaries

Code

snippet
package main

import (
	"fmt"
	"html"
)

func main() {
	// User-controlled text concatenated straight into an HTML page is executed as markup
	comment := `<script>alert("xss")</script> & "quotes" 'apostrophes'`

	// EscapeString turns < > & ' " into entities: the browser renders them as plain text
	fmt.Println(html.EscapeString(comment))

	// UnescapeString reverses entities back into characters
	escaped := "Tom &amp; Jerry &lt;3"
	fmt.Println(html.UnescapeString(escaped))

	// Escaping grows the string: lengths of the original, once-escaped, and double-escaped forms
	single := html.EscapeString(comment)
	double := html.EscapeString(single)
	fmt.Println("orig:", len(comment), "escaped:", len(single), "double:", len(double))
}

The flow inside the file

Escape Strings Before They Reach HTML comes down to the function main.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Signature: func main()

Running the file prints labeled results such as orig: — each operation’s effect is visible in the output.

Key statements

single := html.EscapeString(comment)

Interactive Tools for This Topic

FAQ

What does Escape Strings Before They Reach HTML print when run?
Run it as a complete program — the output lines carry labels such as `orig:`.