php editor Xinyi brings you a solution to the problem of errors when binding form data in the Golang GIN framework. When using the GIN framework for form data binding, you sometimes encounter some problems, such as the inability to parse the form data correctly. These problems may be caused by parameter binding, data type mismatch, etc. This article will introduce how to correctly bind form data and solve common errors to help developers successfully use the GIN framework for development work.
When I try to bind a form data request to a structure, it errors out with "Fatal Error: Stack Overflow".
This is my code. There's nothing to explain. I'm getting started with the code but can't figure it out.
Structure
type Wish struct { ID int `gorm:"primarykey;autoIncrement" json:"id"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at"` UserID int `json:"user_id" form:"user_id"` User *User `gorm:"foreignKey:UserID" json:"user_data,omitempty"` WishTypeID int `json:"wish_type_id" form:"wish_type_id"` WishType *WishType `gorm:"foreignKey:WishTypeID" json:"wish_type_data,omitempty"` ProcessTrack []*ProcessTrack `gorm:"foreignKey:WishID" json:"process_track,omitempty"` VacationDateRange *VacationDateRange `gorm:"foreignKey:WishID" json:"vacation_date_range,omitempty"` Content string `gorm:"type:varchar(255)" json:"content" form:"content"` Status WishStatus `gorm:"type:integer" json:"status" form:"status"` Files []*File `gorm:"polymorphic:Module;polymorphicValue:wish_files" json:"files,omitempty"` }
Controller
var wish migrations.Wish if err := c.Bind(&wish); err != nil { c.JSON(400, gin.H{"error": err.Error(), "message": "Talep Okunamadı!"}) return } c.JSON(200, wish) return
Request
I modified the controller
type Req struct { Content string `form:"content"` WishTypeID int `form:"wish_type_id"` VacationDateRange *migrations.VacationDateRange `form:"vacation_date_range"` } err, i, g := authorizer.AuthorizeIt(c, a.Subject, a.Action) if err != nil { c.JSON(i, g) return } var wishReq Req var wish migrations.Wish if err := c.Bind(&wishReq); err != nil { c.JSON(400, gin.H{"error": err.Error(), "message": "Wish can't bind."}) return } wish.WishTypeID = wishReq.WishTypeID wish.Content = wishReq.Content wish.VacationDateRange = wishReq.VacationDateRange
But I still don't understand why it can't be the first style. I've also added common usage. It usually works too.
err, i, g := authorizer.AuthorizeIt(c, a.Subject, a.Action) if err != nil { c.JSON(i, g) return } var announce mig.Announce err = c.Bind(&announce) if err != nil { c.JSON(400, gin.H{"error": err.Error(), "message": "Announce can't bind. Error Code: AN-CRT-20"}) return }
The above is the detailed content of Golang GIN error when binding form data. For more information, please follow other related articles on the PHP Chinese website!