Validate untrusted input and encode output
Validate untrusted input and encode output
Every boundary that accepts data from a client, file or other service needs a contract. Check size, type and business rules before using a value. A label in this example is 1–24 ASCII characters: lowercase letters, digits or hyphens. This is an application rule, not a universal rule for names.
package main
import ( "fmt")
func validLabel(s string) bool { if len(s) < 1 || len(s) > 24 { return false } for _, r := range s { if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') { return false } } return true}func main() { fmt.Println(validLabel("blue-7"), validLabel(""), validLabel("Blue"))}Validation rejects data outside the domain rather than silently changing it. Bound input before parsing or allocation. Free-form text needs different rules; rejecting every non-ASCII character would exclude legitimate names. A validated value is not automatically safe in every output context.
Expected output:
true false falseEncode for the output context
package main
import ( "bytes" "fmt" ht "html/template")
func render(s string) string { t := ht.Must(ht.New("label").Parse(`<p>{{.}}</p>`)) var b bytes.Buffer if e := t.Execute(&b, s); e != nil { panic(e) } return b.String()}func main() { fmt.Println(render("Tea & biscuits"))}html/template treats normal data as text and escapes it according to the surrounding template context. Keep the template itself trusted. Do not mark user data as template.HTML or substitute text/template for HTML generation. SQL parameters and JSON serialization are separate contexts with different rules.
Expected output:
<p>Tea & biscuits</p>Try it locally
Test a 24-character label, a 25-character label and a label with a space.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Security engineering 01: Validate untrusted input and encode output
Check the lesson objective before moving on.
Why validate before processing?
Which package should render trusted HTML templates with ordinary untrusted data?