0
votes

Here is my code snippet I'm trying to pass language_id along with book create call somehow I'm getting an error

func Create(c *gin.Context) {
    dbb := c.MustGet("db").(*gorm.DB)
    book := Models.BookModel{
        Title:  c.PostForm("title"),
        Author: c.PostForm("author"),
        LanguageID: c.PostForm("language_id"),
    }

    dbb.Save(&book)
    c.JSON(http.StatusCreated, gin.H{"status": http.StatusCreated, "message": "Book created successfully!", "bookId": book.ID})
}

error is Cannot use 'c.PostForm("language_id")' (type string) as type int any help that would be great thanks!

1
Please add the error toobitcodr
Err is here. c.PostForm only accepts a string. LanguageID: c.PostForm("language_id"), Cannot use 'c.PostForm("language_id")' (type string) as type int deepu

1 Answers

1
votes

The problem is the LanguageID is an int type and you wanna pass a string value to it, you should parse it to int like:

func Create(c *gin.Context) {
dbb := c.MustGet("db").(*gorm.DB)

languageID, err := strconv.Atoi(c.PostForm("language_id"))
 if err != nil {
    fmt.Println(err)
    return
}

book := Models.BookModel{
    Title:  c.PostForm("title"),
    Author: c.PostForm("author"),
    LanguageID: languageID,
}

dbb.Save(&book)
c.JSON(http.StatusCreated, gin.H{"status": http.StatusCreated, "message": "Book created successfully!", "bookId": book.ID})
}