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")
}
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?