How to Prevent XSS and CSRF in Go Web Applications

Prevent CSRF by using net/http.CrossOriginProtection and stop XSS by escaping user input with html.EscapeString.

Use the new net/http CrossOriginProtection middleware to block CSRF and sanitize output to prevent XSS.

import "net/http"

func main() {
    // 1. Prevent CSRF: Reject non-safe cross-origin requests
    cop := http.NewCrossOriginProtection()
    cop.AddTrustedOrigin("https://your-trusted-domain.com")
    cop.SetDenyHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        http.Error(w, "Forbidden", http.StatusForbidden)
    }))

    // 2. Prevent XSS: Always escape user input before writing to response
    mux := http.NewServeMux()
    mux.HandleFunc("/form", func(w http.ResponseWriter, r *http.Request) {
        if err := cop.Check(r); err != nil {
            cop.ServeHTTP(w, r) // Calls the deny handler
            return
        }
        // Escape user input to prevent XSS
        userInput := r.FormValue("name")
        fmt.Fprintf(w, "Hello, %s", html.EscapeString(userInput))
    })

    http.ListenAndServe(":8080", mux)
}

In Go 1.25+, CrossOriginProtection automatically rejects unsafe cross-origin POST/PUT/DELETE requests based on Sec-Fetch-Site headers, while html.EscapeString neutralizes XSS payloads in HTML responses.