I want to create a CRUD rest API to manage casts using Gorm and Gin. When I add a relation between two of my models, I cannot create a cast because of that converting the string ID to a struct type.
My Models:
type Cast struct {
ID string `sql:"type:uuid;primary_key;default:uuid_generate_v4()"`
FullName string `gorm:"size:150;not null" json:"full_name"`
NickNames string `gorm:"size:250;null;" json:"nick_names"`
BornLocation Country `gorm:"many2many:CastBornLocation;association_foreignkey:ID;foreignkey:ID" json:"born_location"`
Nationalities []Country `gorm:"many2many:Castnationalities;association_foreignkey:ID;foreignkey:ID" json:"cast_nationalities"`
MiniBio string `gorm:"size:1000;null;" json:"mini_bio"`
}
type Country struct {
ID string `sql:"type:uuid;primary_key;default:uuid_generate_v4()"`
Title string `gorm:"size:100;not null" json:"title"`
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
}
And here is the controller:
func (server *Server) CreateCast(c *gin.Context) {
errList = map[string]string{}
body, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
errList["Invalid_body"] = "Unable to get request"
c.JSON(http.StatusUnprocessableEntity, gin.H{
"status": http.StatusUnprocessableEntity,
"error": errList,
})
return
}
item := models.Cast{}
err = json.Unmarshal(body, &item)
if err != nil {
fmt.Println("---------------------------------")
fmt.Println(err)
fmt.Println("---------------------------------")
errList["Unmarshal_error"] = "Cannot unmarshal body"
c.JSON(http.StatusUnprocessableEntity, gin.H{
"status": http.StatusUnprocessableEntity,
"error": errList,
})
return
}
...
And this is the JSON body I'm submitting to the API:
{
"full_name": "Cast fullname",
"nick_names": "nickname1, nickname2",
"born_location": "01346a2e-ae50-45aa-8b3e-a66748a76955",
"Nationalities": [
"c370aa49-b39d-4797-a096-094b84903f27",
"01346a2e-ae50-45aa-8b3e-a66748a76955"
],
"mini_bio": "this is the mini bio of the cast"
}
And this is the full printed error:
json: cannot unmarshal string into Go struct field Cast.born_location of type models.Country
You can not unmarshal string into Struct type. BornLocation
is country struct type but you are sending the only id of string type in JSON. Same for Nationalities
. Try to send id in id node inside of the object to map with your struct.
{
"full_name": "Cast fullname",
"nick_names": "nickname1, nickname2",
"born_location": {
"id" :"01346a2e-ae50-45aa-8b3e-a66748a76955"
}
"Nationalities": [
{
"id" :"c370aa49-b39d-4797-a096-094b84903f27"
},
{
"id" :"01346a2e-ae50-45aa-8b3e-a66748a76955"
}
],
"mini_bio": "this is the mini bio of the cast"
}
Or create another struct for your request body to map your current JSON.