How do I sanitize and validate struct fields in Go?

In Go, sanitizing and validating struct fields is essential for ensuring data integrity and security. This is especially important when dealing with user input that can lead to vulnerabilities such as injection attacks. Here’s how you can effectively sanitize and validate struct fields in Go.

Example of Struct Validation and Sanitization

package main import ( "fmt" "regexp" "strings" ) type User struct { Name string `validate:"required"` Email string `validate:"required,email"` } func isValidEmail(email string) bool { re := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$`) return re.MatchString(email) } func sanitizeString(input string) string { return strings.TrimSpace(input) // Basic sanitization } func validateUser(user User) error { user.Name = sanitizeString(user.Name) user.Email = sanitizeString(user.Email) if user.Name == "" { return fmt.Errorf("name is required") } if !isValidEmail(user.Email) { return fmt.Errorf("invalid email format") } return nil } func main() { user := User{ Name: " John Doe ", Email: " johndoe@example.com ", } if err := validateUser(user); err != nil { fmt.Println("Error:", err) } else { fmt.Println("User is valid:", user) } }

Go struct validation sanitize struct fields Go user input validation Go data integrity