Sobes.tech
Middle

What is XSS (Cross-Site Scripting) and how to combat it?

sobes.tech AI

Answer from AI

XSS (Cross-Site Scripting) is a vulnerability in web applications where an attacker injects malicious scripts (usually JavaScript) into pages viewed by other users. This allows stealing sessions, impersonating user actions, or executing other attacks.

To combat XSS in Go and web development in general:

  • Always escape user input when outputting to HTML. In Go, you can use the html/template package, which automatically escapes data.
  • Use Content Security Policy (CSP) — a header that restricts script execution.
  • Validate and filter input data.
  • Avoid inserting user data directly into HTML, JavaScript, or attributes.

Example of safe output using html/template:

package main

import (
    "html/template"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    tmpl := template.Must(template.New("page").Parse(`<div>{{.}}</div>`))
    userInput := r.URL.Query().Get("input")
    tmpl.Execute(w, userInput) // automatically escapes
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Thus, XSS is prevented through proper escaping and security policies.