I need to do an Update for a table on PG. The request have some columns or fields in the table. First Bind the request to an instance, but when I get the entity from DB then delete all data from request. I prefer to validate the data of the structure before obtaining the data from the database.
package main
import (
"log"
"bitbucket.org/company/app/controllers"
"bitbucket.org/company/gobase/rest"
)
func main() {
server, routes := rest.NewServer(prefixPath)
routes.POST("/data/:id", controllers.Update)
}
The model
type Data struct {
tableName struct{} `sql:"data"`
ID int `sql:"id,pk" json:"id"`
CreatedAt time.Time `sql:"created_at" json:"created_at"`
Column1 string `sql:"column1" json:"column1"`
Column2 string `sql:"column2" json:"column2"`
Column3 time.Time `sql:"column3" json:"column3"`
}
The Controller:
func Update(c echo.Context) (err error) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return c.JSON(http.StatusBadRequest, err)
}
data := Data{}
if err = c.Bind(&data); err != nil {
return c.JSON(http.StatusBadRequest, err)
}
err := db().Table("data").
Where("id = ?", id).
Select(&data)
if err != nil {
return c.JSON(http.StatusNotFound, err)
}
, err := db(data).
Where("id = ?", data.ID).
Update(data)
if err != nil {
return c.JSON(http.StatusInternalServerError, err)
}
return c.JSON(http.StatusOK, userSocial)
}
If I look for the entity in the bd first and then I Bind the request to the entity, it works perfectly, it only updates the request fields. But I prefer to validate the structure of the request before searching the database.