---
title: Output Encoding Before Interpreter Use
impact: HIGH
impactDescription: prevents XSS and injection attacks
tags: xss, encoding, output, html, security
---

## Output Encoding Before Interpreter Use

XSS and injection attacks occur when unescaped user data is interpreted by browsers or other systems.

**Incorrect (no encoding):**

```go
// XSS vulnerability
http.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
    query := r.URL.Query().Get("q")
    fmt.Fprintf(w, "<h1>Results for: %s</h1>", query) // XSS!
})
```

**Correct (context-aware encoding):**

```go
import "html"

// HTML context
http.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
    query := r.URL.Query().Get("q")
    // html.EscapeString escapes <, >, &, ', "
    fmt.Fprintf(w, "<h1>Results for: %s</h1>", html.EscapeString(query))
})

// Using html/template (auto-escapes by default)
tmpl := template.Must(template.New("res").Parse("<h1>Results for: {{.}}</h1>"))
tmpl.Execute(w, query)

// URL context
safeURL := url.QueryEscape(userInput)
```

**Encoding by Context:**

| Context | Encoding |
|---------|----------|
| HTML body | `html.EscapeString()` |
| URL | `url.QueryEscape()` |
| JSON | `json.Marshal()` |

**Tools:** SonarQube, Semgrep, `html/template` (enforced escaping)
