GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Gorilla

XSS in APIs occurs when untrusted input is reflected in the response body without a strict Content-Type or proper encoding. In Gorilla-based services, if you fail to explicitly define your response headers, modern browsers might 'sniff' the content and execute embedded scripts if they find HTML-like tags. As a researcher, I see this most often when developers reflect parameters directly into a string response.

The Vulnerable Pattern

func VulnerableHandler(w http.ResponseWriter, r *http.Request) {
    // DANGER: No Content-Type set. If 'name' contains 

The fix involves three critical layers. First, we set 'Content-Type: application/json', instructing the browser to treat the body as data. Second, we apply 'X-Content-Type-Options: nosniff' to prevent the browser from ignoring the Content-Type and executing the payload as HTML. Finally, we use Go's 'encoding/json' package, which automatically escapes characters like '<', '>', and '&' into their Unicode equivalents (e.g., \u003c), neutralizing any script injection attempts even if the browser misinterprets the response.

func SecureHandler(w http.ResponseWriter, r *http.Request) {
    name := r.URL.Query().Get("name")
    data := map[string]string{"user": name}
// 1. Explicitly set JSON content type
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// 2. Prevent MIME-sniffing
w.Header().Set("X-Content-Type-Options", "nosniff")

w.WriteHeader(http.StatusOK)
// 3. Use json.NewEncoder which escapes HTML characters by default
json.NewEncoder(w).Encode(data)

}

System Alert • ID: 7135
Target: API Responses API
Potential Vulnerability

Your API Responses API might be exposed to XSS

74% of API Responses apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.