How do I validate JSON payloads with custom rules in Go?

In Go, you can validate JSON payloads using custom rules by unmarshalling the JSON into a struct and then implementing validation logic either in the struct methods or as separate validation functions.

Here’s an example of how to validate JSON payloads using custom rules:

package main import ( "encoding/json" "fmt" "log" ) type User struct { Name string `json:"name"` Age int `json:"age"` Email string `json:"email"` } func (u *User) Validate() error { if u.Name == "" { return fmt.Errorf("name cannot be empty") } if u.Age < 0 { return fmt.Errorf("age cannot be negative") } if u.Email == "" || !isValidEmail(u.Email) { return fmt.Errorf("invalid email") } return nil } func isValidEmail(email string) bool { // Simplistic email validation return len(email) > 5 && len(email) < 255 } func main() { jsonPayload := `{"name": "Alice", "age": 30, "email": "alice@example.com"}` var user User if err := json.Unmarshal([]byte(jsonPayload), &user); err != nil { log.Fatalf("Error unmarshalling JSON: %v", err) } if err := user.Validate(); err != nil { log.Fatalf("Validation error: %v", err) } fmt.Println("User is valid") }

JSON validation Go programming custom validation rules Go structs JSON unmarshalling