213 r.ParseForm()
214 username := r.Form.Get("username")
215 if !isValidUsername(username) {
216 fmt.Fprintf(w, "%q is an unknown user", username)217 }
218 })
219 http.ListenAndServe(":8080", nil)
Directly writing a user-defined HTTP request parameter (e.g., username) to an HTTP response without adequately sanitizing the input first allows for a cross-site scripting vulnerability. To guard against cross-site scripting, consider escaping the input or sanitizing the input.
func handleUser() {
http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
username := r.Form.Get("username")
// NOTE: username is directly written to the HTTP response
// without sanitizing.
fmt.Fprintf(w, "user: %q", username)
})
}
func handleUser() {
http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
username := r.Form.Get("username")
// NOTE: username is directly written to the HTTP response
// and escaped using html.EscapeString.
fmt.Fprintf(w, "user: %q", html.EscapeString(username))
})
}