How to Implement Input Validation and Sanitization in Go

Prevent security vulnerabilities in Go by using html/template for automatic escaping and filepath.IsLocal or os.OpenRoot for safe file access.

Use html/template for automatic HTML escaping and filepath.IsLocal or os.OpenRoot for path validation to prevent injection and traversal attacks.

package main

import (
	"html/template"
	"os"
	"path/filepath"
)

func main() {
	// Sanitize HTML output
	tmpl := template.Must(template.New("safe").Parse("<p>{{.}}</p>"))
	tmpl.Execute(os.Stdout, "<script>alert('xss')</script>")

	// Validate file paths
	if !filepath.IsLocal("../../etc/passwd") {
		return // Reject traversal attempt
	}

	// Or use traversal-resistant root
	root, _ := os.OpenRoot("/safe/dir")
	defer root.Close()
	f, _ := root.Open("file.txt") // Safe from symlinks and ..
}