binding
andmsg
It is a struct tag, mainly used for data verification and error message prompts. They are usually associated with the Gin frameworkShouldBindJSON
Use with it, and for handling form verification.
The following is a detailed explanation:
Basic usage examples:
type LoginForm struct { Username string `json:"username" binding:"required" msg:"Username cannot be empty"` Password string `json:"password" binding:"required,min=6" msg:"Password cannot be empty and has at least length6Bit"` Age int `json:"age" binding:"required,gte=18" msg:"Age must be greater than or equal to18age"` Email string `json:"email" binding:"required,email" msg:"Please enter a valid email address"` }
Use in Gin:
func Login(c *) { var form LoginForm if err := (&form); err != nil { (400, {"error": ()}) return } // Handle login logic...}
Commonly used binding verification rules:
type User struct { // required: Required Name string `binding:"required"` // min,max: string length or number range Password string `binding:"min=6,max=20"` // email: Email format Email string `binding:"email"` // oneof: Enumeration value Role string `binding:"oneof=admin user guest"` // gte,lte: greater than or equal to, less than or equal to Age int `binding:"gte=18,lte=100"` // url: URL format Website string `binding:"url"` // Regular expression Phone string `binding:"required,regexp=^1[3-9]\\d{9}$"` }
Custom Verifier:
type RegisterForm struct { Password string `binding:"required,CustomPassword"` Phone string `binding:"required,CustomPhone"` } func customValidator() { if v, ok := ().(*); ok { // Register a custom validator ("CustomPassword", ValidatePassword) ("CustomPhone", ValidatePhone) } } func ValidatePassword(fl ) bool { password := ().String() // Custom password verification logic return len(password) >= 8 }
Use the msg tag to customize the error message:
type CreateUserForm struct { Username string `json:"username" binding:"required" msg:"Username cannot be empty"` Password string `json:"password" binding:"required,min=6" msg:"Minimum password length6Bit"` } // Helper function for handling error messagesfunc getValidMsg(err error, obj interface{}) string { // Get struct type by reflection getObj := (obj) // If it is a pointer, get its base type if () == { getObj = () } // Convert error message to validator error if errs, ok := err.(); ok { // traverse every error for _, e := range errs { // Get the corresponding field if f, exist := (()); exist { // Get the msg tag content msg := ("msg") if msg != "" { return msg } } } } return () }
Use in the controller:
func CreateUser(c *) { var form CreateUserForm if err := (&form); err != nil { // Get custom error message errMsg := getValidMsg(err, form) (400, {"error": errMsg}) return } // Handle business logic...}
Combination verification rules:
type Product struct { // Multiple verification rules are separated by commas Name string `binding:"required,min=2,max=50" msg:"The product name must be in2-50between"` Price float64 `binding:"required,gte=0" msg:"The price must be greater than or equal to0"` // Condition verification: Description is required when Status is "active". Status string `binding:"required,oneof=active inactive" msg:"The status must be active or inactive"` Description string `binding:"required_if=Status active" msg:"When the status isactivehour,Required description"` }
Cross-field verification:
type ChangePassword struct { Password string `binding:"required" msg:"Password cannot be empty"` ConfirmPassword string `binding:"required,eqfield=Password" msg:"The passwords entered twice are inconsistent"` }
Initialize the validator:
func InitValidator() { // Register a validator if v, ok := ().(*); ok { // Register a custom validator ("custom_validation", CustomValidationFunc) // Register a custom error message translator (v, trans) } }
These tags are mainly used for:
- Data verification (binding)
- Custom error message (msg)
- Parameter binding
- Form Verification
- API interface parameter verification
By using these tags reasonably, you can:
- Reduce manual verification code writing
- Provide more friendly error prompts
- Ensure the integrity and effectiveness of data
- Improve code maintainability
This is the article about binding and msg structure labels in gorm structures. For more related contents of gorm binding and msg structure labels, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!