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.
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)
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?